code
stringlengths
17
247k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
public function dontRequireField($table, $fieldName) { $fieldList = $this->fieldList($table); if (array_key_exists($fieldName, $fieldList ?? [])) { $suffix = ''; while (isset($fieldList[strtolower("_obsolete_{$fieldName}$suffix")])) { $suffix = $suffix ? ((int)$suffix + 1) : 2; } $this->renameField($table, $fieldName, "_obsolete_{$fieldName}$suffix"); $this->alterationMessage( "Field $table.$fieldName: renamed to $table._obsolete_{$fieldName}$suffix", "obsolete" ); } }
If the given field exists, move it out of the way by renaming it to _obsolete_(fieldname). @param string $table @param string $fieldName
dontRequireField
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function fixTableCase($tableName) { // Check if table exists $tables = $this->tableList(); if (!array_key_exists(strtolower($tableName ?? ''), $tables ?? [])) { return; } // Check if case differs $currentName = $tables[strtolower($tableName)]; if ($currentName === $tableName) { return; } $this->alterationMessage( "Table $tableName: renamed from $currentName", 'repaired' ); // Rename via temp table to avoid case-sensitivity issues $tempTable = "__TEMP__{$tableName}"; $this->renameTable($currentName, $tempTable); $this->renameTable($tempTable, $tableName); }
Ensure the given table has the correct case @param string $tableName Name of table in desired case
fixTableCase
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function clearCachedFieldlist($tableName = null) { return true; }
This allows the cached values for a table's field list to be erased. If $tablename is empty, then the whole cache is erased. @param string $tableName @return boolean
clearCachedFieldlist
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBSchemaManager.php
BSD-3-Clause
public function __construct($database, $handle) { $this->handle = $handle; if (is_object($this->handle)) { $this->columns = $this->handle->fetch_fields(); } }
Hook the result-set given into a Query class, suitable for use by SilverStripe. @param MySQLiConnector $database The database object that created this query. @param mixed $handle the internal mysql handle that is points to the resultset. Non-mysqli_result values could be given for non-select queries (e.g. true)
__construct
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLQuery.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLQuery.php
BSD-3-Clause
public function __construct($statement, $metadata) { $this->statement = $statement; $this->metadata = $metadata; // Immediately bind and buffer $this->bind(); }
Hook the result-set given into a Query class, suitable for use by SilverStripe. @param mysqli_stmt $statement The related statement, if present @param mysqli_result $metadata The metadata for this statement
__construct
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLStatement.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLStatement.php
BSD-3-Clause
protected function bind() { $variables = []; // Bind each field while ($field = $this->metadata->fetch_field()) { $this->columns[] = $field->name; $this->types[$field->name] = $field->type; // Note that while boundValues isn't initialised at this point, // later calls to $this->statement->fetch() Will populate // $this->boundValues later with the next result. $variables[] = &$this->boundValues[$field->name]; } $this->bound = true; $this->metadata->free(); // Buffer all results $this->statement->store_result(); call_user_func_array([$this->statement, 'bind_result'], $variables ?? []); }
Binds this statement to the variables
bind
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLStatement.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLStatement.php
BSD-3-Clause
public function selectTimezone($timezone) { if (empty($timezone)) { return; } $this->preparedQuery("SET SESSION time_zone = ?", [$timezone]); }
Sets the system timezone for the database connection @param string $timezone
selectTimezone
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLDatabase.php
BSD-3-Clause
protected function getTransactionManager() { if (!$this->transactionManager) { $this->transactionManager = new NestedTransactionManager(new MySQLTransactionManager($this)); } return $this->transactionManager; }
Returns the TransactionManager to handle transactions for this database. @return TransactionManager
getTransactionManager
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLDatabase.php
BSD-3-Clause
protected function resetTransactionNesting() { // Check whether to use a connector's built-in transaction methods if ($this->connector instanceof TransactionalDBConnector) { if ($this->transactionNesting > 0) { $this->connector->transactionRollback(); } } $this->transactionNesting = 0; }
In error condition, set transactionNesting to zero
resetTransactionNesting
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLDatabase.php
BSD-3-Clause
protected function inspectQuery($sql) { // Any DDL discards transactions. // See https://dev.mysql.com/doc/internals/en/transactions-notes-on-ddl-and-normal-transaction.html // on why we need to be over-eager $isDDL = $this->getConnector()->isQueryDDL($sql); if ($isDDL) { $this->resetTransactionNesting(); } }
Inspect a SQL query prior to execution @param string $sql
inspectQuery
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLDatabase.php
BSD-3-Clause
protected function setLastStatement($statement) { $this->lastStatement = $statement; }
Store the most recent statement for later use @param mysqli_stmt $statement
setLastStatement
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLiConnector.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLiConnector.php
BSD-3-Clause
public function prepareStatement($sql, &$success) { // Record last statement for error reporting $statement = $this->dbConn->stmt_init(); $this->setLastStatement($statement); try { $success = $statement->prepare($sql); } catch (mysqli_sql_exception $e) { $success = false; $this->throwRelevantError($e->getMessage(), $e->getCode(), E_USER_ERROR, $sql, []); } if (!$success || $statement->error) { $this->throwRelevantError($this->getLastError(), $this->getLastErrorCode(), E_USER_ERROR, $sql, []); } return $statement; }
Retrieve a prepared statement for a given SQL string @param string $sql @param boolean $success (by reference) @return mysqli_stmt
prepareStatement
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLiConnector.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLiConnector.php
BSD-3-Clause
protected function beforeQuery($sql) { // Clear the last statement $this->setLastStatement(null); }
Invoked before any query is executed @param string $sql
beforeQuery
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLiConnector.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLiConnector.php
BSD-3-Clause
public function parsePreparedParameters($parameters, &$blobs) { $types = ''; $values = []; $blobs = []; $parametersCount = count($parameters ?? []); for ($index = 0; $index < $parametersCount; $index++) { $value = $parameters[$index]; $phpType = gettype($value); // Allow overriding of parameter type using an associative array if ($phpType === 'array') { $phpType = $value['type']; $value = $value['value']; } // Convert php variable type to one that makes mysqli_stmt_bind_param happy // @see http://www.php.net/manual/en/mysqli-stmt.bind-param.php switch ($phpType) { case 'boolean': case 'integer': $types .= 'i'; break; case 'float': // Not actually returnable from gettype case 'double': $types .= 'd'; break; case 'object': // Allowed if the object or resource has a __toString method case 'resource': case 'string': case 'NULL': // Take care that a where clause should use "where XX is null" not "where XX = null" $types .= 's'; break; case 'blob': $types .= 'b'; // Blobs must be sent via send_long_data and set to null here $blobs[] = [ 'index' => $index, 'value' => $value ]; $value = null; break; case 'array': case 'unknown type': default: throw new \InvalidArgumentException( "Cannot bind parameter \"$value\" as it is an unsupported type ($phpType)" ); } $values[] = $value; } return array_merge([$types], $values); }
Prepares the list of parameters in preparation for passing to mysqli_stmt_bind_param @param array $parameters List of parameters @param array $blobs Out parameter for list of blobs to bind separately (by reference) @return array List of parameters appropriate for mysqli_stmt_bind_param function
parsePreparedParameters
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLiConnector.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLiConnector.php
BSD-3-Clause
public function bindParameters(mysqli_stmt $statement, array $parameters) { // Because mysqli_stmt::bind_param arguments must be passed by reference // we need to do a bit of hackery $boundNames = []; $parametersCount = count($parameters ?? []); for ($i = 0; $i < $parametersCount; $i++) { $boundName = "param$i"; $$boundName = $parameters[$i]; $boundNames[] = &$$boundName; } $statement->bind_param(...$boundNames); }
Binds a list of parameters to a statement @param mysqli_stmt $statement MySQLi statement @param array $parameters List of parameters to pass to bind_param
bindParameters
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLiConnector.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLiConnector.php
BSD-3-Clause
public function __construct(TransactionManager $child) { $this->child = $child; }
Create a NestedTransactionManager @param TransactionManager $child The transaction manager that will handle the topmost transaction
__construct
php
silverstripe/silverstripe-framework
src/ORM/Connect/NestedTransactionManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/NestedTransactionManager.php
BSD-3-Clause
public function transactionDepth() { return $this->transactionNesting; }
Return the depth of the transaction. @return int
transactionDepth
php
silverstripe/silverstripe-framework
src/ORM/Connect/NestedTransactionManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/NestedTransactionManager.php
BSD-3-Clause
public function isQueryMutable($sql) { $operations = array_merge( Config::inst()->get(static::class, 'write_operations'), Config::inst()->get(static::class, 'ddl_operations') ); return $this->isQueryType($sql, $operations); }
Determine if this SQL statement is a destructive operation (write or ddl) @param string $sql @return bool
isQueryMutable
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBConnector.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBConnector.php
BSD-3-Clause
public function isQueryDDL($sql) { $operations = Config::inst()->get(static::class, 'ddl_operations'); return $this->isQueryType($sql, $operations); }
Determine if this SQL statement is a DDL operation @param string $sql @return bool
isQueryDDL
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBConnector.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBConnector.php
BSD-3-Clause
public function isQueryWrite($sql) { $operations = Config::inst()->get(static::class, 'write_operations'); return $this->isQueryType($sql, $operations); }
Determine if this SQL statement is a write operation (alters content but not structure) @param string $sql @return bool
isQueryWrite
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBConnector.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBConnector.php
BSD-3-Clause
protected function isQueryType($sql, $type) { if (!preg_match('/^(?<operation>\w+)\b/', $sql ?? '', $matches)) { return false; } $operation = $matches['operation']; if (is_array($type)) { return in_array(strtolower($operation ?? ''), $type ?? []); } return strcasecmp($sql ?? '', $type ?? '') === 0; }
Determine if a query is of the given type @param string $sql Raw SQL @param string|array $type Type or list of types (first word in the query). Must be lowercase @return bool
isQueryType
php
silverstripe/silverstripe-framework
src/ORM/Connect/DBConnector.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/DBConnector.php
BSD-3-Clause
protected function runTableCheckCommand($sql) { $testResults = $this->query($sql); foreach ($testResults as $testRecord) { if (strtolower($testRecord['Msg_text'] ?? '') != 'ok') { return false; } } return true; }
Helper function used by checkAndRepairTable. @param string $sql Query to run. @return boolean Returns if the query returns a successful result.
runTableCheckCommand
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function alterField($tableName, $fieldName, $fieldSpec) { $this->query("ALTER TABLE \"$tableName\" CHANGE \"$fieldName\" \"$fieldName\" $fieldSpec"); }
Change the database type of the given field. @param string $tableName The name of the tbale the field is in. @param string $fieldName The name of the field to change. @param string $fieldSpec The new field specification
alterField
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function renameField($tableName, $oldName, $newName) { $fieldList = $this->fieldList($tableName); if (array_key_exists($oldName, $fieldList ?? [])) { $this->query("ALTER TABLE \"$tableName\" CHANGE \"$oldName\" \"$newName\" " . $fieldList[$oldName]); } }
Change the database column name of the given field. @param string $tableName The name of the tbale the field is in. @param string $oldName The name of the field to change. @param string $newName The new name of the field
renameField
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function createIndex($tableName, $indexName, $indexSpec) { $this->query("ALTER TABLE \"$tableName\" ADD " . $this->getIndexSqlDefinition($indexName, $indexSpec)); }
Create an index on a table. @param string $tableName The name of the table. @param string $indexName The name of the index. @param string $indexSpec The specification of the index, see {@link SS_Database::requireIndex()} for more details.
createIndex
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
protected function getIndexSqlDefinition($indexName, $indexSpec) { if ($indexSpec['type'] == 'using') { return sprintf('index "%s" using (%s)', $indexName, $this->implodeColumnList($indexSpec['columns'])); } else { return sprintf('%s "%s" (%s)', $indexSpec['type'], $indexName, $this->implodeColumnList($indexSpec['columns'])); } }
Generate SQL suitable for creating this index @param string $indexName @param string|array $indexSpec See {@link requireTable()} for details @return string MySQL compatible ALTER TABLE syntax
getIndexSqlDefinition
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function boolean($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'tinyint', 'precision'=>1, 'sign'=>'unsigned', 'null'=>'not null', //'default'=>$this->default); //DB::requireField($this->tableName, $this->name, "tinyint(1) unsigned not null default //'{$this->defaultVal}'"); $width = $this->shouldUseIntegerWidth() ? '(1)' : ''; return 'tinyint' . $width . ' unsigned not null' . $this->defaultClause($values); }
Return a boolean type-formatted string @param array $values Contains a tokenised list of info about this data type @return string
boolean
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function date($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'date'); //DB::requireField($this->tableName, $this->name, "date"); return 'date'; }
Return a date type-formatted string For MySQL, we simply return the word 'date', no other parameters are necessary @param array $values Contains a tokenised list of info about this data type @return string
date
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function decimal($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'decimal', 'precision'=>"$this->wholeSize,$this->decimalSize"); //DB::requireField($this->tableName, $this->name, "decimal($this->wholeSize,$this->decimalSize)"); // Avoid empty strings being put in the db if ($values['precision'] == '') { $precision = 1; } else { $precision = $values['precision']; } // Fix format of default value to match precision if (isset($values['default']) && is_numeric($values['default'])) { $decs = strpos($precision ?? '', ',') !== false ? (int) substr($precision, strpos($precision, ',') + 1) : 0; $values['default'] = number_format($values['default'] ?? 0.0, $decs ?? 0, '.', ''); } else { unset($values['default']); } return "decimal($precision) not null" . $this->defaultClause($values); }
Return a decimal type-formatted string @param array $values Contains a tokenised list of info about this data type @return string
decimal
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function enum($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'enum', 'enums'=>$this->enum, 'character set'=>'utf8', 'collate'=> // 'utf8_general_ci', 'default'=>$this->default); //DB::requireField($this->tableName, $this->name, "enum('" . implode("','", $this->enum) . "') character set // utf8 collate utf8_general_ci default '{$this->default}'"); $valuesString = implode(",", Convert::raw2sql($values['enums'], true)); $charset = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'charset'); $collation = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'collation'); return "enum($valuesString) character set {$charset} collate {$collation}" . $this->defaultClause($values); }
Return a enum type-formatted string @param array $values Contains a tokenised list of info about this data type @return string
enum
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function set($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'enum', 'enums'=>$this->enum, 'character set'=>'utf8', 'collate'=> // 'utf8_general_ci', 'default'=>$this->default); //DB::requireField($this->tableName, $this->name, "enum('" . implode("','", $this->enum) . "') character set //utf8 collate utf8_general_ci default '{$this->default}'"); $valuesString = implode(",", Convert::raw2sql($values['enums'], true)); $charset = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'charset'); $collation = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'collation'); return "set($valuesString) character set {$charset} collate {$collation}" . $this->defaultClause($values); }
Return a set type-formatted string @param array $values Contains a tokenised list of info about this data type @return string
set
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function float($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'float'); //DB::requireField($this->tableName, $this->name, "float"); return "float not null" . $this->defaultClause($values); }
Return a float type-formatted string For MySQL, we simply return the word 'date', no other parameters are necessary @param array $values Contains a tokenised list of info about this data type @return string
float
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function int($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'int', 'precision'=>11, 'null'=>'not null', 'default'=>(int)$this->default); //DB::requireField($this->tableName, $this->name, "int(11) not null default '{$this->defaultVal}'"); $width = $this->shouldUseIntegerWidth() ? '(11)' : ''; return 'int' . $width . ' not null' . $this->defaultClause($values); }
Return a int type-formatted string @param array $values Contains a tokenised list of info about this data type @return string
int
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function bigint($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'bigint', 'precision'=>20, 'null'=>'not null', 'default'=>$this->defaultVal, // 'arrayValue'=>$this->arrayValue); //$values=Array('type'=>'bigint', 'parts'=>$parts); //DB::requireField($this->tableName, $this->name, $values); $width = $this->shouldUseIntegerWidth() ? '(20)' : ''; return 'bigint' . $width . ' not null' . $this->defaultClause($values); }
Return a bigint type-formatted string @param array $values Contains a tokenised list of info about this data type @return string
bigint
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function datetime($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'datetime'); //DB::requireField($this->tableName, $this->name, $values); return 'datetime'; }
Return a datetime type-formatted string For MySQL, we simply return the word 'datetime', no other parameters are necessary @param array $values Contains a tokenised list of info about this data type @return string
datetime
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function text($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'mediumtext', 'character set'=>'utf8', 'collate'=>'utf8_general_ci'); //DB::requireField($this->tableName, $this->name, "mediumtext character set utf8 collate utf8_general_ci"); $charset = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'charset'); $collation = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'collation'); return 'mediumtext character set ' . $charset . ' collate ' . $collation . $this->defaultClause($values); }
Return a text type-formatted string @param array $values Contains a tokenised list of info about this data type @return string
text
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function time($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'time'); //DB::requireField($this->tableName, $this->name, "time"); return 'time'; }
Return a time type-formatted string For MySQL, we simply return the word 'time', no other parameters are necessary @param array $values Contains a tokenised list of info about this data type @return string
time
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
public function varchar($values) { //For reference, this is what typically gets passed to this function: //$parts=Array('datatype'=>'varchar', 'precision'=>$this->size, 'character set'=>'utf8', 'collate'=> //'utf8_general_ci'); //DB::requireField($this->tableName, $this->name, "varchar($this->size) character set utf8 collate // utf8_general_ci"); $default = $this->defaultClause($values); $charset = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'charset'); $collation = Config::inst()->get('SilverStripe\ORM\Connect\MySQLDatabase', 'collation'); return "varchar({$values['precision']}) character set {$charset} collate {$collation}{$default}"; }
Return a varchar type-formatted string @param array $values Contains a tokenised list of info about this data type @return string
varchar
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
protected function defaultClause($values) { if (isset($values['default'])) { return ' default ' . $this->database->quoteString($values['default']); } return ''; }
Parses and escapes the default values for a specification @param array $values Contains a tokenised list of info about this data type @return string Default clause
defaultClause
php
silverstripe/silverstripe-framework
src/ORM/Connect/MySQLSchemaManager.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/MySQLSchemaManager.php
BSD-3-Clause
protected function isDBTemp($name) { $prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_'; $result = preg_match( sprintf('/^%stmpdb_[0-9]+_[0-9]+$/i', preg_quote($prefix ?? '', '/')), $name ?? '' ); return $result === 1; }
Check if the given name matches the temp_db pattern @param string $name @return bool
isDBTemp
php
silverstripe/silverstripe-framework
src/ORM/Connect/TempDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/TempDatabase.php
BSD-3-Clause
public function isUsed() { $selected = $this->getConn()->getSelectedDatabase(); return $this->isDBTemp($selected); }
Returns true if we are currently using a temporary database @return bool
isUsed
php
silverstripe/silverstripe-framework
src/ORM/Connect/TempDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/TempDatabase.php
BSD-3-Clause
public function startTransaction() { if (static::getConn()->supportsTransactions()) { static::getConn()->transactionStart(); } }
Start a transaction for easy rollback after tests
startTransaction
php
silverstripe/silverstripe-framework
src/ORM/Connect/TempDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/TempDatabase.php
BSD-3-Clause
public function rollbackTransaction() { // Ensure a rollback can be performed $success = static::getConn()->supportsTransactions() && static::getConn()->transactionDepth(); if (!$success) { return false; } try { // Explicit false = gnostic error from transactionRollback if (static::getConn()->transactionRollback() === false) { return false; } return true; } catch (DatabaseException $ex) { return false; } }
Rollback a transaction (or trash all data if the DB doesn't support databases @return bool True if successfully rolled back, false otherwise. On error the DB is killed and must be re-created. Note that calling rollbackTransaction() when there is no transaction is counted as a failure, user code should either kill or flush the DB as necessary
rollbackTransaction
php
silverstripe/silverstripe-framework
src/ORM/Connect/TempDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/TempDatabase.php
BSD-3-Clause
public function kill() { // Nothing to kill if (!$this->isUsed()) { return; } // Rollback any transactions (note: Success ignored) $this->rollbackTransaction(); // Check the database actually exists $dbConn = $this->getConn(); $dbName = $dbConn->getSelectedDatabase(); if (!$dbConn->databaseExists($dbName)) { return; } // Some DataExtensions keep a static cache of information that needs to // be reset whenever the database is killed foreach (ClassInfo::subclassesFor(DataExtension::class) as $class) { $toCall = [$class, 'on_db_reset']; if (is_callable($toCall)) { call_user_func($toCall); } } $dbConn->dropSelectedDatabase(); }
Destroy the current temp database
kill
php
silverstripe/silverstripe-framework
src/ORM/Connect/TempDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/TempDatabase.php
BSD-3-Clause
public function clearAllData() { if (!$this->isUsed()) { return; } $this->getConn()->clearAllData(); // Some DataExtensions keep a static cache of information that needs to // be reset whenever the database is cleaned out $classes = array_merge( ClassInfo::subclassesFor(DataExtension::class), ClassInfo::subclassesFor(DataObject::class) ); foreach ($classes as $class) { $toCall = [$class, 'on_db_reset']; if (is_callable($toCall)) { call_user_func($toCall); } } }
Remove all content from the temporary database.
clearAllData
php
silverstripe/silverstripe-framework
src/ORM/Connect/TempDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/TempDatabase.php
BSD-3-Clause
public function build() { // Disable PHPUnit error handling $oldErrorHandler = set_error_handler(null); // Create a temporary database, and force the connection to use UTC for time $dbConn = $this->getConn(); $prefix = Environment::getEnv('SS_DATABASE_PREFIX') ?: 'ss_'; do { $dbname = strtolower(sprintf('%stmpdb_%s_%s', $prefix, time(), rand(1000000, 9999999))); } while ($dbConn->databaseExists($dbname)); $dbConn->selectDatabase($dbname, true); $this->resetDBSchema(); // Reinstate PHPUnit error handling set_error_handler($oldErrorHandler); // Ensure test db is killed on exit $teardownOnExit = Config::inst()->get(static::class, 'teardown_on_exit'); if ($teardownOnExit) { register_shutdown_function(function () { try { $this->kill(); } catch (Exception $ex) { // An exception thrown while trying to remove a test database shouldn't fail a build, ignore } }); } return $dbname; }
Create temp DB without creating extra objects @return string DB name
build
php
silverstripe/silverstripe-framework
src/ORM/Connect/TempDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/TempDatabase.php
BSD-3-Clause
public function deleteAll() { $schema = $this->getConn()->getSchemaManager(); foreach ($schema->databaseList() as $dbName) { if ($this->isDBTemp($dbName)) { $schema->dropDatabase($dbName); $schema->alterationMessage("Dropped database \"$dbName\"", 'deleted'); flush(); } } }
Clear all temp DBs on this connection Note: This will output results to stdout unless suppressOutput is set on the current db schema
deleteAll
php
silverstripe/silverstripe-framework
src/ORM/Connect/TempDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/TempDatabase.php
BSD-3-Clause
public function resetDBSchema(array $extraDataObjects = []) { // Skip if no DB if (!$this->isUsed()) { return; } try { $this->rebuildTables($extraDataObjects); } catch (DatabaseException $ex) { // Avoid infinite loops if ($this->skippedException && $this->skippedException->getMessage() == $ex->getMessage()) { throw $ex; } $this->skippedException = $ex; // In case of error during build force a hard reset // e.g. pgsql doesn't allow schema updates inside transactions $this->kill(); $this->build(); $this->rebuildTables($extraDataObjects); $this->skippedException = null; } }
Reset the testing database's schema. @param array $extraDataObjects List of extra dataobjects to build
resetDBSchema
php
silverstripe/silverstripe-framework
src/ORM/Connect/TempDatabase.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Connect/TempDatabase.php
BSD-3-Clause
public function __construct( DataObject $rootNode, $childrenMethod = null, $numChildrenMethod = null, $nodeCountThreshold = null, $maxChildNodes = null ) { if (! $rootNode::has_extension(Hierarchy::class)) { throw new InvalidArgumentException( get_class($rootNode) . " does not have the Hierarchy extension" ); } $this->rootNode = $rootNode; if ($childrenMethod) { $this->setChildrenMethod($childrenMethod); } if ($numChildrenMethod) { $this->setNumChildrenMethod($numChildrenMethod); } if ($nodeCountThreshold) { $this->setNodeCountThreshold($nodeCountThreshold); } if ($maxChildNodes) { $this->setMaxChildNodes($maxChildNodes); } }
Create an empty set with the given class @param DataObject $rootNode Root node for this set. To collect the entire tree, pass in a singleton object. @param string $childrenMethod Override children method @param string $numChildrenMethod Override children counting method @param int $nodeCountThreshold Minimum threshold for number nodes to mark @param int $maxChildNodes Maximum threshold for number of child nodes to include
__construct
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function getNodeCountThreshold() { return $this->nodeCountThreshold ?: $this->rootNode->config()->get('node_threshold_total'); }
Get total number of nodes to get. This acts as a soft lower-bounds for number of nodes to search until found. Defaults to value of node_threshold_total of hierarchy class. @return int
getNodeCountThreshold
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function getMaxChildNodes() { return $this->maxChildNodes ?: $this->rootNode->config()->get('node_threshold_leaf'); }
Max number of nodes that can be physically rendered at any level. Acts as a hard upper bound, after which nodes will be trimmed for performance reasons. @return int
getMaxChildNodes
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function setMaxChildNodes($count) { $this->maxChildNodes = $count; return $this; }
Set hard limit of number of nodes to get for this level @param int $count @return $this
setMaxChildNodes
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function getChildrenMethod() { return $this->childrenMethod ?: 'AllChildrenIncludingDeleted'; }
Get method to use for getting children @return string
getChildrenMethod
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function setChildrenMethod($method) { // Check method is valid if (!$this->rootNode->hasMethod($method)) { throw new InvalidArgumentException(sprintf( "Can't find the method '%s' on class '%s' for getting tree children", $method, get_class($this->rootNode) )); } $this->childrenMethod = $method; return $this; }
Set method to use for getting children @param string $method @throws InvalidArgumentException @return $this
setChildrenMethod
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function getNumChildrenMethod() { return $this->numChildrenMethod ?: 'numChildren'; }
Get method name for num children @return string
getNumChildrenMethod
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function setNumChildrenMethod($method) { // Check method is valid if (!$this->rootNode->hasMethod($method)) { throw new InvalidArgumentException(sprintf( "Can't find the method '%s' on class '%s' for counting tree children", $method, get_class($this->rootNode) )); } $this->numChildrenMethod = $method; return $this; }
Set method name to get num children @param string $method @return $this
setNumChildrenMethod
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function renderChildren( $template = null, $context = [] ) { // Default to HTML template if (!$template) { $template = [ 'type' => 'Includes', MarkedSet::class . '_HTML' ]; } $tree = $this->getSubtree($this->rootNode, 0); $node = $this->renderSubtree($tree, $template, $context); return (string)$node->getField('SubTree'); }
Returns the children of this DataObject as an XHTML UL. This will be called recursively on each child, so if they have children they will be displayed as a UL inside a LI. @param string $template Template for items in the list @param array|callable $context Additional arguments to add to template when rendering due to excessive line length. If callable, this will be executed with the current node dataobject @return string
renderChildren
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function getChildrenAsArray($serialiseEval = null) { if (!$serialiseEval) { $serialiseEval = function ($data) { /** @var DataObject $node */ $node = $data['node']; return [ 'id' => $node->ID, 'title' => $node->getTitle() ]; }; } $tree = $this->getSubtree($this->rootNode, 0); return $this->getSubtreeAsArray($tree, $serialiseEval); }
Get child data formatted as JSON @param callable $serialiseEval A callback that takes a DataObject as a single parameter, and should return an array containing a simple array representation. This result will replace the 'node' property at each point in the tree. @return array
getChildrenAsArray
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function setMarkingFilter($parameterName, $parameterValue) { $this->markingFilter = [ "parameter" => $parameterName, "value" => $parameterValue ]; return $this; }
Filter the marking to only those object with $node->$parameterName == $parameterValue @param string $parameterName The parameter on each node to check when marking. @param mixed $parameterValue The value the parameter must be to be marked. @return $this
setMarkingFilter
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function setMarkingFilterFunction($callback) { $this->markingFilter = [ "func" => $callback, ]; return $this; }
Filter the marking to only those where the function returns true. The node in question will be passed to the function. @param callable $callback Callback to filter @return $this
setMarkingFilterFunction
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
protected function markingFilterMatches(DataObject $node) { if (!$this->markingFilter) { return true; } // Func callback filter if (isset($this->markingFilter['func'])) { $func = $this->markingFilter['func']; return call_user_func($func, $node); } // Check object property filter if (isset($this->markingFilter['parameter'])) { $parameterName = $this->markingFilter['parameter']; $value = $this->markingFilter['value']; if (is_array($value)) { return in_array($node->$parameterName, $value ?? []); } else { return $node->$parameterName == $value; } } throw new LogicException("Invalid marking filter"); }
Returns true if the marking filter matches on the given node. @param DataObject $node Node to check @return bool
markingFilterMatches
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
protected function markingClasses($node) { $classes = []; if (!$this->isExpanded($node)) { $classes[] = 'unexpanded'; } // Set jstree open state, or mark it as a leaf (closed) if there are no children if (!$this->getNumChildren($node)) { // No children $classes[] = "jstree-leaf closed"; } elseif ($this->isTreeOpened($node)) { // Open with children $classes[] = "jstree-open"; } else { // Closed with children $classes[] = "jstree-closed closed"; } return implode(' ', $classes); }
Return CSS classes of 'unexpanded', 'closed', both, or neither, as well as a 'jstree-*' state depending on the marking of this DataObject. @param DataObject $node @return string
markingClasses
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function markById($id, $open = false) { if (isset($this->markedNodes[$id])) { $this->markChildren($this->markedNodes[$id]); if ($open) { $this->markOpened($this->markedNodes[$id]); } return true; } else { return false; } }
Mark the children of the DataObject with the given ID. @param int $id ID of parent node @param bool $open If this is true, mark the parent node as opened @return bool
markById
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function markedNodeIDs() { return array_keys($this->markedNodes ?? []); }
Return the IDs of all the marked nodes. @refactor called from CMSMain @return array
markedNodeIDs
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function markExpanded(DataObject $node) { $id = $node->ID ?: 0; $this->markedNodes[$id] = $node; $this->expanded[$id] = true; return $this; }
Mark this DataObject as expanded. @param DataObject $node @return $this
markExpanded
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function markUnexpanded(DataObject $node) { $id = $node->ID ?: 0; $this->markedNodes[$id] = $node; unset($this->expanded[$id]); return $this; }
Mark this DataObject as unexpanded. @param DataObject $node @return $this
markUnexpanded
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function markOpened(DataObject $node) { $id = $node->ID ?: 0; $this->markedNodes[$id] = $node; $this->treeOpened[$id] = true; return $this; }
Mark this DataObject's tree as opened. @param DataObject $node @return $this
markOpened
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function markClosed(DataObject $node) { $id = $node->ID ?: 0; $this->markedNodes[$id] = $node; unset($this->treeOpened[$id]); return $this; }
Mark this DataObject's tree as closed. @param DataObject $node @return $this
markClosed
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function isMarked(DataObject $node) { $id = $node->ID ?: 0; return !empty($this->markedNodes[$id]); }
Check if this DataObject is marked. @param DataObject $node @return bool
isMarked
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function isExpanded(DataObject $node) { $id = $node->ID ?: 0; return !empty($this->expanded[$id]); }
Check if this DataObject is expanded. An expanded object has had it's children iterated through. @param DataObject $node @return bool
isExpanded
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function isTreeOpened(DataObject $node) { $id = $node->ID ?: 0; return !empty($this->treeOpened[$id]); }
Check if this DataObject's tree is opened. This is an expanded node which also should have children visually shown. @param DataObject $node @return bool
isTreeOpened
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
protected function isNodeLimited(DataObject $node, $count = null) { // Singleton root node isn't limited if (!$node->ID) { return false; } // Check if limiting is enabled first if (!$this->getLimitingEnabled()) { return false; } // Count children for this node and compare to max if (!isset($count)) { $count = $this->getNumChildren($node); } return $count > $this->getMaxChildNodes(); }
Check if this node has too many children @param DataObject|Hierarchy $node @param int $count Children count (if already calculated) @return bool
isNodeLimited
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/MarkedSet.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/MarkedSet.php
BSD-3-Clause
public function validate(ValidationResult $validationResult) { Deprecation::notice('5.4.0', 'Will be renamed to updateValidate()'); // The object is new, won't be looping. $owner = $this->owner; if (!$owner->ID) { return; } // The object has no parent, won't be looping. if (!$owner->ParentID) { return; } // The parent has not changed, skip the check for performance reasons. if (!$owner->isChanged('ParentID')) { return; } // Walk the hierarchy upwards until we reach the top, or until we reach the originating node again. $node = $owner; while ($node && $node->ParentID) { if ((int)$node->ParentID === (int)$owner->ID) { // Hierarchy is looping. $validationResult->addError( _t( __CLASS__ . '.InfiniteLoopNotAllowed', 'Infinite loop found within the "{type}" hierarchy. Please change the parent to resolve this', 'First argument is the class that makes up the hierarchy.', ['type' => get_class($owner)] ), 'bad', 'INFINITE_LOOP' ); break; } $node = $node->Parent(); } }
Validate the owner object - check for existence of infinite loops. @param ValidationResult $validationResult @deprecated 5.4.0 Will be renamed to updateValidate()
validate
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function getDescendantIDList() { $idList = []; $this->loadDescendantIDListInto($idList); return $idList; }
Get a list of this DataObject's and all it's descendants IDs. @return int[]
getDescendantIDList
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
protected function loadDescendantIDListInto(&$idList, $node = null) { if (!$node) { $node = $this->owner; } $children = $node->AllChildren(); foreach ($children as $child) { if (!in_array($child->ID, $idList ?? [])) { $idList[] = $child->ID; $this->loadDescendantIDListInto($idList, $child); } } }
Get a list of this DataObject's and all it's descendants ID, and put them in $idList. @param array $idList Array to put results in. @param DataObject|Hierarchy $node
loadDescendantIDListInto
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function Children() { $children = $this->owner->_cache_children; if ($children) { return $children; } $children = $this ->owner ->stageChildren(false) ->filterByCallback(function (DataObject $record) { return $record->canView(); }); $this->owner->_cache_children = $children; return $children; }
Get the children for this DataObject filtered by canView() @return SS_List<DataObject&static>
Children
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function AllChildren() { return $this->owner->stageChildren(true); }
Return all children, including those 'not in menus'. @return DataList<DataObject&static>
AllChildren
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function AllChildrenIncludingDeleted() { /** @var DataObject|Hierarchy|Versioned $owner */ $owner = $this->owner; $stageChildren = $owner->stageChildren(true); // Add live site content that doesn't exist on the stage site, if required. if ($owner->hasExtension(Versioned::class) && $owner->hasStages()) { // Next, go through the live children. Only some of these will be listed $liveChildren = $owner->liveChildren(true, true); if ($liveChildren) { $merged = new ArrayList(); $merged->merge($stageChildren); $merged->merge($liveChildren); $stageChildren = $merged; } } $owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren); return $stageChildren; }
Return all children, including those that have been deleted but are still in live. - Deleted children will be marked as "DeletedFromStage" - Added children will be marked as "AddedToStage" - Modified children will be marked as "ModifiedOnStage" - Everything else has "SameOnStage" set, as an indicator that this information has been looked up. @return ArrayList<DataObject&static>
AllChildrenIncludingDeleted
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function AllHistoricalChildren() { /** @var DataObject|Versioned|Hierarchy $owner */ $owner = $this->owner; if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) { throw new Exception( 'Hierarchy->AllHistoricalChildren() only works with Versioned extension applied with staging' ); } $baseTable = $owner->baseTable(); $parentIDColumn = $owner->getSchema()->sqlColumnForField($owner, 'ParentID'); return Versioned::get_including_deleted( $owner->baseClass(), [ $parentIDColumn => $owner->ID ], "\"{$baseTable}\".\"ID\" ASC" ); }
Return all the children that this page had, including pages that were deleted from both stage & live. @return DataList<DataObject&static> @throws Exception
AllHistoricalChildren
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function numHistoricalChildren() { return $this->AllHistoricalChildren()->count(); }
Return the number of children that this page ever had, including pages that were deleted. @return int
numHistoricalChildren
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function numChildren($cache = true) { $baseClass = $this->owner->baseClass(); $cacheType = 'numChildren'; $id = $this->owner->ID; // cached call if ($cache) { if (isset(Hierarchy::$cache_numChildren[$baseClass][$cacheType][$id])) { return Hierarchy::$cache_numChildren[$baseClass][$cacheType][$id]; } elseif (isset(Hierarchy::$cache_numChildren[$baseClass][$cacheType]['_complete'])) { // If the cache is complete and we didn't find our ID in the cache, it means this object is childless. return 0; } } // We call stageChildren(), because Children() has canView() filtering $numChildren = (int)$this->owner->stageChildren(true)->Count(); // Save if caching if ($cache) { Hierarchy::$cache_numChildren[$baseClass][$cacheType][$id] = $numChildren; } return $numChildren; }
Return the number of direct children. By default, values are cached after the first invocation. Can be augmented by {@link augmentNumChildrenCountQuery()}. @param bool $cache Whether to retrieve values from cache @return int
numChildren
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function prepopulateTreeDataCache($recordList = null, array $options = []) { if (empty($options['numChildrenMethod']) || $options['numChildrenMethod'] === 'numChildren') { $idList = is_array($recordList) ? $recordList : ($recordList instanceof DataList ? $recordList->column('ID') : null); Hierarchy::prepopulate_numchildren_cache($this->getHierarchyBaseClass(), $idList); } $this->owner->extend('onPrepopulateTreeDataCache', $recordList, $options); }
Pre-populate any appropriate caches prior to rendering a tree. This is used to allow for the efficient rendering of tree views, notably in the CMS. In the case of Hierarchy, it caches numChildren values. Other extensions can provide an onPrepopulateTreeDataCache(DataList $recordList = null, array $options) methods to hook into this event as well. @param DataList|array $recordList The list of records to prepopulate caches for. Null for all records. @param array $options A map of hints about what should be cached. "numChildrenMethod" and "childrenMethod" are allowed keys.
prepopulateTreeDataCache
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public static function prepopulate_numchildren_cache($baseClass, $idList = null) { if (!Config::inst()->get(static::class, 'prepopulate_numchildren_cache')) { return; } /** @var DataObject&static $dummyObject */ $dummyObject = DataObject::singleton($baseClass); $baseTable = $dummyObject->baseTable(); $idColumn = Convert::symbol2sql("{$baseTable}.ID"); // Get the stageChildren() result of a dummy object and break down into a generic query $query = $dummyObject->stageChildren(true, true)->dataQuery()->query(); // optional ID-list filter if ($idList) { // Validate the ID list foreach ($idList as $id) { if (!is_numeric($id)) { throw new \InvalidArgumentException( "Bad ID passed to Versioned::prepopulate_numchildren_cache() in \$idList: " . $id ); } } $query->addWhere(['"ParentID" IN (' . DB::placeholders($idList) . ')' => $idList]); } $query->setOrderBy(null); $query->setSelect([ '"ParentID"', "COUNT(DISTINCT $idColumn) AS \"NumChildren\"", ]); $query->setGroupBy([Convert::symbol2sql("ParentID")]); $numChildren = $query->execute()->map(); Hierarchy::$cache_numChildren[$baseClass]['numChildren'] = $numChildren; if (!$idList) { // If all objects are being cached, mark this cache as complete // to avoid counting children of childless object. Hierarchy::$cache_numChildren[$baseClass]['numChildren']['_complete'] = true; } }
Pre-populate the cache for Versioned::get_versionnumber_by_stage() for a list of record IDs, for more efficient database querying. If $idList is null, then every record will be pre-cached. @param string $baseClass @param array $idList
prepopulate_numchildren_cache
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function showingCMSTree() { if (!Controller::has_curr() || !class_exists(LeftAndMain::class)) { return false; } $controller = Controller::curr(); return $controller instanceof LeftAndMain && in_array($controller->getAction(), ["treeview", "listview", "getsubtree"]); }
Checks if we're on a controller where we should filter. ie. Are we loading the SiteTree? @return bool
showingCMSTree
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function stageChildren($showAll = false, $skipParentIDFilter = false) { $owner = $this->owner; $hideFromHierarchy = $owner->config()->hide_from_hierarchy; $hideFromCMSTree = $owner->config()->hide_from_cms_tree; $class = $this->getHierarchyBaseClass(); $schema = DataObject::getSchema(); $tableForParentID = $schema->tableForField($class, 'ParentID'); $tableForID = $schema->tableForField($class, 'ID'); $staged = DataObject::get($class)->where(sprintf( '%s.%s <> %s.%s', Convert::symbol2sql($tableForParentID), Convert::symbol2sql("ParentID"), Convert::symbol2sql($tableForID), Convert::symbol2sql("ID") )); if (!$skipParentIDFilter) { // There's no filtering by ID if we don't have an ID. $staged = $staged->filter('ParentID', (int)$this->owner->ID); } if ($hideFromHierarchy) { $staged = $staged->exclude('ClassName', $hideFromHierarchy); } if ($hideFromCMSTree && $this->showingCMSTree()) { $staged = $staged->exclude('ClassName', $hideFromCMSTree); } if (!$showAll && DataObject::getSchema()->fieldSpec($this->owner, 'ShowInMenus')) { $staged = $staged->filter('ShowInMenus', 1); } $this->owner->extend("augmentStageChildren", $staged, $showAll); return $staged; }
Return children in the stage site. @param bool $showAll Include all of the elements, even those not shown in the menus. Only applicable when extension is applied to {@link SiteTree}. @param bool $skipParentIDFilter Set to true to suppress the ParentID and ID where statements. @return DataList<DataObject&static>
stageChildren
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function liveChildren($showAll = false, $onlyDeletedFromStage = false) { /** @var Versioned|DataObject|Hierarchy $owner */ $owner = $this->owner; if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) { throw new Exception('Hierarchy->liveChildren() only works with Versioned extension applied with staging'); } $hideFromHierarchy = $owner->config()->hide_from_hierarchy; $hideFromCMSTree = $owner->config()->hide_from_cms_tree; $children = DataObject::get($this->getHierarchyBaseClass()) ->filter('ParentID', (int)$owner->ID) ->exclude('ID', (int)$owner->ID) ->setDataQueryParam([ 'Versioned.mode' => $onlyDeletedFromStage ? 'stage_unique' : 'stage', 'Versioned.stage' => 'Live' ]); if ($hideFromHierarchy) { $children = $children->exclude('ClassName', $hideFromHierarchy); } if ($hideFromCMSTree && $this->showingCMSTree()) { $children = $children->exclude('ClassName', $hideFromCMSTree); } if (!$showAll && DataObject::getSchema()->fieldSpec($owner, 'ShowInMenus')) { $children = $children->filter('ShowInMenus', 1); } return $children; }
Return children in the live site, if it exists. @param bool $showAll Include all of the elements, even those not shown in the menus. Only applicable when extension is applied to {@link SiteTree}. @param bool $onlyDeletedFromStage Only return items that have been deleted from stage @return DataList<DataObject&static> @throws Exception
liveChildren
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function getParent($filter = null) { $parentID = $this->owner->ParentID; if (empty($parentID)) { return null; } $baseClass = $this->owner->baseClass(); $idSQL = $this->owner->getSchema()->sqlColumnForField($baseClass, 'ID'); return DataObject::get_one($baseClass, [ [$idSQL => $parentID], $filter ]); }
Get this object's parent, optionally filtered by an SQL clause. If the clause doesn't match the parent, nothing is returned. @param string $filter @return DataObject&static
getParent
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function getAncestors($includeSelf = false) { $ancestors = new ArrayList(); $object = $this->owner; if ($includeSelf) { $ancestors->push($object); } while ($object = $object->getParent()) { $ancestors->push($object); } return $ancestors; }
Return all the parents of this class in a set ordered from the closest to furtherest parent. @param bool $includeSelf @return ArrayList<DataObject&static>
getAncestors
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
public function flushCache() { Deprecation::notice('5.4.0', 'Will be renamed to onFlushCache()'); $this->owner->_cache_children = null; Hierarchy::$cache_numChildren = []; }
Flush all Hierarchy caches: - Children (instance) - NumChildren (instance) @deprecated 5.4.0 Will be renamed to onFlushCache()
flushCache
php
silverstripe/silverstripe-framework
src/ORM/Hierarchy/Hierarchy.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Hierarchy/Hierarchy.php
BSD-3-Clause
protected function getMatchPattern($value) { return "%$value%"; }
Apply the match filter to the given variable value @param string $value The raw value @return string
getMatchPattern
php
silverstripe/silverstripe-framework
src/ORM/Filters/PartialMatchFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/PartialMatchFilter.php
BSD-3-Clause
public function apply(DataQuery $query) { if ($this->aggregate) { throw new InvalidArgumentException(sprintf( 'Aggregate functions can only be used with comparison filters. See %s', $this->fullName )); } return parent::apply($query); }
Apply filter criteria to a SQL query. @param DataQuery $query @return DataQuery
apply
php
silverstripe/silverstripe-framework
src/ORM/Filters/PartialMatchFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/PartialMatchFilter.php
BSD-3-Clause
protected function createSearchFilter($filter, $value) { // Field name is always the first component $fieldArgs = explode(':', $filter); $fieldName = array_shift($fieldArgs); $default = 'DataListFilter.default'; // Inspect type of second argument to determine context $secondArg = array_shift($fieldArgs); $modifiers = $fieldArgs; if (!$secondArg) { // Use default SearchFilter if none specified. E.g. `->filter(['Name' => $myname])` $filterServiceName = $default; } else { // The presence of a second argument is by default ambiguous; We need to query // Whether this is a valid modifier on the default filter, or a filter itself. /** @var SearchFilter $defaultFilterInstance */ $defaultFilterInstance = Injector::inst()->get($default); if (in_array(strtolower($secondArg), $defaultFilterInstance->getSupportedModifiers() ?? [])) { // Treat second (and any subsequent) argument as modifiers, using default filter $filterServiceName = $default; array_unshift($modifiers, $secondArg); } else { // Second argument isn't a valid modifier, so assume is filter identifier $filterServiceName = "DataListFilter.{$secondArg}"; } } // Build instance return Injector::inst()->create($filterServiceName, $fieldName, $value, $modifiers); }
Given a filter expression and value construct a {@see SearchFilter} instance @param string $filter E.g. `Name:ExactMatch:not`, `Name:ExactMatch`, `Name:not`, `Name` @param mixed $value Value of the filter @return SearchFilter
createSearchFilter
php
silverstripe/silverstripe-framework
src/ORM/Filters/SearchFilterable.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/SearchFilterable.php
BSD-3-Clause
public function getDbName() { $indexes = DataObject::getSchema()->databaseIndexes($this->model); if (array_key_exists($this->getName(), $indexes ?? [])) { $index = $indexes[$this->getName()]; } else { return parent::getDbName(); } if (is_array($index) && array_key_exists('columns', $index ?? [])) { return $this->prepareColumns($index['columns']); } else { throw new Exception(sprintf( "Invalid fulltext index format for '%s' on '%s'", var_export($this->getName(), true), var_export($this->model, true) )); } }
This implementation allows for a list of columns to be passed into MATCH() instead of just one. @example <code> MyDataObject::get()->filter('SearchFields:fulltext', 'search term') </code> @throws Exception @return string
getDbName
php
silverstripe/silverstripe-framework
src/ORM/Filters/FulltextFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/FulltextFilter.php
BSD-3-Clause
public function __construct($fullName = null, $value = false, array $modifiers = []) { $this->fullName = $fullName; // sets $this->name and $this->relation $this->addRelation($fullName); $this->addAggregate($fullName); $this->value = $value; $this->setModifiers($modifiers); }
@param string $fullName Determines the name of the field, as well as the searched database column. Can contain a relation name in dot notation, which will automatically join the necessary tables (e.g. "Comments.Name" to join the "Comments" has-many relationship and search the "Name" column when applying this filter to a SiteTree class). @param mixed $value @param array $modifiers
__construct
php
silverstripe/silverstripe-framework
src/ORM/Filters/SearchFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/SearchFilter.php
BSD-3-Clause
protected function addRelation($name) { if (strstr($name ?? '', '.')) { $parts = explode('.', $name ?? ''); $this->name = array_pop($parts); $this->relation = $parts; } else { $this->name = $name; } }
Called by constructor to convert a string pathname into a well defined relationship sequence. @param string $name
addRelation
php
silverstripe/silverstripe-framework
src/ORM/Filters/SearchFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/SearchFilter.php
BSD-3-Clause
protected function addAggregate($name) { if (!$this->relation) { return; } if (!preg_match('/([A-Za-z]+)\(\s*(?:([A-Za-z_*][A-Za-z0-9_]*))?\s*\)$/', $name ?? '', $matches)) { if (stristr($name ?? '', '(') !== false) { throw new InvalidArgumentException(sprintf( 'Malformed aggregate filter %s', $name )); } return; } $this->aggregate = [ 'function' => strtoupper($matches[1] ?? ''), 'column' => isset($matches[2]) ? $matches[2] : null ]; }
Parses the name for any aggregate functions and stores them in the $aggregate array @param string $name
addAggregate
php
silverstripe/silverstripe-framework
src/ORM/Filters/SearchFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/SearchFilter.php
BSD-3-Clause
public function setModel($className) { $this->model = ClassInfo::class_name($className); }
Set the root model class to be selected by this search query. @param string|DataObject $className
setModel
php
silverstripe/silverstripe-framework
src/ORM/Filters/SearchFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/SearchFilter.php
BSD-3-Clause
public function setModifiers(array $modifiers) { $modifiers = array_map('strtolower', $modifiers ?? []); // Validate modifiers are supported $allowed = $this->getSupportedModifiers(); $unsupported = array_diff($modifiers ?? [], $allowed); if ($unsupported) { throw new InvalidArgumentException( static::class . ' does not accept ' . implode(', ', $unsupported) . ' as modifiers' ); } $this->modifiers = $modifiers; }
Set the current modifiers to apply to the filter @param array $modifiers
setModifiers
php
silverstripe/silverstripe-framework
src/ORM/Filters/SearchFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/SearchFilter.php
BSD-3-Clause
public function getSupportedModifiers() { // By default support 'not' as a modifier for all filters return ['not']; }
Gets supported modifiers for this filter @return array
getSupportedModifiers
php
silverstripe/silverstripe-framework
src/ORM/Filters/SearchFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/SearchFilter.php
BSD-3-Clause
public function getFullName() { return $this->fullName; }
The full name passed to the constructor, including any (optional) relations in dot notation. @return string
getFullName
php
silverstripe/silverstripe-framework
src/ORM/Filters/SearchFilter.php
https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Filters/SearchFilter.php
BSD-3-Clause