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 shuffle()
{
return $this->orderBy(DB::get_conn()->random());
} | Shuffle the datalist using a random function provided by the SQL engine
@return static<T> | shuffle | php | silverstripe/silverstripe-framework | src/ORM/DataList.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataList.php | BSD-3-Clause |
public function add($item)
{
// Nothing needs to happen by default
// TO DO: If a filter is given to this data list then
} | This method are overloaded by HasManyList and ManyMany list to perform more sophisticated
list manipulation
@param DataObject|int $item | add | php | silverstripe/silverstripe-framework | src/ORM/DataList.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataList.php | BSD-3-Clause |
public function newObject($initialFields = null)
{
$class = $this->dataClass;
return Injector::inst()->create($class, $initialFields, false);
} | Return a new item to add to this DataList.
@param array $initialFields
@return T | newObject | php | silverstripe/silverstripe-framework | src/ORM/DataList.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataList.php | BSD-3-Clause |
public function remove($item)
{
// By default, we remove an item from a DataList by deleting it.
$this->removeByID($item->ID);
} | Remove this item by deleting it
@param DataObject $item | remove | php | silverstripe/silverstripe-framework | src/ORM/DataList.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataList.php | BSD-3-Clause |
public function removeByID($itemID)
{
$item = $this->byID($itemID);
if ($item) {
$item->delete();
}
} | Remove an item from this DataList by ID
@param int $itemID The primary ID | removeByID | php | silverstripe/silverstripe-framework | src/ORM/DataList.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataList.php | BSD-3-Clause |
public function getForeignClass()
{
return $this->dataQuery->getQueryParam('Foreign.Class');
} | Retrieve the name of the class this (has_many) relation is filtered by
@return class-string<TForeign> | getForeignClass | php | silverstripe/silverstripe-framework | src/ORM/PolymorphicHasManyList.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/PolymorphicHasManyList.php | BSD-3-Clause |
public function __construct($dataClass, $foreignField, $foreignClass)
{
// Set both id foreign key (as in HasManyList) and the class foreign key
parent::__construct($dataClass, "{$foreignField}ID");
$this->classForeignKey = "{$foreignField}Class";
$this->relationForeignKey = "{$foreignField}Relation";
// Ensure underlying DataQuery globally references the class filter
$this->dataQuery->setQueryParam('Foreign.Class', $foreignClass);
// For queries with multiple foreign IDs (such as that generated by
// DataList::relation) the filter must be generalised to filter by subclasses
$classNames = Convert::raw2sql(ClassInfo::subclassesFor($foreignClass));
$foreignClassColumn = DataObject::getSchema()->sqlColumnForField($dataClass, $this->classForeignKey);
$this->dataQuery->where(sprintf(
"$foreignClassColumn IN ('%s')",
implode("', '", $classNames)
));
} | Create a new PolymorphicHasManyList relation list.
@param class-string<T> $dataClass The class of the DataObjects that this will list.
@param string $foreignField The name of the composite foreign (has_one) relation field. Used
to generate the ID, Class, and Relation foreign keys.
@param class-string<TForeign> $foreignClass Name of the class filter this relation is filtered against | __construct | php | silverstripe/silverstripe-framework | src/ORM/PolymorphicHasManyList.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/PolymorphicHasManyList.php | BSD-3-Clause |
public function __construct($record = [], $creationType = DataObject::CREATE_OBJECT, $queryParams = [])
{
parent::__construct();
// Legacy $record default
if ($record === null) {
$record = [];
}
// Legacy $isSingleton boolean
if (!is_int($creationType)) {
if (!is_bool($creationType)) {
user_error('Creation type is neither boolean (old isSingleton arg) nor integer (new arg), please review your code', E_USER_WARNING);
}
$creationType = $creationType ? DataObject::CREATE_SINGLETON : DataObject::CREATE_OBJECT;
}
// Set query params on the DataObject to tell the lazy loading mechanism the context the object creation context
$this->setSourceQueryParams($queryParams);
// Set $this->record to $record, but ignore NULLs
$this->record = [];
switch ($creationType) {
// Hydrate a record
case DataObject::CREATE_HYDRATED:
case DataObject::CREATE_MEMORY_HYDRATED:
$this->hydrate($record, $creationType === DataObject::CREATE_HYDRATED);
break;
// Create a new object, using the constructor argument as the initial content
case DataObject::CREATE_OBJECT:
if ($record instanceof stdClass) {
$record = (array)$record;
}
if (!is_array($record)) {
if (is_object($record)) {
$passed = "an object of type '" . get_class($record) . "'";
} else {
$passed = "The value '$record'";
}
user_error(
"DataObject::__construct passed $passed. It's supposed to be passed an array,"
. " taken straight from the database. Perhaps you should use DataList::create()->First(); instead?",
E_USER_WARNING
);
$record = [];
}
// Default columns
$this->record['ID'] = empty($record['ID']) ? 0 : $record['ID'];
$this->record['ClassName'] = static::class;
$this->record['RecordClassName'] = static::class;
unset($record['ID']);
$this->original = $this->record;
$this->populateDefaults();
// prevent populateDefaults() and setField() from marking overwritten defaults as changed
$this->changed = [];
$this->changeForced = false;
// Set the data passed in the constructor, allowing for defaults and calling setters
// This will mark fields as changed
if ($record) {
$this->update($record);
}
break;
case DataObject::CREATE_SINGLETON:
// No setting happens for a singleton
$this->record['ID'] = 0;
$this->record['ClassName'] = static::class;
$this->record['RecordClassName'] = static::class;
$this->original = $this->record;
$this->changed = [];
$this->changeForced = false;
break;
default:
throw new \LogicException('Bad creationType ' . $this->creationType);
}
} | Construct a new DataObject.
@param array $record Initial record content, or rehydrated record content, depending on $creationType
@param int|boolean $creationType Set to DataObject::CREATE_OBJECT, DataObject::CREATE_HYDRATED,
DataObject::CREATE_MEMORY_HYDRATED or DataObject::CREATE_SINGLETON. Used by Silverstripe internals and best
left as the default by regular users.
@param array $queryParams List of DataQuery params necessary to lazy load, or load related objects. | __construct | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function destroy()
{
$this->flushCache(false);
} | Destroy all of this objects dependent objects and local caches.
You'll need to call this to get the memory of an object that has components or extensions freed. | destroy | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function duplicateHasOneRelation($sourceObject, $destinationObject, $relation)
{
// Check if original object exists
$item = $sourceObject->getComponent($relation);
if (!$item->isInDB()) {
return;
}
$clonedItem = $item->duplicate(false);
$destinationObject->setComponent($relation, $clonedItem);
} | Duplicates a single has_one relation from one object to another.
Note: Child object will be force written.
@param DataObject $sourceObject
@param DataObject $destinationObject
@param string $relation | duplicateHasOneRelation | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function duplicateBelongsToRelation($sourceObject, $destinationObject, $relation)
{
// Check if original object exists
$item = $sourceObject->getComponent($relation);
if (!$item->isInDB()) {
return;
}
$clonedItem = $item->duplicate(false);
$destinationObject->setComponent($relation, $clonedItem);
// After $clonedItem is assigned the appropriate FieldID / FieldClass, force write
$clonedItem->write();
} | Duplicates a single belongs_to relation from one object to another.
Note: This will force a write on both parent / child objects.
@param DataObject $sourceObject
@param DataObject $destinationObject
@param string $relation | duplicateBelongsToRelation | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getObsoleteClassName()
{
$className = $this->getField("ClassName");
if (!ClassInfo::exists($className)) {
return $className;
}
return null;
} | Return obsolete class name, if this is no longer a valid class
@return string | getObsoleteClassName | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function setClassName($className)
{
$className = trim($className ?? '');
if (!$className || !is_subclass_of($className, DataObject::class)) {
return $this;
}
$this->setField("ClassName", $className);
$this->setField('RecordClassName', $className);
return $this;
} | Set the ClassName attribute. {@link $class} is also updated.
Warning: This will produce an inconsistent record, as the object
instance will not automatically switch to the new subclass.
Please use {@link newClassInstance()} for this purpose,
or destroy and reinstanciate the record.
@param string $className The new ClassName attribute (a subclass of {@link DataObject})
@return $this | setClassName | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function exists()
{
return $this->isInDB();
} | Returns true if this object "exists", i.e., has a sensible value.
The default behaviour for a DataObject is to return true if
the object exists in the database, you can override this in subclasses.
@return boolean true if this object exists | exists | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function i18n_pluralise($count)
{
$default = 'one ' . $this->i18n_singular_name() . '|{count} ' . $this->i18n_plural_name();
return i18n::_t(
static::class . '.PLURALS',
$default,
['count' => $count]
);
} | Pluralise this item given a specific count.
E.g. "0 Pages", "1 File", "3 Images"
@param string $count
@return string | i18n_pluralise | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function singular_name()
{
$name = $this->config()->get('singular_name');
if ($name) {
return $name;
}
return ucwords(trim(strtolower(preg_replace(
'/_?([A-Z])/',
' $1',
ClassInfo::shortName($this) ?? ''
) ?? '')));
} | Get the user friendly singular name of this DataObject.
If the name is not defined (by redefining $singular_name in the subclass),
this returns the class name.
@return string User friendly singular name of this DataObject | singular_name | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function i18n_singular_name()
{
return _t(static::class . '.SINGULARNAME', $this->singular_name());
} | Get the translated user friendly singular name of this DataObject
same as singular_name() but runs it through the translating function
Translating string is in the form:
$this->class.SINGULARNAME
Example:
Page.SINGULARNAME
@return string User friendly translated singular name of this DataObject | i18n_singular_name | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function plural_name()
{
if ($name = $this->config()->get('plural_name')) {
return $name;
}
$name = $this->singular_name();
//if the penultimate character is not a vowel, replace "y" with "ies"
if (preg_match('/[^aeiou]y$/i', $name ?? '')) {
$name = substr($name ?? '', 0, -1) . 'ie';
}
return ucfirst($name . 's');
} | Get the user friendly plural name of this DataObject
If the name is not defined (by renaming $plural_name in the subclass),
this returns a pluralised version of the class name.
@return string User friendly plural name of this DataObject | plural_name | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function i18n_plural_name()
{
return _t(static::class . '.PLURALNAME', $this->plural_name());
} | Get the translated user friendly plural name of this DataObject
Same as plural_name but runs it through the translation function
Translation string is in the form:
$this->class.PLURALNAME
Example:
Page.PLURALNAME
@return string User friendly translated plural name of this DataObject | i18n_plural_name | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function classDescription()
{
return static::config()->get('class_description', Config::UNINHERITED);
} | Get description for this class
@return null|string | classDescription | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function i18n_classDescription()
{
$notDefined = 'NOT_DEFINED';
$baseDescription = $this->classDescription() ?? $notDefined;
// Check the new i18n key first
$description = _t(static::class . '.CLASS_DESCRIPTION', $baseDescription);
if ($description !== $baseDescription) {
return $description;
}
// Fall back on the deprecated localisation key
$legacyI18n = _t(static::class . '.DESCRIPTION', $baseDescription);
if ($legacyI18n !== $baseDescription) {
return $legacyI18n;
}
// If there was no description available in config nor in i18n, return null
if ($baseDescription === $notDefined) {
return null;
}
// Return raw description
return $baseDescription;
} | Get localised description for this class
@return null|string | i18n_classDescription | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function data()
{
return $this;
} | Returns the associated database record - in this case, the object itself.
This is included so that you can call $dataOrController->data() and get a DataObject all the time.
@return static Associated database record | data | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function toMap()
{
$this->loadLazyFields();
return array_filter($this->record ?? [], function ($val) {
return $val !== null;
});
} | Convert this object to a map.
Note that it has the following quirks:
- custom getters, including those that adjust the result of database fields, won't be executed
- NULL values won't be returned.
@return array The data as a map. | toMap | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getQueriedDatabaseFields()
{
return $this->record;
} | Return all currently fetched database fields.
This function is similar to toMap() but doesn't trigger the lazy-loading of all unfetched fields.
Obviously, this makes it a lot faster.
@return array The data as a map. | getQueriedDatabaseFields | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function update($data)
{
foreach ($data as $key => $value) {
// Implement dot syntax for updates
if (strpos($key ?? '', '.') !== false) {
$relations = explode('.', $key ?? '');
$fieldName = array_pop($relations);
$relObj = $this;
$relation = null;
foreach ($relations as $i => $relation) {
// no support for has_many or many_many relationships,
// as the updater wouldn't know which object to write to (or create)
if ($relObj->$relation() instanceof DataObject) {
$parentObj = $relObj;
/** @var static $relObj */
$relObj = $relObj->$relation();
// If the intermediate relationship objects haven't been created, then write them
if ($i < sizeof($relations ?? []) - 1 && !$relObj->ID || (!$relObj->ID && $parentObj !== $this)) {
$relObj->write();
$relatedFieldName = $relation . "ID";
$parentObj->$relatedFieldName = $relObj->ID;
$parentObj->write();
}
} else {
user_error(
"DataObject::update(): Can't traverse relationship '$relation'," .
"it has to be a has_one relationship or return a single DataObject",
E_USER_NOTICE
);
// unset relation object so we don't write properties to the wrong object
$relObj = null;
break;
}
}
if ($relObj) {
$relObj->$fieldName = $value;
$relObj->write();
$relatedFieldName = $relation . "ID";
$this->$relatedFieldName = $relObj->ID;
$relObj->flushCache();
} else {
$class = static::class;
user_error("Couldn't follow dot syntax '{$key}' on '{$class}' object", E_USER_WARNING);
}
} else {
$this->$key = $value;
}
}
return $this;
} | Update a number of fields on this object, given a map of the desired changes.
The field names can be simple names, or you can use a dot syntax to access $has_one relations.
For example, array("Author.FirstName" => "Jim") will set $this->Author()->FirstName to "Jim".
Doesn't write the main object, but if you use the dot syntax, it will write()
the related objects that it alters.
When using this method with user supplied data, it's very important to
whitelist the allowed keys.
@param array $data A map of field name to data values to update.
@return static $this | update | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function forceChange()
{
// Ensure lazy fields loaded
$this->loadLazyFields();
// Populate the null values in record so that they actually get written
foreach (array_keys(static::getSchema()->fieldSpecs(static::class) ?? []) as $fieldName) {
if (!isset($this->record[$fieldName])) {
$this->record[$fieldName] = null;
}
}
$this->changeForced = true;
return $this;
} | Forces the record to think that all its data has changed.
Doesn't write to the database. Force-change preserved until
next write. Existing CHANGE_VALUE or CHANGE_STRICT values
are preserved.
@return $this | forceChange | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function onBeforeWrite()
{
$this->brokenOnWrite = false;
$dummy = null;
$this->extend('onBeforeWrite', $dummy);
} | Event handler called before writing to the database.
You can overload this to clean up or otherwise process data before writing it to the
database. Don't forget to call parent::onBeforeWrite(), though!
This called after {@link $this->validate()}, so you can be sure that your data is valid.
@uses DataExtension::onBeforeWrite() | onBeforeWrite | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function onAfterWrite()
{
$dummy = null;
$this->extend('onAfterWrite', $dummy);
} | Event handler called after writing to the database.
You can overload this to act upon changes made to the data after it is written.
$this->changed will have a record
database. Don't forget to call parent::onAfterWrite(), though!
@uses DataExtension::onAfterWrite() | onAfterWrite | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function findCascadeDeletes($recursive = true, $list = null)
{
// Find objects in these relationships
return $this->findRelatedObjects('cascade_deletes', $recursive, $list);
} | Find all objects that will be cascade deleted if this object is deleted
Notes:
- If this object is versioned, objects will only be searched in the same stage as the given record.
- This will only be useful prior to deletion, as post-deletion this record will no longer exist.
@param bool $recursive True if recursive
@param ArrayList $list Optional list to add items to
@return ArrayList<DataObject> list of objects | findCascadeDeletes | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function validateWrite()
{
if ($this->ObsoleteClassName) {
return new ValidationException(
"Object is of class '{$this->ObsoleteClassName}' which doesn't exist - " .
"you need to change the ClassName before you can write it"
);
}
// Note: Validation can only be disabled at the global level, not per-model
if (DataObject::config()->uninherited('validation_enabled')) {
$result = $this->validate();
if (!$result->isValid()) {
return new ValidationException($result);
}
}
return null;
} | Determine validation of this object prior to write
@return ValidationException Exception generated by this write, or null if valid | validateWrite | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function preWrite()
{
// Validate this object
if ($writeException = $this->validateWrite()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->invokeWithExtensions('onAfterSkippedWrite');
throw $writeException;
}
// Check onBeforeWrite
$this->brokenOnWrite = true;
$this->onBeforeWrite();
if ($this->brokenOnWrite) {
throw new LogicException(
static::class . " has a broken onBeforeWrite() function."
. " Make sure that you call parent::onBeforeWrite()."
);
}
} | Prepare an object prior to write
@throws ValidationException | preWrite | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function updateChanges($forceChanges = false)
{
if ($forceChanges) {
// Force changes, but only for loaded fields
foreach ($this->record as $field => $value) {
$this->changed[$field] = static::CHANGE_VALUE;
}
return true;
}
return $this->isChanged();
} | Detects and updates all changes made to this object
@param bool $forceChanges If set to true, force all fields to be treated as changed
@return bool True if any changes are detected | updateChanges | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function writeBaseRecord($baseTable, $now)
{
// Generate new ID if not specified
if ($this->isInDB()) {
return;
}
// Perform an insert on the base table
$manipulation = [];
$this->prepareManipulationTable($baseTable, $now, true, $manipulation, $this->baseClass());
DB::manipulate($manipulation);
$this->changed['ID'] = DataObject::CHANGE_VALUE;
$this->record['ID'] = DB::get_generated_id($baseTable);
} | Ensures that a blank base record exists with the basic fixed fields for this dataobject
Does nothing if an ID is already assigned for this record
@param string $baseTable Base table
@param string $now Timestamp to use for the current time | writeBaseRecord | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false)
{
$now = DBDatetime::now()->Rfc2822();
// Execute pre-write tasks
$this->preWrite();
// Check if we are doing an update or an insert
$isNewRecord = !$this->isInDB() || $forceInsert;
// Check changes exist, abort if there are none
$hasChanges = $this->updateChanges($isNewRecord);
if ($hasChanges || $forceWrite || $isNewRecord) {
// Ensure Created and LastEdited are populated
if (!isset($this->record['Created'])) {
$this->record['Created'] = $now;
}
$this->record['LastEdited'] = $now;
// Try write the changes - but throw a validation exception if we violate a unique index
try {
// New records have their insert into the base data table done first, so that they can pass the
// generated primary key on to the rest of the manipulation
$baseTable = $this->baseTable();
$this->writeBaseRecord($baseTable, $now);
// Write the DB manipulation for all changed fields
$this->writeManipulation($baseTable, $now, $isNewRecord);
} catch (DuplicateEntryException $e) {
throw new ValidationException($this->buildValidationResultForDuplicateEntry($e));
}
// If there's any relations that couldn't be saved before, save them now (we have an ID here)
$this->writeRelations();
$this->onAfterWrite();
// Reset isChanged data
// DBComposites properly bound to the parent record will also have their isChanged value reset
$this->changed = [];
$this->changeForced = false;
$this->original = $this->record;
} else {
if ($showDebug) {
Debug::message("no changes for DataObject");
}
// Used by DODs to clean up after themselves, eg, Versioned
$this->invokeWithExtensions('onAfterSkippedWrite');
}
// Write relations as necessary
if ($writeComponents) {
$recursive = true;
$skip = [];
if (is_array($writeComponents)) {
$recursive = isset($writeComponents['recursive']) && $writeComponents['recursive'];
$skip = isset($writeComponents['skip']) && is_array($writeComponents['skip'])
? $writeComponents['skip']
: [];
}
$this->writeComponents($recursive, $skip);
}
// Clears the cache for this object so get_one returns the correct object.
$this->flushCache();
return $this->record['ID'];
} | Writes all changes to this object to the database.
- It will insert a record whenever ID isn't set, otherwise update.
- All relevant tables will be updated.
- $this->onBeforeWrite() gets called beforehand.
- Extensions such as Versioned will amend the database-write to ensure that a version is saved.
@uses DataExtension::augmentWrite()
@param boolean $showDebug Show debugging information
@param boolean $forceInsert Run INSERT command rather than UPDATE, even if record already exists
@param boolean $forceWrite Write to database even if there are no changes
@param boolean|array $writeComponents Call write() on all associated component instances which were previously
retrieved through {@link getComponent()}, {@link getComponents()} or
{@link getManyManyComponents()}. Default to `false`. The parameter can also be provided in
the form of an array: `['recursive' => true, skip => ['Page'=>[1,2,3]]`. This avoid infinite
loops when one DataObject are components of each other.
@return int The ID of the record
@throws ValidationException Exception that can be caught and handled by the calling function | write | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
private function skipWriteComponents($recursive, DataObject $target, array &$skip)
{
// skip writing component if it doesn't exist
if (!$target->exists()) {
return true;
}
// We only care about the skip list if our call is meant to be recursive
if (!$recursive) {
return false;
}
// Get our Skip array keys
$classname = get_class($target);
$id = $target->ID;
// Check if the target is in the skip list
if (isset($skip[$classname])) {
if (in_array($id, $skip[$classname] ?? [])) {
// Skip the object
return true;
}
} else {
// This is the first object of this class
$skip[$classname] = [];
}
// Add the target to our skip list
$skip[$classname][] = $id;
return false;
} | Check if target is in the skip list and add it if it isn't.
@param bool $recursive
@param DataObject $target
@param array $skip
@return bool Whether the target is already in the list | skipWriteComponents | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public static function delete_by_id($className, $id)
{
$obj = DataObject::get_by_id($className, $id);
if ($obj) {
$obj->delete();
} else {
user_error("$className object #$id wasn't found when calling DataObject::delete_by_id", E_USER_WARNING);
}
} | Delete the record with the given ID.
@param string $className The class name of the record to be deleted
@param int $id ID of record to be deleted | delete_by_id | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getClassAncestry()
{
return ClassInfo::ancestry(static::class);
} | Get the class ancestry, including the current class name.
The ancestry will be returned as an array of class names, where the 0th element
will be the class that inherits directly from DataObject, and the last element
will be the current class.
@return array Class ancestry | getClassAncestry | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function setComponent($componentName, $item)
{
// Validate component
$schema = static::getSchema();
if ($class = $schema->hasOneComponent(static::class, $componentName)) {
// Force item to be written if not by this point
if ($item && !$item->isInDB()) {
$item->write();
}
// Update local ID
$joinField = $componentName . 'ID';
$this->setField($joinField, $item ? $item->ID : null);
// Update Class (Polymorphic has_one)
// Extract class name for polymorphic relations
if ($class === DataObject::class) {
$this->setField($componentName . 'Class', $item ? get_class($item) : null);
}
} elseif ($class = $schema->belongsToComponent(static::class, $componentName)) {
if ($item) {
// For belongs_to, add to has_one on other component
$joinField = $schema->getRemoteJoinField(static::class, $componentName, 'belongs_to', $polymorphic);
if (!$polymorphic) {
$joinField = substr($joinField ?? '', 0, -2);
}
$item->setComponent($joinField, $this);
}
} else {
throw new InvalidArgumentException(
"DataObject->setComponent(): Could not find component '$componentName'."
);
}
$this->components[$componentName] = $item;
return $this;
} | Assign an item to the given component
@param string $componentName
@param DataObject|null $item
@return $this | setComponent | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getComponents($componentName, $id = null)
{
$result = null;
$schema = $this->getSchema();
$componentClass = $schema->hasManyComponent(static::class, $componentName);
if (!$componentClass) {
throw new InvalidArgumentException(sprintf(
"DataObject::getComponents(): Unknown 1-to-many component '%s' on class '%s'",
$componentName,
static::class
));
}
if (isset($this->eagerLoadedData[$componentName])) {
return $this->eagerLoadedData[$componentName];
}
// If we haven't been written yet, we can't save these relations, so use a list that handles this case
if (!isset($id)) {
$id = $this->ID;
}
if (!$id) {
if (!isset($this->unsavedRelations[$componentName])) {
$this->unsavedRelations[$componentName] =
new UnsavedRelationList(static::class, $componentName, $componentClass);
}
return $this->unsavedRelations[$componentName];
}
// Determine type and nature of foreign relation
$details = $schema->getHasManyComponentDetails(static::class, $componentName);
if ($details['polymorphic']) {
$result = PolymorphicHasManyList::create($componentClass, $details['joinField'], static::class);
if ($details['needsRelation']) {
Deprecation::withSuppressedNotice(fn () => $result->setForeignRelation($componentName));
}
} else {
$result = HasManyList::create($componentClass, $details['joinField']);
}
return $result
->setDataQueryParam($this->getInheritableQueryParams())
->forForeignID($id);
} | Returns a one-to-many relation as a HasManyList
@param string $componentName Name of the component
@param int|array $id Optional ID(s) for parent of this relation, if not the current record
@return HasManyList|UnsavedRelationList The components of the one-to-many relationship. | getComponents | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getRelationClass($relationName)
{
// Parse many_many, which can have an array instead of a class name
$manyManyComponent = static::getSchema()->manyManyComponent(static::class, $relationName);
if ($manyManyComponent) {
return $manyManyComponent['childClass'];
}
// Parse has_one, which can have an array instead of a class name
$hasOneComponent = static::getSchema()->hasOneComponent(static::class, $relationName);
if ($hasOneComponent) {
return $hasOneComponent;
}
// Go through all remaining relationship configuration fields.
$config = $this->config();
$candidates = array_merge(
($relations = $config->get('has_many')) ? $relations : [],
($relations = $config->get('belongs_to')) ? $relations : []
);
if (isset($candidates[$relationName])) {
$remoteClass = $candidates[$relationName];
// If dot notation is present, extract just the first part that contains the class.
if (($fieldPos = strpos($remoteClass ?? '', '.')) !== false) {
return substr($remoteClass ?? '', 0, $fieldPos);
}
// Otherwise just return the class
return $remoteClass;
}
return null;
} | Find the foreign class of a relation on this DataObject, regardless of the relation type.
@param string $relationName Relation name.
@return string Class name, or null if not found. | getRelationClass | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function hasOne()
{
$hasOne = (array) $this->config()->get('has_one');
// Boil down has_one spec to just the class name
foreach ($hasOne as $relationName => $spec) {
if (is_array($spec)) {
$hasOne[$relationName] = DataObject::getSchema()->hasOneComponent(static::class, $relationName);
}
}
return $hasOne;
} | Return the class of a all has_one relations.
@return array An array of all has_one components and their classes. | hasOne | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function belongsTo($classOnly = true)
{
$belongsTo = (array)$this->config()->get('belongs_to');
if ($belongsTo && $classOnly) {
return preg_replace('/(.+)?\..+/', '$1', $belongsTo ?? '');
} else {
return $belongsTo ? $belongsTo : [];
}
} | Returns the class of a remote belongs_to relationship. If no component is specified a map of all components and
their class name will be returned.
@param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
the field data stripped off. It defaults to TRUE.
@return string|array | belongsTo | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function hasMany($classOnly = true)
{
$hasMany = (array)$this->config()->get('has_many');
if ($hasMany && $classOnly) {
return preg_replace('/(.+)?\..+/', '$1', $hasMany ?? '');
} else {
return $hasMany ? $hasMany : [];
}
} | Gets the class of a one-to-many relationship. If no $component is specified then an array of all the one-to-many
relationships and their classes will be returned.
@param bool $classOnly If this is TRUE, than any has_many relationships in the form "ClassName.Field" will have
the field data stripped off. It defaults to TRUE.
@return string|array|false | hasMany | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function manyManyExtraFields()
{
return $this->config()->get('many_many_extraFields');
} | Return the many-to-many extra fields specification.
If you don't specify a component name, it returns all
extra fields for all components available.
@return array|null | manyManyExtraFields | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function manyMany()
{
$config = $this->config();
$manyManys = (array)$config->get('many_many');
$belongsManyManys = (array)$config->get('belongs_many_many');
$items = array_merge($manyManys, $belongsManyManys);
return $items;
} | Return information about a many-to-many component.
The return value is an array of (parentclass, childclass). If $component is null, then all many-many
components are returned.
@see DataObjectSchema::manyManyComponent()
@return array|null An array of (parentclass, childclass), or an array of all many-many components | manyMany | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function database_extensions($class)
{
$extensions = Config::inst()->get($class, 'database_extensions', Config::UNINHERITED);
if ($extensions) {
return $extensions;
} else {
return false;
}
} | This returns an array (if it exists) describing the database extensions that are required, or false if none
This is experimental, and is currently only a Postgres-specific enhancement.
@param string $class
@return array|false | database_extensions | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getDefaultSearchContext()
{
return SearchContext::create(
static::class,
$this->scaffoldSearchFields(),
$this->defaultSearchFilters()
);
} | Generates a SearchContext to be used for building and processing
a generic search form for properties on this object.
@return SearchContext<static> | getDefaultSearchContext | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function scaffoldFormFields($_params = null)
{
$params = array_merge(
[
'tabbed' => false,
'mainTabOnly' => false,
'includeRelations' => false,
'restrictRelations' => [],
'ignoreRelations' => [],
'restrictFields' => false,
'ignoreFields' => [],
'fieldClasses' => false,
'ajaxSafe' => false
],
(array)$_params
);
$fs = FormScaffolder::create($this);
$fs->tabbed = $params['tabbed'];
$fs->mainTabOnly = $params['mainTabOnly'];
$fs->includeRelations = $params['includeRelations'];
$fs->restrictRelations = $params['restrictRelations'];
$fs->ignoreRelations = $params['ignoreRelations'];
$fs->restrictFields = $params['restrictFields'];
$fs->ignoreFields = $params['ignoreFields'];
$fs->fieldClasses = $params['fieldClasses'];
$fs->ajaxSafe = $params['ajaxSafe'];
$this->extend('updateFormScaffolder', $fs, $this);
return $fs->getFieldList();
} | Scaffold a simple edit form for all properties on this dataobject,
based on default {@link FormField} mapping in {@link DBField::scaffoldFormField()}.
Field labels/titles will be auto generated from {@link DataObject::fieldLabels()}.
@uses FormScaffolder
@param array $_params Associative array passing through properties to {@link FormScaffolder}.
@return FieldList | scaffoldFormFields | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function beforeUpdateCMSFields($callback)
{
$this->beforeExtending('updateCMSFields', $callback);
} | Allows user code to hook into DataObject::getCMSFields prior to updateCMSFields
being called on extensions
@param callable $callback The callback to execute | beforeUpdateCMSFields | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function afterUpdateCMSFields(callable $callback)
{
$this->afterExtending('updateCMSFields', $callback);
} | Allows user code to hook into DataObject::getCMSFields after updateCMSFields
being called on extensions
@param callable $callback The callback to execute | afterUpdateCMSFields | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getCMSActions()
{
$actions = new FieldList();
$this->extend('updateCMSActions', $actions);
return $actions;
} | need to be overload by solid dataobject, so that the customised actions of that dataobject,
including that dataobject's extensions customised actions could be added to the EditForm.
@return FieldList an Empty FieldList(); need to be overload by solid subclass | getCMSActions | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getField($field)
{
// If we already have a value in $this->record, then we should just return that
if (isset($this->record[$field])) {
return $this->record[$field];
}
// Do we have a field that needs to be lazy loaded?
if (isset($this->record[$field . '_Lazy'])) {
$tableClass = $this->record[$field . '_Lazy'];
$this->loadLazyFields($tableClass);
}
$schema = static::getSchema();
// Support unary relations as fields
if ($schema->unaryComponent(static::class, $field)) {
return $this->getComponent($field);
}
// In case of complex fields, return the DBField object
if ($schema->compositeField(static::class, $field)) {
$this->record[$field] = $this->dbObject($field);
}
return isset($this->record[$field]) ? $this->record[$field] : null;
} | Gets the value of a field.
Called by {@link __get()} and any getFieldName() methods you might create.
@param string $field The name of the field
@return mixed The field value | getField | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function setField($fieldName, $val)
{
$this->objCacheClear();
//if it's a has_one component, destroy the cache
if (substr($fieldName ?? '', -2) == 'ID') {
unset($this->components[substr($fieldName, 0, -2)]);
}
// If we've just lazy-loaded the column, then we need to populate the $original array
if (isset($this->record[$fieldName . '_Lazy'])) {
$tableClass = $this->record[$fieldName . '_Lazy'];
$this->loadLazyFields($tableClass);
}
// Support component assignent via field setter
$schema = static::getSchema();
if ($schema->unaryComponent(static::class, $fieldName)) {
unset($this->components[$fieldName]);
// Assign component directly
if (is_null($val) || $val instanceof DataObject) {
return $this->setComponent($fieldName, $val);
}
// Assign by ID instead of object
if (is_numeric($val)) {
$fieldName .= 'ID';
}
}
// Situation 1: Passing an DBField
if ($val instanceof DBField) {
$val->setName($fieldName);
$val->saveInto($this);
// Situation 1a: Composite fields should remain bound in case they are
// later referenced to update the parent dataobject
if ($val instanceof DBComposite) {
$val->bindTo($this);
$this->setFieldValue($fieldName, $val);
}
// Situation 2: Passing a literal or non-DBField object
} else {
$this->setFieldValue($fieldName, $val);
}
return $this;
} | Set the value of the field
Called by {@link __set()} and any setFieldName() methods you might create.
@param string $fieldName Name of the field
@param mixed $val New field value
@return $this | setField | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function setCastedField($fieldName, $value)
{
if (!$fieldName) {
throw new InvalidArgumentException("DataObject::setCastedField: Called without a fieldName");
}
$fieldObj = $this->dbObject($fieldName);
if ($fieldObj) {
$fieldObj->setValue($value);
$fieldObj->saveInto($this);
} else {
$this->$fieldName = $value;
}
return $this;
} | Set the value of the field, using a casting object.
This is useful when you aren't sure that a date is in SQL format, for example.
setCastedField() can also be used, by forms, to set related data. For example, uploaded images
can be saved into the Image table.
@param string $fieldName Name of the field
@param mixed $value New field value
@return $this | setCastedField | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function hasField($field)
{
$schema = static::getSchema();
return (
array_key_exists($field, $this->record ?? [])
|| array_key_exists($field, $this->components ?? [])
|| $schema->fieldSpec(static::class, $field)
|| $schema->unaryComponent(static::class, $field)
|| $this->hasMethod("get{$field}")
);
} | Returns true if the given field exists in a database column on any of
the objects tables and optionally look up a dynamic getter with
get<fieldName>().
@param string $field Name of the field
@return boolean True if the given field exists | hasField | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function hasDatabaseField($field)
{
$spec = static::getSchema()->fieldSpec(static::class, $field, DataObjectSchema::DB_ONLY);
return !empty($spec);
} | Returns true if the given field exists as a database column
@param string $field Name of the field
@return boolean | hasDatabaseField | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function can($perm, $member = null, $context = [])
{
if (!$member) {
$member = Security::getCurrentUser();
}
if ($member && Permission::checkMember($member, "ADMIN")) {
return true;
}
if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm ?? ''))) {
$method = 'can' . ucfirst($perm ?? '');
return $this->$method($member);
}
$results = $this->extendedCan('can', $member);
if (isset($results)) {
return $results;
}
return ($member && Permission::checkMember($member, $perm));
} | Returns true if the member is allowed to do the given action.
See {@link extendedCan()} for a more versatile tri-state permission control.
@param string $perm The permission to be checked, such as 'View'.
@param Member $member The member whose permissions need checking. Defaults to the currently logged
in user.
@param array $context Additional $context to pass to extendedCan()
@return boolean True if the the member is allowed to do the given action | can | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function canCreate($member = null, $context = [])
{
$extended = $this->extendedCan(__FUNCTION__, $member, $context);
if ($extended !== null) {
return $extended;
}
return Permission::check('ADMIN', 'any', $member);
} | @param Member $member
@param array $context Additional context-specific data which might
affect whether (or where) this object could be created.
@return boolean | canCreate | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function dbObject($fieldName)
{
// Check for field in DB
$schema = static::getSchema();
$helper = $schema->fieldSpec(static::class, $fieldName, DataObjectSchema::INCLUDE_CLASS);
if (!$helper) {
return null;
}
if (!isset($this->record[$fieldName]) && isset($this->record[$fieldName . '_Lazy'])) {
$tableClass = $this->record[$fieldName . '_Lazy'];
$this->loadLazyFields($tableClass);
}
$value = isset($this->record[$fieldName])
? $this->record[$fieldName]
: null;
// If we have a DBField object in $this->record, then return that
if ($value instanceof DBField) {
return $value;
}
$pos = strpos($helper ?? '', '.');
$class = substr($helper ?? '', 0, $pos);
$spec = substr($helper ?? '', $pos + 1);
/** @var DBField $obj */
$table = $schema->tableName($class);
$obj = Injector::inst()->create($spec, $fieldName);
$obj->setTable($table);
$obj->setValue($value, $this, false);
return $obj;
} | Return the DBField object that represents the given field.
This works similarly to obj() with 2 key differences:
- it still returns an object even when the field has no value.
- it only matches fields and not methods
- it matches foreign keys generated by has_one relationships, eg, "ParentID"
@param string $fieldName Name of the field
@return DBField The field as a DBField object | dbObject | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function relField($fieldName)
{
// Navigate to relative parent using relObject() if needed
$component = $this;
if (($pos = strrpos($fieldName ?? '', '.')) !== false) {
$relation = substr($fieldName ?? '', 0, $pos);
$fieldName = substr($fieldName ?? '', $pos + 1);
$component = $this->relObject($relation);
}
// Bail if the component is null
if (!$component) {
return null;
}
if (ClassInfo::hasMethod($component, $fieldName)) {
return $component->$fieldName();
}
return $component->$fieldName;
} | Traverses to a field referenced by relationships between data objects, returning the value
The path to the related field is specified with dot separated syntax (eg: Parent.Child.Child.FieldName)
@param string $fieldName string
@return mixed Will return null on a missing value | relField | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getReverseAssociation($className)
{
if (is_array($this->manyMany())) {
$many_many = array_flip($this->manyMany() ?? []);
if (array_key_exists($className, $many_many ?? [])) {
return $many_many[$className];
}
}
if (is_array($this->hasMany())) {
$has_many = array_flip($this->hasMany() ?? []);
if (array_key_exists($className, $has_many ?? [])) {
return $has_many[$className];
}
}
if (is_array($this->hasOne())) {
$has_one = array_flip($this->hasOne() ?? []);
if (array_key_exists($className, $has_one ?? [])) {
return $has_one[$className];
}
}
return false;
} | Temporary hack to return an association name, based on class, to get around the mangle
of having to deal with reverse lookup of relationships to determine autogenerated foreign keys.
@param string $className
@return string | getReverseAssociation | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function flushCache($persistent = true)
{
if (static::class == DataObject::class) {
DataObject::$_cache_get_one = [];
return $this;
}
$classes = ClassInfo::ancestry(static::class);
foreach ($classes as $class) {
if (isset(DataObject::$_cache_get_one[$class])) {
unset(DataObject::$_cache_get_one[$class]);
}
}
$this->extend('flushCache');
$this->components = [];
$this->eagerLoadedData = [];
return $this;
} | Flush the cached results for all relations (has_one, has_many, many_many)
Also clears any cached aggregate data.
@param boolean $persistent When true will also clear persistent data stored in the Cache system.
When false will just clear session-local cached data
@return static $this | flushCache | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public static function flush_and_destroy_cache()
{
if (DataObject::$_cache_get_one) {
foreach (DataObject::$_cache_get_one as $class => $items) {
if (is_array($items)) {
foreach ($items as $item) {
if ($item) {
$item->destroy();
}
}
}
}
}
DataObject::$_cache_get_one = [];
} | Flush the get_one global cache and destroy associated objects. | flush_and_destroy_cache | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public static function reset()
{
DBEnum::reset();
ClassInfo::reset_db_cache();
static::getSchema()->reset();
DataObject::$_cache_get_one = [];
DataObject::$_cache_field_labels = [];
} | Reset all global caches associated with DataObject. | reset | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function baseTable()
{
return static::getSchema()->baseDataTable($this);
} | Get the name of the base table for this object
@return string | baseTable | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function baseClass()
{
return static::getSchema()->baseDataClass($this);
} | Get the base class for this object
@return class-string<DataObject> | baseClass | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getInheritableQueryParams()
{
$params = $this->getSourceQueryParams();
$this->extend('updateInheritableQueryParams', $params);
return $params;
} | Get list of parameters that should be inherited to relations on this object
@return array | getInheritableQueryParams | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function onAfterBuild()
{
$this->extend('onAfterBuild');
} | Invoked after every database build is complete (including after table creation and
default record population).
See {@link DatabaseAdmin::doBuild()} for context. | onAfterBuild | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function fieldLabel($name)
{
$labels = $this->fieldLabels();
return (isset($labels[$name])) ? $labels[$name] : FormField::name_to_label($name);
} | Get a human-readable label for a single field,
see {@link fieldLabels()} for more details.
@uses fieldLabels()
@uses FormField::name_to_label()
@param string $name Name of the field
@return string Label of the field | fieldLabel | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function summaryFields()
{
$rawFields = $this->config()->get('summary_fields');
// Merge associative / numeric keys
$fields = [];
foreach ($rawFields as $key => $value) {
if (is_int($key)) {
$key = $value;
}
$fields[$key] = $value;
}
if (!$fields) {
$fields = [];
// try to scaffold a couple of usual suspects
if ($this->hasField('Name')) {
$fields['Name'] = 'Name';
}
if (static::getSchema()->fieldSpec($this, 'Title')) {
$fields['Title'] = 'Title';
}
if ($this->hasField('Description')) {
$fields['Description'] = 'Description';
}
if ($this->hasField('FirstName')) {
$fields['FirstName'] = 'First Name';
}
}
$this->extend("updateSummaryFields", $fields);
// Final fail-over, just list ID field
if (!$fields) {
$fields['ID'] = 'ID';
}
// Localize fields (if possible)
foreach ($this->fieldLabels(false) as $name => $label) {
// only attempt to localize if the label definition is the same as the field name.
// this will preserve any custom labels set in the summary_fields configuration
if (isset($fields[$name]) && $name === $fields[$name]) {
$fields[$name] = $label;
}
}
return $fields;
} | Get the default summary fields for this object.
@return array | summaryFields | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function defaultSearchFilters()
{
$filters = [];
foreach ($this->searchableFields() as $name => $spec) {
if (empty($spec['filter'])) {
$filters[$name] = 'PartialMatchFilter';
} elseif ($spec['filter'] instanceof SearchFilter) {
$filters[$name] = $spec['filter'];
} else {
$filters[$name] = Injector::inst()->create($spec['filter'], $name);
}
}
return $filters;
} | Defines a default list of filters for the search context.
If a filter class mapping is defined on the data object,
it is constructed here. Otherwise, the default filter specified in
{@link DBField} is used.
@return array | defaultSearchFilters | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public static function disable_subclass_access()
{
Deprecation::notice('5.2.0', 'Will be removed without equivalent functionality');
DataObject::$subclass_access = false;
} | Temporarily disable subclass access in data object qeur
@deprecated 5.2.0 Will be removed without equivalent functionality | disable_subclass_access | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function hasValue($field, $arguments = null, $cache = true)
{
// has_one fields should not use dbObject to check if a value is given
$hasOne = static::getSchema()->hasOneComponent(static::class, $field);
if (!$hasOne && ($obj = $this->dbObject($field))) {
return $obj->exists();
} else {
return parent::hasValue($field, $arguments, $cache);
}
} | Returns true if the given method/parameter has a value
(Uses the DBField::hasValue if the parameter is a database field)
@param string $field The field name
@param array $arguments
@param bool $cache
@return boolean | hasValue | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public function getJoin()
{
return $this->joinRecord;
} | If selected through a many_many through relation, this is the instance of the joined record
@return DataObject | getJoin | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
protected function mergeRelatedObject($list, $added, $item)
{
// Identify item
$itemKey = get_class($item) . '/' . $item->ID;
// Write if saved, versioned, and not already added
if ($item->isInDB() && !isset($list[$itemKey])) {
$list[$itemKey] = $item;
$added[$itemKey] = $item;
}
// Add joined record (from many_many through) automatically
$joined = $item->getJoin();
if ($joined) {
$this->mergeRelatedObject($list, $added, $joined);
}
} | Merge single object into a list, but ensures that existing objects are not
re-added.
@param ArrayList $list Global list
@param ArrayList $added Additional list to insert into
@param DataObject $item Item to add | mergeRelatedObject | php | silverstripe/silverstripe-framework | src/ORM/DataObject.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/DataObject.php | BSD-3-Clause |
public static function create($into = null, $assignments = [])
{
return Injector::inst()->createWithArgs(__CLASS__, func_get_args());
} | Construct a new SQLInsert object
@param string $into Table name to insert into (ANSI quoted)
@param array $assignments List of column assignments
@return static | create | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLInsert.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLInsert.php | BSD-3-Clause |
function __construct($into = null, $assignments = [])
{
$this->setInto($into);
if (!empty($assignments)) {
$this->setAssignments($assignments);
}
} | Construct a new SQLInsert object
@param string $into Table name to insert into (ANSI quoted)
@param array $assignments List of column assignments | __construct | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLInsert.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLInsert.php | BSD-3-Clause |
public function setInto($into)
{
$this->into = $into;
return $this;
} | Sets the table name to insert into
@param string $into Single table name (ANSI quoted)
@return $this The self reference to this query | setInto | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLInsert.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLInsert.php | BSD-3-Clause |
public function getInto()
{
return $this->into;
} | Gets the table name to insert into
@return string Single table name | getInto | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLInsert.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLInsert.php | BSD-3-Clause |
public function setRows(array $rows)
{
return $this->clear()->addRows($rows);
} | Sets all rows to the given array
@param array $rows the list of rows
@return $this The self reference to this query | setRows | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLInsert.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLInsert.php | BSD-3-Clause |
public function clearRow()
{
$this->currentRow(true)->clear();
return $this;
} | Clears all currently set assignment values on the current row
@return $this The self reference to this query | clearRow | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLInsert.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLInsert.php | BSD-3-Clause |
public static function create(
$select = "*",
$from = [],
$where = [],
$orderby = [],
$groupby = [],
$having = [],
$limit = []
) {
return Injector::inst()->createWithArgs(__CLASS__, func_get_args());
} | Construct a new SQLSelect.
@param array|string $select An array of SELECT fields.
@param array|string $from An array of FROM clauses. The first one should be just the table name.
Each should be ANSI quoted.
@param array $where An array of WHERE clauses.
@param array $orderby An array ORDER BY clause.
@param array $groupby An array of GROUP BY clauses.
@param array $having An array of HAVING clauses.
@param array|string $limit A LIMIT clause or array with limit and offset keys
@return static | create | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function __construct(
$select = "*",
$from = [],
$where = [],
$orderby = [],
$groupby = [],
$having = [],
$limit = []
) {
parent::__construct($from, $where);
$this->setSelect($select);
$this->setOrderBy($orderby);
$this->setGroupBy($groupby);
$this->setHaving($having);
$this->setLimit($limit);
} | Construct a new SQLSelect.
@param array|string $select An array of SELECT fields.
@param array|string $from An array of FROM clauses. The first one should be just the table name.
Each should be ANSI quoted.
@param array $where An array of WHERE clauses.
@param array $orderby An array ORDER BY clause.
@param array $groupby An array of GROUP BY clauses.
@param array $having An array of HAVING clauses.
@param array|string $limit A LIMIT clause or array with limit and offset keys | __construct | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function selectField($field, $alias = null)
{
if (!$alias) {
if (preg_match('/"([^"]+)"$/', $field ?? '', $matches)) {
$alias = $matches[1];
} else {
$alias = $field;
}
}
$this->select[$alias] = $field;
return $this;
} | Select an additional field.
@param string $field The field to select (ansi quoted SQL identifier or statement)
@param string|null $alias The alias of that field (unquoted SQL identifier).
Defaults to the unquoted column name of the $field parameter.
@return $this Self reference | selectField | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function expressionForField($field)
{
return isset($this->select[$field]) ? $this->select[$field] : null;
} | Return the SQL expression for the given field alias.
Returns null if the given alias doesn't exist.
See {@link selectField()} for details on alias generation.
@param string $field
@return string | expressionForField | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
private function getDirectionFromString($value, $defaultDirection = null)
{
if (preg_match('/^(.*)(asc|desc)$/i', $value ?? '', $matches)) {
$column = trim($matches[1] ?? '');
$direction = strtoupper($matches[2] ?? '');
} else {
$column = $value;
$direction = $defaultDirection ? $defaultDirection : "ASC";
}
return [$column, $direction];
} | Extract the direction part of a single-column order by clause.
@param string $value
@param string $defaultDirection
@return array A two element array: [$column, $direction] | getDirectionFromString | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function getOrderBy()
{
$orderby = $this->orderby;
if (!$orderby) {
$orderby = [];
}
if (!is_array($orderby)) {
// spilt by any commas not within brackets
$orderby = preg_split('/,(?![^()]*+\\))/', $orderby ?? '');
}
foreach ($orderby as $k => $v) {
if (strpos($v ?? '', ' ') !== false) {
unset($orderby[$k]);
$rule = explode(' ', trim($v ?? ''));
$clause = $rule[0];
$dir = (isset($rule[1])) ? $rule[1] : 'ASC';
$orderby[$clause] = $dir;
}
}
return $orderby;
} | Returns the current order by as array if not already. To handle legacy
statements which are stored as strings. Without clauses and directions,
convert the orderby clause to something readable.
@return array | getOrderBy | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function getHaving()
{
return $this->having;
} | Return a list of HAVING clauses used internally.
@return array | getHaving | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function getHavingParameterised(&$parameters)
{
$this->splitQueryParameters($this->having, $conditions, $parameters);
return $conditions;
} | Return a list of HAVING clauses used internally.
@param array $parameters Out variable for parameters required for this query
@return array | getHavingParameterised | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function getGroupBy()
{
return $this->groupby;
} | Return a list of GROUP BY clauses used internally.
@return array | getGroupBy | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function unlimitedRowCount($column = null)
{
// we can't clear the select if we're relying on its output by a HAVING clause
if (count($this->having ?? [])) {
$records = $this->execute();
return $records->numRecords();
}
$clone = clone $this;
$clone->limit = null;
$clone->orderby = null;
// Choose a default column
if ($column == null) {
if ($this->groupby) {
$countQuery = new SQLSelect();
$countQuery->setSelect("count(*)");
$countQuery->setFrom(['(' . $clone->sql($innerParameters) . ') all_distinct']);
$sql = $countQuery->sql($parameters); // $parameters should be empty
$result = DB::prepared_query($sql, $innerParameters);
return (int)$result->value();
} else {
$clone->setSelect(["count(*)"]);
}
} else {
$clone->setSelect(["count($column)"]);
}
$clone->setGroupBy([]);
return (int)$clone->execute()->value();
} | Return the number of rows in this query if the limit were removed. Useful in paged data sets.
@param string $column
@return int | unlimitedRowCount | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function canSortBy($fieldName)
{
$fieldName = preg_replace('/(\s+?)(A|DE)SC$/', '', $fieldName ?? '');
return isset($this->select[$fieldName]);
} | Returns true if this query can be sorted by the given field.
@param string $fieldName
@return bool | canSortBy | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function aggregate($column, $alias = null)
{
$clone = clone $this;
// don't set an ORDER BY clause if no limit has been set. It doesn't make
// sense to add an ORDER BY if there is no limit, and it will break
// queries to databases like MSSQL if you do so. Note that the reason
// this came up is because DataQuery::initialiseQuery() introduces
// a default sort.
if ($this->limit) {
$clone->setLimit($this->limit);
$clone->setOrderBy($this->orderby);
} else {
$clone->setOrderBy([]);
}
$clone->setGroupBy($this->groupby);
if ($alias) {
$clone->setSelect([]);
$clone->selectField($column, $alias);
} else {
$clone->setSelect($column);
}
return $clone;
} | Return a new SQLSelect that calls the given aggregate functions on this data.
@param string $column An aggregate expression, such as 'MAX("Balance")', or a set of them
(as an escaped SQL statement)
@param string $alias An optional alias for the aggregate column.
@return SQLSelect A clone of this object with the given aggregate function | aggregate | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function firstRow()
{
$query = clone $this;
$offset = $this->limit ? $this->limit['start'] : 0;
$query->setLimit(1, $offset);
return $query;
} | Returns a query that returns only the first row of this query
@return SQLSelect A clone of this object with the first row only | firstRow | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
public function lastRow()
{
$query = clone $this;
$offset = $this->limit ? $this->limit['start'] : 0;
// Limit index to start in case of empty results
$index = max($this->count() + $offset - 1, 0);
$query->setLimit(1, $index);
return $query;
} | Returns a query that returns only the last row of this query
@return SQLSelect A clone of this object with the last row only | lastRow | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLSelect.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLSelect.php | BSD-3-Clause |
function __construct(array $values = [])
{
$this->setAssignments($values);
} | Instantiate a new SQLAssignmentRow object with the given values
@param array $values | __construct | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLAssignmentRow.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLAssignmentRow.php | BSD-3-Clause |
protected function parseAssignment($value)
{
// Assume string values (or values saved as customised array objects)
// represent simple assignment
if (!is_array($value) || isset($value['type'])) {
return ['?' => [$value]];
}
// If given as array then extract and check both the SQL as well as the parameter(s)
// Note that there could be multiple parameters, e.g.
// ['MAX(?,?)' => [1,2]] although the container should
// have a single item
if (count($value ?? []) == 1) {
foreach ($value as $sql => $parameters) {
if (!is_string($sql)) {
continue;
}
if (!is_array($parameters)) {
$parameters = [$parameters];
}
return [$sql => $parameters];
}
}
throw new InvalidArgumentException(
"Nested field assignments should be given as a single parameterised item array in "
. "['?' => ['value']] format)"
);
} | Given a key / value pair, extract the predicate and any potential parameters
in a format suitable for storing internally as a list of paramaterised conditions.
@param mixed $value Either a literal field value, or an array with
placeholder => parameter(s) as a pair
@return array A single item array in the format [$sql => [$parameters]] | parseAssignment | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLAssignmentRow.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLAssignmentRow.php | BSD-3-Clause |
public function setAssignments(array $assignments)
{
return $this->clear()->addAssignments($assignments);
} | Sets the list of assignments to the given list
@see SQLWriteExpression::addAssignments() for syntax examples
@param array $assignments
@return $this The self reference to this row | setAssignments | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLAssignmentRow.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLAssignmentRow.php | BSD-3-Clause |
public function assignSQL($field, $sql)
{
return $this->assign($field, [$sql => []]);
} | Assigns a value to a field using the literal SQL expression, rather than
a value to be escaped
@param string $field The field name to update
@param string $sql The SQL to use for this update. E.g. "NOW()"
@return $this The self reference to this row | assignSQL | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLAssignmentRow.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLAssignmentRow.php | BSD-3-Clause |
public function isEmpty()
{
return empty($this->assignments);
} | Determine if this assignment is empty
@return boolean Flag indicating that this assignment is empty | isEmpty | php | silverstripe/silverstripe-framework | src/ORM/Queries/SQLAssignmentRow.php | https://github.com/silverstripe/silverstripe-framework/blob/master/src/ORM/Queries/SQLAssignmentRow.php | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.