diff --git a/src/AbstractActiveRecord.php b/src/AbstractActiveRecord.php index 182ab6f80..85be9d077 100644 --- a/src/AbstractActiveRecord.php +++ b/src/AbstractActiveRecord.php @@ -5,10 +5,8 @@ namespace Yiisoft\ActiveRecord; use Closure; -use ReflectionClass; use ReflectionException; use Throwable; -use Yiisoft\Db\Connection\ConnectionInterface; use Yiisoft\Db\Exception\Exception; use Yiisoft\Db\Exception\InvalidArgumentException; use Yiisoft\Db\Exception\InvalidCallException; @@ -32,38 +30,27 @@ use function in_array; use function is_array; use function is_int; -use function ltrim; -use function preg_replace; +use function method_exists; use function reset; -use function strtolower; /** - * ActiveRecord is the base class for classes representing relational data in terms of objects. + * The base class implementing {@see ActiveRecordInterface}. * * See {@see ActiveRecord} for a concrete implementation. * - * @psalm-import-type ARClass from ActiveQueryInterface + * @psalm-import-type ModelClass from ActiveQueryInterface */ abstract class AbstractActiveRecord implements ActiveRecordInterface { private array|null $oldValues = null; /** - * @var ActiveRecordInterface[]|ActiveRecordInterface[][]|array[]|array[][] - * @psalm-var array + * @var ActiveRecordModelInterface[]|ActiveRecordModelInterface[][]|array[]|array[][] + * @psalm-var array */ private array $related = []; /** @var string[][] */ private array $relationsDependencies = []; - /** - * Returns the available property values of an Active Record object. - * - * @return array - * - * @psalm-return array - */ - abstract protected function propertyValuesInternal(): array; - /** * Inserts Active Record values into DB without considering transaction. * @@ -79,13 +66,9 @@ abstract protected function propertyValuesInternal(): array; */ abstract protected function insertInternal(array|null $propertyNames = null): bool; - /** - * Sets the value of the named property. - * - * @param string $name The property name. - * @param mixed $value The property value. - */ - abstract protected function populateProperty(string $name, mixed $value): void; + public function __construct(protected ActiveRecordModelInterface $model) + { + } public function delete(): int { @@ -94,24 +77,25 @@ public function delete(): int public function deleteAll(array $condition = [], array $params = []): int { - $command = $this->db()->createCommand(); - $command->delete($this->getTableName(), $condition, $params); + $command = $this->model->db()->createCommand(); + $command->delete($this->model->tableName(), $condition, $params); return $command->execute(); } - public function equals(ActiveRecordInterface $record): bool + public function equals(ActiveRecordModelInterface $record): bool { - if ($this->getIsNewRecord() || $record->getIsNewRecord()) { + if ($this->isNewRecord() || $record->activeRecord()->isNewRecord()) { return false; } - return $this->getTableName() === $record->getTableName() && $this->getPrimaryKey() === $record->getPrimaryKey(); + return $this->model->tableName() === $record->tableName() + && $this->getPrimaryKey() === $record->activeRecord()->getPrimaryKey(); } public function get(string $propertyName): mixed { - return $this->propertyValuesInternal()[$propertyName] ?? null; + return $this->model->propertyValues()[$propertyName] ?? null; } public function propertyValues(array|null $names = null, array $except = []): array @@ -122,10 +106,10 @@ public function propertyValues(array|null $names = null, array $except = []): ar $names = array_diff($names, $except); } - return array_intersect_key($this->propertyValuesInternal(), array_flip($names)); + return array_intersect_key($this->model->propertyValues(), array_flip($names)); } - public function getIsNewRecord(): bool + public function isNewRecord(): bool { return $this->oldValues === null; } @@ -190,7 +174,7 @@ public function getOldPrimaryKey(bool $asArray = false): mixed if (empty($keys)) { throw new Exception( - static::class . ' does not have a primary key. You should either define a primary key for ' + $this->model::class . ' does not have a primary key. You should either define a primary key for ' . 'the corresponding table or override the primaryKey() method.' ); } @@ -230,7 +214,7 @@ public function getPrimaryKey(bool $asArray = false): mixed * * @return array An array of related records indexed by relation names. * - * {@see relationQuery()} + * {@see ActiveRecordModelInterface::relationQuery()} */ public function getRelatedRecords(): array { @@ -266,17 +250,17 @@ public function hasProperty(string $name): bool * * Call methods declared in {@see ActiveQuery} to further customize the relation. * - * @param ActiveRecordInterface|Closure|string $class The class name of the related record, or an instance of - * the related record, or a Closure to create an {@see ActiveRecordInterface} object. + * @param ActiveRecordModelInterface|Closure|string $class The class name of the related record, or an instance of + * the related record, or a Closure to create an {@see ActiveRecordModelInterface} object. * @param array $link The primary-foreign key constraint. The keys of the array refer to the property names of * the record associated with the `$class` model, while the values of the array refer to the corresponding property * names in **this** active record class. * * @return ActiveQueryInterface The relational query object. * - * @psalm-param ARClass $class + * @psalm-param ModelClass $class */ - public function hasMany(string|ActiveRecordInterface|Closure $class, array $link): ActiveQueryInterface + public function hasMany(string|ActiveRecordModelInterface|Closure $class, array $link): ActiveQueryInterface { return $this->createRelationQuery($class, $link, true); } @@ -305,17 +289,17 @@ public function hasMany(string|ActiveRecordInterface|Closure $class, array $link * * Call methods declared in {@see ActiveQuery} to further customize the relation. * - * @param ActiveRecordInterface|Closure|string $class The class name of the related record, or an instance of - * the related record, or a Closure to create an {@see ActiveRecordInterface} object. + * @param ActiveRecordModelInterface|Closure|string $class The class name of the related record, or an instance of + * the related record, or a Closure to create an {@see ActiveRecordModelInterface} object. * @param array $link The primary-foreign key constraint. The keys of the array refer to the property names of * the record associated with the `$class` model, while the values of the array refer to the corresponding property * names in **this** active record class. * * @return ActiveQueryInterface The relational query object. * - * @psalm-param ARClass $class + * @psalm-param ModelClass $class */ - public function hasOne(string|ActiveRecordInterface|Closure $class, array $link): ActiveQueryInterface + public function hasOne(string|ActiveRecordModelInterface|Closure $class, array $link): ActiveQueryInterface { return $this->createRelationQuery($class, $link, false); } @@ -326,14 +310,18 @@ public function insert(array|null $propertyNames = null): bool } /** - * @param ActiveRecordInterface|Closure|string $arClass The class name of the related record, or an instance of - * the related record, or a Closure to create an {@see ActiveRecordInterface} object. + * @param ActiveRecordModelInterface|Closure|string $modelClass The class name of the related record, or an instance of + * the related record, or a Closure to create an {@see ActiveRecordModelInterface} object. * - * @psalm-param ARClass $arClass + * @psalm-param ModelClass $modelClass */ - public function instantiateQuery(string|ActiveRecordInterface|Closure $arClass): ActiveQueryInterface + public function instantiateQuery(string|ActiveRecordModelInterface|Closure $modelClass): ActiveQueryInterface { - return new ActiveQuery($arClass); + if (method_exists($this->model, 'instantiateQuery')) { + return $this->model->instantiateQuery($modelClass); + } + + return new ActiveQuery($modelClass); } public function isChanged(): bool @@ -343,7 +331,7 @@ public function isChanged(): bool public function isPropertyChanged(string $name): bool { - $values = $this->propertyValuesInternal(); + $values = $this->model->propertyValues(); if (empty($this->oldValues) || !array_key_exists($name, $this->oldValues)) { return array_key_exists($name, $values); @@ -354,7 +342,7 @@ public function isPropertyChanged(string $name): bool public function isPropertyChangedNonStrict(string $name): bool { - $values = $this->propertyValuesInternal(); + $values = $this->propertyValues(); if (empty($this->oldValues) || !array_key_exists($name, $this->oldValues)) { return array_key_exists($name, $values); @@ -376,15 +364,16 @@ public function isRelationPopulated(string $name): bool return array_key_exists($name, $this->related); } - public function link(string $relationName, ActiveRecordInterface $arClass, array $extraColumns = []): void + public function link(string $relationName, ActiveRecordModelInterface $model, array $extraColumns = []): void { - $viaClass = null; + $viaActiveRecord = null; $viaTable = null; - $relation = $this->relationQuery($relationName); + $relation = $this->model->relationQuery($relationName); $via = $relation->getVia(); + $activeRecord = $model->activeRecord(); if ($via !== null) { - if ($this->getIsNewRecord() || $arClass->getIsNewRecord()) { + if ($this->isNewRecord() || $activeRecord->isNewRecord()) { throw new InvalidCallException( 'Unable to link models: the models being linked cannot be newly created.' ); @@ -393,7 +382,7 @@ public function link(string $relationName, ActiveRecordInterface $arClass, array if (is_array($via)) { [$viaName, $viaRelation] = $via; /** @psalm-var ActiveQueryInterface $viaRelation */ - $viaClass = $viaRelation->getARInstance(); + $viaActiveRecord = $viaRelation->getModelInstance()->activeRecord(); // unset $viaName so that it can be reloaded to reflect the change. /** @psalm-var string $viaName */ unset($this->related[$viaName]); @@ -425,7 +414,7 @@ public function link(string $relationName, ActiveRecordInterface $arClass, array */ foreach ($link as $a => $b) { /** @psalm-var mixed */ - $columns[$b] = $arClass->get($a); + $columns[$b] = $activeRecord->get($a); } /** @@ -437,38 +426,38 @@ public function link(string $relationName, ActiveRecordInterface $arClass, array $columns[$k] = $v; } - if ($viaClass instanceof ActiveRecordInterface) { + if ($viaActiveRecord instanceof ActiveRecordInterface) { /** * @psalm-var string $column * @psalm-var mixed $value */ foreach ($columns as $column => $value) { - $viaClass->set($column, $value); + $viaActiveRecord->set($column, $value); } - $viaClass->insert(); + $viaActiveRecord->insert(); } elseif (is_string($viaTable)) { - $this->db()->createCommand()->insert($viaTable, $columns)->execute(); + $this->model->db()->createCommand()->insert($viaTable, $columns)->execute(); } } else { $link = $relation->getLink(); - $p1 = $arClass->isPrimaryKey(array_keys($link)); + $p1 = $activeRecord->isPrimaryKey(array_keys($link)); $p2 = $this->isPrimaryKey(array_values($link)); if ($p1 && $p2) { - if ($this->getIsNewRecord() && $arClass->getIsNewRecord()) { + if ($this->isNewRecord() && $activeRecord->isNewRecord()) { throw new InvalidCallException('Unable to link models: at most one model can be newly created.'); } - if ($this->getIsNewRecord()) { - $this->bindModels(array_flip($link), $this, $arClass); + if ($this->isNewRecord()) { + $this->bindModels(array_flip($link), $this, $activeRecord); } else { - $this->bindModels($link, $arClass, $this); + $this->bindModels($link, $activeRecord, $this); } } elseif ($p1) { - $this->bindModels(array_flip($link), $this, $arClass); + $this->bindModels(array_flip($link), $this, $activeRecord); } elseif ($p2) { - $this->bindModels($link, $arClass, $this); + $this->bindModels($link, $activeRecord, $this); } else { throw new InvalidCallException( 'Unable to link models: the link defining the relation does not involve any primary key.' @@ -478,22 +467,22 @@ public function link(string $relationName, ActiveRecordInterface $arClass, array // Update lazily loaded related objects. if (!$relation->getMultiple()) { - $this->related[$relationName] = $arClass; + $this->related[$relationName] = $model; } elseif (isset($this->related[$relationName])) { - /** @psalm-var ActiveRecordInterface[] $this->related[$relationName] */ + /** @psalm-var ActiveRecordModelInterface[] $this->related[$relationName] */ $indexBy = $relation->getIndexBy(); if ($indexBy !== null) { if ($indexBy instanceof Closure) { - $index = $indexBy($arClass->propertyValues()); + $index = $indexBy($model->propertyValues()); } else { - $index = $arClass->get($indexBy); + $index = $activeRecord->get($indexBy); } if ($index !== null) { - $this->related[$relationName][$index] = $arClass; + $this->related[$relationName][$index] = $model; } } else { - $this->related[$relationName][] = $arClass; + $this->related[$relationName][] = $model; } } } @@ -523,12 +512,12 @@ public function markPropertyChanged(string $name): void */ public function populateRecord(array|object $row): void { - if ($row instanceof ActiveRecordInterface) { + if ($row instanceof ActiveRecordModelInterface) { $row = $row->propertyValues(); } foreach ($row as $name => $value) { - $this->populateProperty($name, $value); + $this->model->populateProperty($name, $value); $this->oldValues[$name] = $value; } @@ -536,7 +525,7 @@ public function populateRecord(array|object $row): void $this->relationsDependencies = []; } - public function populateRelation(string $name, array|ActiveRecordInterface|null $records): void + public function populateRelation(string $name, array|ActiveRecordModelInterface|null $records): void { foreach ($this->relationsDependencies as &$relationNames) { unset($relationNames[$name]); @@ -553,12 +542,12 @@ public function populateRelation(string $name, array|ActiveRecordInterface|null */ public function refresh(): bool { - $record = $this->instantiateQuery(static::class)->findOne($this->getPrimaryKey(true)); + $record = $this->instantiateQuery($this->model::class)->findOne($this->getPrimaryKey(true)); return $this->refreshInternal($record); } - public function relation(string $name): ActiveRecordInterface|array|null + public function relation(string $name): ActiveRecordModelInterface|array|null { if (array_key_exists($name, $this->related)) { return $this->related[$name]; @@ -567,11 +556,6 @@ public function relation(string $name): ActiveRecordInterface|array|null return $this->retrieveRelation($name); } - public function relationQuery(string $name): ActiveQueryInterface - { - throw new InvalidArgumentException(static::class . ' has no relation named "' . $name . '".'); - } - public function resetRelation(string $name): void { foreach ($this->relationsDependencies as &$relationNames) { @@ -581,10 +565,10 @@ public function resetRelation(string $name): void unset($this->related[$name]); } - protected function retrieveRelation(string $name): ActiveRecordInterface|array|null + public function retrieveRelation(string $name): ActiveRecordModelInterface|array|null { /** @var ActiveQueryInterface $query */ - $query = $this->relationQuery($name); + $query = $this->model->relationQuery($name); $this->setRelationDependencies($name, $query); @@ -593,7 +577,7 @@ protected function retrieveRelation(string $name): ActiveRecordInterface|array|n public function save(array|null $propertyNames = null): bool { - if ($this->getIsNewRecord()) { + if ($this->isNewRecord()) { return $this->insert($propertyNames); } @@ -611,7 +595,7 @@ public function set(string $propertyName, mixed $value): void $this->resetDependentRelations($propertyName); } - $this->populateProperty($propertyName, $value); + $this->model->populateProperty($propertyName, $value); } /** @@ -627,7 +611,7 @@ public function populateProperties(array $values): void /** @psalm-var mixed $value */ foreach ($values as $name => $value) { - $this->populateProperty($name, $value); + $this->model->populateProperty($name, $value); } } @@ -636,11 +620,11 @@ public function populateProperties(array $values): void * * @param bool $value Whether the record is new and should be inserted when calling {@see save()}. * - * @see getIsNewRecord() + * @see isNewRecord() */ public function setIsNewRecord(bool $value): void { - $this->oldValues = $value ? null : $this->propertyValuesInternal(); + $this->oldValues = $value ? null : $this->propertyValues(); } /** @@ -657,7 +641,7 @@ public function assignOldValue(string $propertyName, mixed $value): void if (isset($this->oldValues[$propertyName]) || $this->hasProperty($propertyName)) { $this->oldValues[$propertyName] = $value; } else { - throw new InvalidArgumentException(static::class . ' has no property named "' . $propertyName . '".'); + throw new InvalidArgumentException($this->model::class . ' has no property named "' . $propertyName . '".'); } } @@ -681,9 +665,9 @@ public function update(array|null $propertyNames = null): int public function updateAll(array $propertyValues, array|string $condition = [], array $params = []): int { - $command = $this->db()->createCommand(); + $command = $this->model->db()->createCommand(); - $command->update($this->getTableName(), $propertyValues, $condition, $params); + $command->update($this->model->tableName(), $propertyValues, $condition, $params); return $command->execute(); } @@ -703,7 +687,7 @@ public function updateProperties(array $properties): int $values = $this->newValues($names); - if (empty($values) || $this->getIsNewRecord()) { + if (empty($values) || $this->isNewRecord()) { return 0; } @@ -750,8 +734,8 @@ public function updateAllCounters(array $counters, array|string $condition = '', $n++; } - $command = $this->db()->createCommand(); - $command->update($this->getTableName(), $counters, $condition, $params); + $command = $this->model->db()->createCommand(); + $command->update($this->model->tableName(), $counters, $condition, $params); return $command->execute(); } @@ -789,25 +773,26 @@ public function updateCounters(array $counters): bool foreach ($counters as $name => $value) { $value += $this->get($name) ?? 0; - $this->populateProperty($name, $value); + $this->model->populateProperty($name, $value); $this->oldValues[$name] = $value; } return true; } - public function unlink(string $relationName, ActiveRecordInterface $arClass, bool $delete = false): void + public function unlink(string $relationName, ActiveRecordModelInterface $model, bool $delete = false): void { $viaClass = null; $viaTable = null; - $relation = $this->relationQuery($relationName); + $relation = $this->model->relationQuery($relationName); $viaRelation = $relation->getVia(); + $activeRecord = $model->activeRecord(); if ($viaRelation !== null) { if (is_array($viaRelation)) { [$viaName, $viaRelation] = $viaRelation; /** @psalm-var ActiveQueryInterface $viaRelation */ - $viaClass = $viaRelation->getARInstance(); + $viaClass = $viaRelation->getModelInstance()->activeRecord(); /** @psalm-var string $viaName */ unset($this->related[$viaName]); } @@ -829,7 +814,7 @@ public function unlink(string $relationName, ActiveRecordInterface $arClass, boo foreach ($link as $a => $b) { /** @psalm-var mixed */ - $columns[$b] = $arClass->get($a); + $columns[$b] = $activeRecord->get($a); } $nulls = array_fill_keys(array_keys($columns), null); @@ -846,7 +831,7 @@ public function unlink(string $relationName, ActiveRecordInterface $arClass, boo $viaClass->updateAll($nulls, $columns); } } elseif (is_string($viaTable)) { - $command = $this->db()->createCommand(); + $command = $this->model->db()->createCommand(); if ($delete) { $command->delete($viaTable, $columns)->execute(); } else { @@ -856,20 +841,20 @@ public function unlink(string $relationName, ActiveRecordInterface $arClass, boo } elseif ($relation instanceof ActiveQueryInterface) { if ($this->isPrimaryKey($relation->getLink())) { if ($delete) { - $arClass->delete(); + $activeRecord->delete(); } else { foreach ($relation->getLink() as $a => $b) { - $arClass->set($a, null); + $activeRecord->set($a, null); } - $arClass->save(); + $activeRecord->save(); } - } elseif ($arClass->isPrimaryKey(array_keys($relation->getLink()))) { + } elseif ($activeRecord->isPrimaryKey(array_keys($relation->getLink()))) { foreach ($relation->getLink() as $a => $b) { /** @psalm-var mixed $values */ $values = $this->get($b); /** relation via array valued property */ if (is_array($values)) { - if (($key = array_search($arClass->get($a), $values)) !== false) { + if (($key = array_search($activeRecord->get($a), $values)) !== false) { unset($values[$key]); $this->set($b, array_values($values)); } @@ -886,10 +871,10 @@ public function unlink(string $relationName, ActiveRecordInterface $arClass, boo if (!$relation->getMultiple()) { unset($this->related[$relationName]); } elseif (isset($this->related[$relationName]) && is_array($this->related[$relationName])) { - /** @psalm-var array $related */ + /** @psalm-var array $related */ $related = $this->related[$relationName]; foreach ($related as $a => $b) { - if ($arClass->getPrimaryKey() === $b->getPrimaryKey()) { + if ($activeRecord->getPrimaryKey() === $b->activeRecord()->getPrimaryKey()) { unset($this->related[$relationName][$a]); } } @@ -916,14 +901,14 @@ public function unlinkAll(string $relationName, bool $delete = false): void { $viaClass = null; $viaTable = null; - $relation = $this->relationQuery($relationName); + $relation = $this->model->relationQuery($relationName); $viaRelation = $relation->getVia(); if ($viaRelation !== null) { if (is_array($viaRelation)) { [$viaName, $viaRelation] = $viaRelation; /** @psalm-var ActiveQueryInterface $viaRelation */ - $viaClass = $viaRelation->getARInstance(); + $viaClass = $viaRelation->getModelInstance()->activeRecord(); /** @psalm-var string $viaName */ unset($this->related[$viaName]); } else { @@ -958,7 +943,7 @@ public function unlinkAll(string $relationName, bool $delete = false): void $viaClass->updateAll($nulls, $condition); } } elseif (is_string($viaTable)) { - $command = $this->db()->createCommand(); + $command = $this->model->db()->createCommand(); if ($delete) { $command->delete($viaTable, $condition)->execute(); } else { @@ -966,7 +951,7 @@ public function unlinkAll(string $relationName, bool $delete = false): void } } } else { - $relatedModel = $relation->getARInstance(); + $relatedAr = $relation->getModelInstance()->activeRecord(); $link = $relation->getLink(); if (!$delete && count($link) === 1 && is_array($this->get($b = reset($link)))) { @@ -992,9 +977,9 @@ public function unlinkAll(string $relationName, bool $delete = false): void } if ($delete) { - $relatedModel->deleteAll($condition); + $relatedAr->deleteAll($condition); } else { - $relatedModel->updateAll($nulls, $condition); + $relatedAr->updateAll($nulls, $condition); } } } @@ -1012,7 +997,7 @@ public function unlinkAll(string $relationName, bool $delete = false): void private function setRelationDependencies( string $name, ActiveQueryInterface $relation, - string $viaRelationName = null + string|null $viaRelationName = null ): void { $via = $relation->getVia(); @@ -1038,20 +1023,20 @@ private function setRelationDependencies( /** * Creates a query instance for `has-one` or `has-many` relation. * - * @param ActiveRecordInterface|Closure|string $arClass The class name of the related record. + * @param ActiveRecordModelInterface|Closure|string $modelClass The class name of the related record. * @param array $link The primary-foreign key constraint. * @param bool $multiple Whether this query represents a relation to more than one record. * * @return ActiveQueryInterface The relational query object. * - * @psalm-param ARClass $arClass + * @psalm-param ModelClass $modelClass * {@see hasOne()} * {@see hasMany()} */ - protected function createRelationQuery(string|ActiveRecordInterface|Closure $arClass, array $link, bool $multiple): ActiveQueryInterface + protected function createRelationQuery(string|ActiveRecordModelInterface|Closure $modelClass, array $link, bool $multiple): ActiveQueryInterface { - return $this->instantiateQuery($arClass)->primaryModel($this)->link($link)->multiple($multiple); + return $this->instantiateQuery($modelClass)->primaryModel($this->model)->link($link)->multiple($multiple); } /** @@ -1071,16 +1056,14 @@ protected function deleteInternal(): int */ $condition = $this->getOldPrimaryKey(true); - if ($this instanceof OptimisticLockInterface) { - $lock = $this->optimisticLockPropertyName(); + if ($this->model instanceof OptimisticLockInterface) { + $lock = $this->model->optimisticLockPropertyName(); $condition[$lock] = $this->get($lock); $result = $this->deleteAll($condition); if ($result === 0) { - throw new OptimisticLockException( - 'The object being deleted is outdated.' - ); + throw new OptimisticLockException('The object being deleted is outdated.'); } } else { $result = $this->deleteAll($condition); @@ -1094,23 +1077,25 @@ protected function deleteInternal(): int /** * Repopulates this active record with the latest data from a newly fetched instance. * - * @param ActiveRecordInterface|array|null $record The record to take property values from. + * @param ActiveRecordModelInterface|array|null $record The record to take property values from. * * @return bool Whether refresh was successful. * * {@see refresh()} */ - protected function refreshInternal(array|ActiveRecordInterface|null $record = null): bool + protected function refreshInternal(array|ActiveRecordModelInterface|null $record = null): bool { if ($record === null || is_array($record)) { return false; } + $activeRecord = $record->activeRecord(); + foreach ($this->propertyNames() as $name) { - $this->populateProperty($name, $record->get($name)); + $this->model->populateProperty($name, $activeRecord->get($name)); } - $this->oldValues = $record->oldValues(); + $this->oldValues = $activeRecord->oldValues(); $this->related = []; $this->relationsDependencies = []; @@ -1138,8 +1123,8 @@ protected function updateInternal(array|null $propertyNames = null): int $condition = $this->getOldPrimaryKey(true); - if ($this instanceof OptimisticLockInterface) { - $lock = $this->optimisticLockPropertyName(); + if ($this->model instanceof OptimisticLockInterface) { + $lock = $this->model->optimisticLockPropertyName(); $lockValue = $this->get($lock); $condition[$lock] = $lockValue; @@ -1148,12 +1133,10 @@ protected function updateInternal(array|null $propertyNames = null): int $rows = $this->updateAll($values, $condition); if ($rows === 0) { - throw new OptimisticLockException( - 'The object being updated is outdated.' - ); + throw new OptimisticLockException('The object being updated is outdated.'); } - $this->populateProperty($lock, $lockValue); + $this->model->populateProperty($lock, $lockValue); } else { $rows = $this->updateAll($values, $condition); } @@ -1165,38 +1148,32 @@ protected function updateInternal(array|null $propertyNames = null): int private function bindModels( array $link, - ActiveRecordInterface $foreignModel, - ActiveRecordInterface $primaryModel + ActiveRecordInterface $foreignActiveRecord, + ActiveRecordInterface $primaryAcriveRecord ): void { - /** @psalm-var string[] $link */ + /** @var string[] $link */ foreach ($link as $fk => $pk) { - /** @psalm-var mixed $value */ - $value = $primaryModel->get($pk); + /** @var self $primaryAcriveRecord */ + $value = $primaryAcriveRecord->get($pk); if ($value === null) { throw new InvalidCallException( - 'Unable to link active record: the primary key of ' . $primaryModel::class . ' is null.' + 'Unable to link active record: the primary key of ' . $primaryAcriveRecord->model::class . ' is null.' ); } /** * Relation via array valued property. */ - if (is_array($fkValue = $foreignModel->get($fk))) { - /** @psalm-var mixed */ + if (is_array($fkValue = $foreignActiveRecord->get($fk))) { $fkValue[] = $value; - $foreignModel->set($fk, $fkValue); + $foreignActiveRecord->set($fk, $fkValue); } else { - $foreignModel->set($fk, $value); + $foreignActiveRecord->set($fk, $value); } } - $foreignModel->save(); - } - - protected function hasDependentRelations(string $propertyName): bool - { - return isset($this->relationsDependencies[$propertyName]); + $foreignActiveRecord->save(); } /** @@ -1204,27 +1181,16 @@ protected function hasDependentRelations(string $propertyName): bool * * @param string $propertyName The changed property name. */ - protected function resetDependentRelations(string $propertyName): void + public function resetDependentRelations(string $propertyName): void { + if (!isset($this->relationsDependencies[$propertyName])) { + return; + } + foreach ($this->relationsDependencies[$propertyName] as $relation) { unset($this->related[$relation]); } unset($this->relationsDependencies[$propertyName]); } - - public function getTableName(): string - { - $name = (new ReflectionClass($this))->getShortName(); - /** @var string $name */ - $name = preg_replace('/[A-Z]([A-Z](?![a-z]))*/', '_$0', $name); - $name = strtolower(ltrim($name, '_')); - - return '{{%' . $name . '}}'; - } - - public function db(): ConnectionInterface - { - return ConnectionProvider::get(); - } } diff --git a/src/AbstractActiveRecordModel.php b/src/AbstractActiveRecordModel.php new file mode 100644 index 000000000..7e5623acd --- /dev/null +++ b/src/AbstractActiveRecordModel.php @@ -0,0 +1,43 @@ +activeRecord ??= new ActiveRecord($this); + } + + public function db(): ConnectionInterface + { + return ConnectionProvider::get(); + } + + public function relationQuery(string $name): ActiveQueryInterface + { + throw new InvalidArgumentException(static::class . ' has no relation named "' . $name . '".'); + } + + public function tableName(): string + { + $name = (new ReflectionClass($this))->getShortName(); + /** @var string $name */ + $name = preg_replace('/[A-Z]([A-Z](?![a-z]))*/', '_$0', $name); + $name = strtolower(ltrim($name, '_')); + + return '{{%' . $name . '}}'; + } +} diff --git a/src/ActiveQuery.php b/src/ActiveQuery.php index 62b833dcc..e67996301 100644 --- a/src/ActiveQuery.php +++ b/src/ActiveQuery.php @@ -100,7 +100,7 @@ * as inverse of another relation and {@see onCondition()} which adds a condition that is to be added to relational * query join condition. * - * @psalm-import-type ARClass from ActiveQueryInterface + * @psalm-import-type ModelClass from ActiveQueryInterface * @psalm-import-type IndexKey from ArArrayHelper * * @psalm-property IndexKey|null $indexBy @@ -116,12 +116,12 @@ class ActiveQuery extends Query implements ActiveQueryInterface private array $joinWith = []; /** - * @psalm-param ARClass $arClass + * @psalm-param ModelClass $modelClass */ final public function __construct( - protected string|ActiveRecordInterface|Closure $arClass + protected string|ActiveRecordModelInterface|Closure $modelClass ) { - parent::__construct($this->getARInstance()->db()); + parent::__construct($this->getModelInstance()->db()); } public function each(): DataReaderInterface @@ -169,6 +169,7 @@ public function prepare(QueryBuilderInterface $builder): QueryInterface if ($this->primaryModel === null) { $query = $this->createInstance(); } else { + $activeRecord = $this->primaryModel->activeRecord(); $where = $this->getWhere(); if ($this->via instanceof ActiveQueryInterface) { @@ -183,21 +184,21 @@ public function prepare(QueryBuilderInterface $builder): QueryInterface if ($viaQuery->getMultiple()) { if ($viaCallableUsed) { $viaModels = $viaQuery->all(); - } elseif ($this->primaryModel->isRelationPopulated($viaName)) { - /** @var ActiveRecordInterface[]|array[] $viaModels */ - $viaModels = $this->primaryModel->relation($viaName); + } elseif ($activeRecord->isRelationPopulated($viaName)) { + /** @var ActiveRecordModelInterface[]|array[] $viaModels */ + $viaModels = $activeRecord->relation($viaName); } else { $viaModels = $viaQuery->all(); - $this->primaryModel->populateRelation($viaName, $viaModels); + $activeRecord->populateRelation($viaName, $viaModels); } } else { if ($viaCallableUsed) { $model = $viaQuery->one(); - } elseif ($this->primaryModel->isRelationPopulated($viaName)) { - $model = $this->primaryModel->relation($viaName); + } elseif ($activeRecord->isRelationPopulated($viaName)) { + $model = $activeRecord->relation($viaName); } else { $model = $viaQuery->one(); - $this->primaryModel->populateRelation($viaName, $model); + $activeRecord->populateRelation($viaName, $model); } $viaModels = $model === null ? [] : [$model]; } @@ -228,8 +229,8 @@ public function prepare(QueryBuilderInterface $builder): QueryInterface * @psalm-param list $rows * @psalm-return ( * $rows is non-empty-list - * ? non-empty-list - * : list + * ? non-empty-list + * : list * ) */ public function populate(array $rows): array @@ -274,8 +275,8 @@ public function populate(array $rows): array */ private function removeDuplicatedRows(array $rows): array { - $instance = $this->getARInstance(); - $pks = $instance->primaryKey(); + $instance = $this->getModelInstance(); + $pks = $instance->activeRecord()->primaryKey(); if (empty($pks)) { throw new InvalidConfigException('Primary key of "' . $instance::class . '" can not be empty.'); @@ -301,7 +302,7 @@ private function removeDuplicatedRows(array $rows): array return array_values(array_combine($hash, $rows)); } - public function one(): array|ActiveRecordInterface|null + public function one(): array|ActiveRecordModelInterface|null { if ($this->shouldEmulateExecution()) { return null; @@ -417,10 +418,10 @@ public function buildJoinWith(): void $this->join = []; - $arClass = $this->getARInstance(); + $model = $this->getModelInstance(); foreach ($this->joinWith as [$with, $eagerLoading, $joinType]) { - $this->joinWithRelations($arClass, $with, $joinType); + $this->joinWithRelations($model, $with, $joinType); if (is_array($eagerLoading)) { foreach ($with as $name => $callback) { @@ -480,7 +481,7 @@ public function innerJoinWith(array|string $with, array|bool $eagerLoading = tru /** * Modifies the current query by adding join fragments based on the given relations. * - * @param ActiveRecordInterface $arClass The primary model. + * @param ActiveRecordModelInterface $model The primary model. * @param array $with The relations to be joined. * @param array|string $joinType The join type. * @@ -489,7 +490,7 @@ public function innerJoinWith(array|string $with, array|bool $eagerLoading = tru * @throws NotInstantiableException * @throws \Yiisoft\Definitions\Exception\InvalidConfigException */ - private function joinWithRelations(ActiveRecordInterface $arClass, array $with, array|string $joinType): void + private function joinWithRelations(ActiveRecordModelInterface $model, array $with, array|string $joinType): void { $relations = []; @@ -499,7 +500,7 @@ private function joinWithRelations(ActiveRecordInterface $arClass, array $with, $callback = null; } - $primaryModel = $arClass; + $primaryModel = $model; $parent = $this; $prefix = ''; @@ -518,7 +519,7 @@ private function joinWithRelations(ActiveRecordInterface $arClass, array $with, } if ($relation instanceof ActiveQueryInterface) { - $primaryModel = $relation->getARInstance(); + $primaryModel = $relation->getModelInstance(); $parent = $relation; } @@ -564,7 +565,7 @@ private function getJoinType(array|string $joinType, string $name): string } /** - * Returns the table name and the table alias for {@see arClass}. + * Returns the table name and the table alias for {@see $modelClass}. * * @throws CircularReferenceException * @throws InvalidConfigException @@ -731,11 +732,11 @@ public function orOnCondition(array|string $condition, array $params = []): stat return $this; } - public function viaTable(string $tableName, array $link, callable $callable = null): static + public function viaTable(string $tableName, array $link, callable|null $callable = null): static { - $arClass = $this->primaryModel ?? $this->arClass; + $modelClass = $this->primaryModel ?? $this->modelClass; - $relation = (new static($arClass)) + $relation = (new static($modelClass)) ->from([$tableName]) ->link($link) ->multiple(true) @@ -791,7 +792,7 @@ public function getTablesUsedInFrom(): array */ protected function getPrimaryTableName(): string { - return $this->getARInstance()->getTableName(); + return $this->getModelInstance()->tableName(); } public function getOn(): array|string|null @@ -812,9 +813,9 @@ public function getSql(): string|null return $this->sql; } - public function getARClass(): string|ActiveRecordInterface|Closure + public function getModelClass(): string|ActiveRecordModelInterface|Closure { - return $this->arClass; + return $this->modelClass; } /** @@ -823,7 +824,7 @@ public function getARClass(): string|ActiveRecordInterface|Closure * @throws InvalidConfigException * @throws Throwable */ - public function findOne(mixed $condition): array|ActiveRecordInterface|null + public function findOne(mixed $condition): array|ActiveRecordModelInterface|null { return $this->findByCondition($condition)->one(); } @@ -855,7 +856,8 @@ public function findAll(mixed $condition): array */ protected function findByCondition(mixed $condition): static { - $arInstance = $this->getARInstance(); + $modelInstance = $this->getModelInstance(); + $activeRecord = $modelInstance->activeRecord(); if (!is_array($condition)) { $condition = [$condition]; @@ -863,13 +865,13 @@ protected function findByCondition(mixed $condition): static if (!DbArrayHelper::isAssociative($condition)) { /** query by primary key */ - $primaryKey = $arInstance->primaryKey(); + $primaryKey = $activeRecord->primaryKey(); if (isset($primaryKey[0])) { $pk = $primaryKey[0]; if (!empty($this->getJoins()) || !empty($this->getJoinWith())) { - $pk = $arInstance->getTableName() . '.' . $pk; + $pk = $modelInstance->tableName() . '.' . $pk; } /** @@ -878,11 +880,11 @@ protected function findByCondition(mixed $condition): static */ $condition = [$pk => array_values($condition)]; } else { - throw new InvalidConfigException('"' . $arInstance::class . '" must have a primary key.'); + throw new InvalidConfigException('"' . $modelInstance::class . '" must have a primary key.'); } } else { - $aliases = $arInstance->filterValidAliases($this); - $condition = $arInstance->filterCondition($condition, $aliases); + $aliases = $activeRecord->filterValidAliases($this); + $condition = $activeRecord->filterCondition($condition, $aliases); } return $this->setWhere($condition); @@ -905,18 +907,18 @@ public function sql(string|null $value): static return $this; } - public function getARInstance(): ActiveRecordInterface + public function getModelInstance(): ActiveRecordModelInterface { - if ($this->arClass instanceof ActiveRecordInterface) { - return clone $this->arClass; + if ($this->modelClass instanceof ActiveRecordModelInterface) { + return clone $this->modelClass; } - if ($this->arClass instanceof Closure) { - return ($this->arClass)(); + if ($this->modelClass instanceof Closure) { + return ($this->modelClass)(); } - /** @psalm-var class-string $class */ - $class = $this->arClass; + /** @psalm-var class-string $class */ + $class = $this->modelClass; return new $class(); } @@ -928,7 +930,7 @@ protected function index(array $rows): array private function createInstance(): static { - return (new static($this->arClass)) + return (new static($this->modelClass)) ->where($this->getWhere()) ->limit($this->getLimit()) ->offset($this->getOffset()) @@ -946,7 +948,7 @@ private function createInstance(): static ->withQueries($this->withQueries); } - private function populateOne(array $row): ActiveRecordInterface|array + private function populateOne(array $row): ActiveRecordModelInterface|array { return $this->populate([$row])[0]; } diff --git a/src/ActiveQueryInterface.php b/src/ActiveQueryInterface.php index ff94adb1d..7fe8e2111 100644 --- a/src/ActiveQueryInterface.php +++ b/src/ActiveQueryInterface.php @@ -23,7 +23,7 @@ * * A class implementing this interface should also use {@see ActiveQueryTrait} and {@see ActiveRelationTrait}. * - * @psalm-type ARClass = class-string|ActiveRecordInterface|Closure():ActiveRecordInterface + * @psalm-type ModelClass = class-string|ActiveRecordModelInterface|Closure():ActiveRecordModelInterface * @psalm-import-type IndexKey from ArArrayHelper */ interface ActiveQueryInterface extends QueryInterface @@ -35,8 +35,8 @@ interface ActiveQueryInterface extends QueryInterface * @throws InvalidConfigException * @throws Throwable * - * @return ActiveRecordInterface[]|array[] All rows of the query result. Each array element is an `array` or - * instance of {@see ActiveRecordInterface} representing a row of data, depends on {@see isAsArray()} result. + * @return ActiveRecordModelInterface[]|array[] All rows of the query result. Each array element is an `array` or + * instance of {@see ActiveRecordModelInterface} representing a row of data, depends on {@see isAsArray()} result. * Empty array if the query results in nothing. */ public function all(): array; @@ -102,7 +102,7 @@ public function with(array|string ...$with): static; * @param callable|null $callable A PHP callback for customizing the relation associated with the junction table. * Its signature should be `function($query)`, where `$query` is the query to be customized. */ - public function via(string $relationName, callable $callable = null): static; + public function via(string $relationName, callable|null $callable = null): static; /** * @return array|string|null the join condition to be used when this query is used in a relational context. @@ -208,7 +208,7 @@ public function innerJoinWith(array|string $with, array|bool $eagerLoading = tru * * Otherwise, the condition will be used in the `WHERE` part of a query. * - * Use this method to specify more conditions when declaring a relation in the {@see ActiveRecord} class: + * Use this method to specify more conditions when declaring a relation in the {@see ActiveRecordModel} class: * * ```php * public function getActiveUsers(): ActiveQuery @@ -258,7 +258,7 @@ public function orOnCondition(array|string $condition, array $params = []): stat /** * Specifies the junction table for a relational query. * - * Use this method to specify a junction table when declaring a relation in the {@see ActiveRecord} class: + * Use this method to specify a junction table when declaring a relation in the {@see ActiveRecordModel} class: * * ```php * public function getItems() @@ -276,10 +276,10 @@ public function orOnCondition(array|string $condition, array $params = []): stat * * @see via() */ - public function viaTable(string $tableName, array $link, callable $callable = null): static; + public function viaTable(string $tableName, array $link, callable|null $callable = null): static; /** - * Define an alias for the table defined in {@see arClass}. + * Define an alias for the table defined in {@see modelClass}. * * This method will adjust {@see from()} so that an already defined alias will be overwritten. * @@ -313,11 +313,11 @@ public function getTablesUsedInFrom(): array; public function getSql(): string|null; /** - * @return ActiveRecordInterface|Closure|string The AR class associated with this query. + * @return ActiveRecordModelInterface|Closure|string The AR class associated with this query. * - * @psalm-return ARClass + * @psalm-return ModelClass */ - public function getARClass(): string|ActiveRecordInterface|Closure; + public function getModelClass(): string|ActiveRecordModelInterface|Closure; /** * Creates an {@see ActiveQuery} instance with a given SQL statement. @@ -351,13 +351,13 @@ public function sql(string|null $value): static; * * @param array[] $rows The raw query result from a database. * - * @return ActiveRecordInterface[]|array[] The converted query result. + * @return ActiveRecordModelInterface[]|array[] The converted query result. * * @psalm-param list $rows * @psalm-return ( * $rows is non-empty-list - * ? non-empty-list - * : list + * ? non-empty-list + * : list * ) */ public function populate(array $rows): array; @@ -365,7 +365,7 @@ public function populate(array $rows): array; /** * Returns related record(s). * - * This method is invoked when a relation of an ActiveRecord is being accessed in a lazy fashion. + * This method is invoked when a relation of an ActiveRecordModel is being accessed in a lazy fashion. * * @throws Exception * @throws InvalidArgumentException @@ -373,9 +373,9 @@ public function populate(array $rows): array; * @throws ReflectionException * @throws Throwable if the relation is invalid. * - * @return ActiveRecordInterface|ActiveRecordInterface[]|array|array[]|null the related record(s). + * @return ActiveRecordModelInterface|ActiveRecordModelInterface[]|array|array[]|null the related record(s). */ - public function relatedRecords(): ActiveRecordInterface|array|null; + public function relatedRecords(): ActiveRecordModelInterface|array|null; /** * Returns a single active record instance by a primary key or an array of column values. @@ -394,7 +394,7 @@ public function relatedRecords(): ActiveRecordInterface|array|null; * Column names are limited to current records' table columns for SQL DBMS, or filtered otherwise to be limited to * simple filter conditions. * - * That this method will automatically call the `one()` method and return an {@see ActiveRecordInterface} instance. + * That this method will automatically call the `one()` method and return an {@see ActiveRecordModelInterface} instance. * * Note: As this is a shorthand method only, using more complex conditions, `like ['!=', 'id', 1]` will not work. * If you need to specify more complex conditions, in combination with {@see ActiveQuery::where()} instead. @@ -456,9 +456,9 @@ public function relatedRecords(): ActiveRecordInterface|array|null; * * @throws InvalidConfigException * - * @return ActiveRecordInterface|array|null Instance matching the condition, or `null` if nothing matches. + * @return ActiveRecordModelInterface|array|null Instance matching the condition, or `null` if nothing matches. */ - public function findOne(mixed $condition): array|ActiveRecordInterface|null; + public function findOne(mixed $condition): array|ActiveRecordModelInterface|null; /** * Returns a list of active record that matches the specified primary key value(s) or a set of column values. @@ -479,7 +479,7 @@ public function findOne(mixed $condition): array|ActiveRecordInterface|null; * Column names are limited to current records' table columns for SQL DBMS, or filtered otherwise to be limited * to simple filter conditions. * - * This method will automatically call the `all()` method and return an array of {@see ActiveRecordInterface} + * This method will automatically call the `all()` method and return an array of {@see ActiveRecordModelInterface} * instances. * * Note: As this is a shorthand method only, using more complex conditions, `like ['!=', 'id', 1]` will not work. @@ -554,7 +554,7 @@ public function isAsArray(): bool|null; /** * It's used to set the query options for the query. */ - public function primaryModel(ActiveRecordInterface|null $value): static; + public function primaryModel(ActiveRecordModelInterface|null $value): static; /** * It's used to set the query options for the query. @@ -604,9 +604,9 @@ public function getLink(): array; * @throws CircularReferenceException * @throws InvalidConfigException * @throws NotInstantiableException - * @return ActiveRecordInterface The model instance associated with this query. + * @return ActiveRecordModelInterface The model instance associated with this query. */ - public function getARInstance(): ActiveRecordInterface; + public function getModelInstance(): ActiveRecordModelInterface; /** * @return bool Whether this query represents a relation to more than one record. @@ -630,24 +630,25 @@ public function getMultiple(): bool; * @throws ReflectionException * @throws Throwable * - * @return ActiveRecordInterface|array|null The first row as an `array` or instance of {@see ActiveRecordInterface} + * @return ActiveRecordModelInterface|array|null The first row as an `array` or instance of {@see ActiveRecordModelInterface} * of the query result, depends on {@see isAsArray()} result. `null` if the query results in nothing. */ - public function one(): array|ActiveRecordInterface|null; + public function one(): array|ActiveRecordModelInterface|null; /** * Finds the related records and populates them into the primary models. * * @param string $name The relation name. - * @param ActiveRecordInterface[]|array[] $primaryModels Primary models. + * @param ActiveRecordModelInterface[]|array[] $primaryModels Primary models. * * @throws Exception * @throws InvalidArgumentException|InvalidConfigException|NotSupportedException|Throwable If {@see link()} is * invalid. - * @return ActiveRecordInterface[]|array[] The related models. * - * @psalm-param non-empty-list $primaryModels - * @psalm-param-out non-empty-list $primaryModels + * @return ActiveRecordModelInterface[]|array[] The related models. + * + * @psalm-param non-empty-list $primaryModels + * @psalm-param-out non-empty-list $primaryModels */ public function populateRelation(string $name, array &$primaryModels): array; } diff --git a/src/ActiveQueryTrait.php b/src/ActiveQueryTrait.php index bc2783b31..936c1be11 100644 --- a/src/ActiveQueryTrait.php +++ b/src/ActiveQueryTrait.php @@ -106,10 +106,11 @@ public function with(array|string ...$with): static * @param array[] $rows The rows to be converted. * * @throws InvalidConfigException - * @return ActiveRecordInterface[]|array[] The model instances. + * + * @return ActiveRecordModelInterface[]|array[] The model instances. * * @psalm-param non-empty-list $rows - * @psalm-return non-empty-list + * @psalm-return non-empty-list */ protected function createModels(array $rows): array { @@ -120,8 +121,8 @@ protected function createModels(array $rows): array if ($this->resultCallback !== null) { $rows = ($this->resultCallback)($rows); - if ($rows[0] instanceof ActiveRecordInterface) { - /** @psalm-var non-empty-list */ + if ($rows[0] instanceof ActiveRecordModelInterface) { + /** @psalm-var non-empty-list */ return $rows; } } @@ -129,8 +130,8 @@ protected function createModels(array $rows): array $models = []; foreach ($rows as $row) { - $arClass = $this->getARInstance(); - $arClass->populateRecord($row); + $arClass = $this->getModelInstance(); + $arClass->activeRecord()->populateRecord($row); $models[] = $arClass; } @@ -143,7 +144,7 @@ protected function createModels(array $rows): array * * @param array $with a list of relations that this query should be performed with. Please refer to {@see with()} * for details about specifying this parameter. - * @param ActiveRecordInterface[]|array[] $models the primary models (can be either AR instances or arrays) + * @param ActiveRecordModelInterface[]|array[] $models the primary models (can be either AR instances or arrays) * * @throws Exception * @throws InvalidArgumentException @@ -151,15 +152,15 @@ protected function createModels(array $rows): array * @throws ReflectionException * @throws Throwable * - * @psalm-param non-empty-list $models - * @psalm-param-out non-empty-list $models + * @psalm-param non-empty-list $models + * @psalm-param-out non-empty-list $models */ public function findWith(array $with, array &$models): void { $primaryModel = reset($models); - if (!$primaryModel instanceof ActiveRecordInterface) { - $primaryModel = $this->getARInstance(); + if (!$primaryModel instanceof ActiveRecordModelInterface) { + $primaryModel = $this->getModelInstance(); } $relations = $this->normalizeRelations($primaryModel, $with); @@ -177,7 +178,7 @@ public function findWith(array $with, array &$models): void /** * @return ActiveQueryInterface[] */ - private function normalizeRelations(ActiveRecordInterface $model, array $with): array + private function normalizeRelations(ActiveRecordModelInterface $model, array $with): array { $relations = []; diff --git a/src/ActiveRecord.php b/src/ActiveRecord.php index 2337efe4e..a8ffbfa96 100644 --- a/src/ActiveRecord.php +++ b/src/ActiveRecord.php @@ -15,7 +15,6 @@ use function array_keys; use function array_map; use function array_values; -use function get_object_vars; use function in_array; use function is_array; use function is_string; @@ -23,60 +22,7 @@ use function preg_replace; /** - * Active Record class which implements {@see ActiveRecordInterface} interface with the minimum set of methods. - * - * Active Record implements the [Active Record design pattern](https://en.wikipedia.org/wiki/Active_record). - * - * The premise behind Active Record is that an individual {@see ActiveRecord} object is associated with a specific row - * in a database table. The object's properties are mapped to the columns of the corresponding table. - * - * Referencing an Active Record property is equivalent to accessing the corresponding table column for that record. - * - * As an example, say that the `Customer` ActiveRecord class is associated with the `customer` table. - * - * This would mean that the class's `name` property is automatically mapped to the `name` column in `customer` table. - * Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of the - * `name` column for the table row, you can use the expression `$customer->name`. - * - * In this example, Active Record is providing an object-oriented interface for accessing data stored in the database. - * But Active Record provides much more functionality than this. - * - * To declare an ActiveRecord class, you need to extend {@see ActiveRecord} and implement the `getTableName` method: - * - * ```php - * class Customer extends ActiveRecord - * { - * public static function getTableName(): string - * { - * return 'customer'; - * } - * } - * ``` - * - * The `getTableName` method only has to return the name of the database table associated with the class. - * - * Class instances are obtained in one of two ways: - * - * Using the `new` operator to create a new, empty object. - * Using a method to fetch an existing record (or records) from the database. - * - * Below is an example showing some typical usage of ActiveRecord: - * - * ```php - * $user = new User($db); - * $user->name = 'Qiang'; - * $user->save(); // a new row is inserted into user table - * - * // the following will retrieve the user 'CeBe' from the database - * $userQuery = new ActiveQuery(User::class); - * $user = $userQuery->where(['name' => 'CeBe'])->one(); - * - * // this will get related records from orders table when relation is defined - * $orders = $user->orders; - * ``` - * - * For more details and usage information on ActiveRecord, - * {@see the [guide article on ActiveRecord](guide:db-active-record)} + * Active Record class which implements {@see ActiveRecordInterface} interface. * * @psalm-suppress ClassMustBeFinal */ @@ -99,7 +45,7 @@ public function filterCondition(array $condition, array $aliases = []): array $columnNames = $this->filterValidColumnNames($aliases); foreach ($condition as $key => $value) { - if (is_string($key) && !in_array($this->db()->getQuoter()->quoteSql($key), $columnNames, true)) { + if (is_string($key) && !in_array($this->model->db()->getQuoter()->quoteSql($key), $columnNames, true)) { throw new InvalidArgumentException( 'Key "' . $key . '" is not a column name and can not be used as a filter' ); @@ -129,10 +75,10 @@ public function filterValidAliases(ActiveQuery $query): array */ public function getTableSchema(): TableSchemaInterface { - $tableSchema = $this->db()->getSchema()->getTableSchema($this->getTableName()); + $tableSchema = $this->model->db()->getSchema()->getTableSchema($this->model->tableName()); if ($tableSchema === null) { - throw new InvalidConfigException('The table does not exist: ' . $this->getTableName()); + throw new InvalidConfigException('The table does not exist: ' . $this->model->tableName()); } return $tableSchema; @@ -194,7 +140,7 @@ public function primaryKey(): array */ public function refresh(): bool { - $query = $this->instantiateQuery(static::class); + $query = $this->instantiateQuery($this->model::class); /** @var string $tableName */ $tableName = key($query->getTablesUsedInFrom()); @@ -219,8 +165,8 @@ public function refresh(): bool protected function filterValidColumnNames(array $aliases): array { $columnNames = []; - $tableName = $this->getTableName(); - $quoter = $this->db()->getQuoter(); + $tableName = $this->model->tableName(); + $quoter = $this->model->db()->getQuoter(); $quotedTableName = $quoter->quoteTableName($tableName); foreach ($this->getTableSchema()->getColumnNames() as $columnName) { @@ -239,15 +185,10 @@ protected function filterValidColumnNames(array $aliases): array return $columnNames; } - protected function propertyValuesInternal(): array - { - return get_object_vars($this); - } - - protected function insertInternal(array $propertyNames = null): bool + protected function insertInternal(array|null $propertyNames = null): bool { $values = $this->newValues($propertyNames); - $primaryKeys = $this->db()->createCommand()->insertWithReturningPks($this->getTableName(), $values); + $primaryKeys = $this->model->db()->createCommand()->insertWithReturningPks($this->model->tableName(), $values); if ($primaryKeys === false) { return false; @@ -265,9 +206,4 @@ protected function insertInternal(array $propertyNames = null): bool return true; } - - protected function populateProperty(string $name, mixed $value): void - { - $this->$name = $value; - } } diff --git a/src/ActiveRecordInterface.php b/src/ActiveRecordInterface.php index f6c75f0bd..ae8b7b08a 100644 --- a/src/ActiveRecordInterface.php +++ b/src/ActiveRecordInterface.php @@ -5,13 +5,15 @@ namespace Yiisoft\ActiveRecord; use Throwable; -use Yiisoft\Db\Connection\ConnectionInterface; use Yiisoft\Db\Constant\ColumnType; use Yiisoft\Db\Exception\Exception; use Yiisoft\Db\Exception\InvalidArgumentException; use Yiisoft\Db\Exception\InvalidConfigException; use Yiisoft\Db\Exception\NotSupportedException; +/** + * This interface is used by {@see ActiveRecordModelInterface}. + */ interface ActiveRecordInterface { /** @@ -30,11 +32,6 @@ public function propertyNames(): array; */ public function columnType(string $propertyName): string; - /** - * Returns the database connection used by the Active Record instance. - */ - public function db(): ConnectionInterface; - /** * Deletes the table row corresponding to this active record. * @@ -85,13 +82,13 @@ public function deleteAll(array $condition = []): int; * Returns a value indicating whether the given active record is the same as the current one. * * The comparison is made by comparing the table names and the primary key values of the two active records. If one - * of the records {@see getIsNewRecord|is new} they're also considered not equal. + * of the records {@see isNewRecord|is new} they're also considered not equal. * - * @param self $record Record to compare to. + * @param ActiveRecordModelInterface $record Record to compare to. * * @return bool Whether the two active records refer to the same row in the same database table. */ - public function equals(self $record): bool; + public function equals(ActiveRecordModelInterface $record): bool; /** * Filters array condition before it's assigned to a Query filter. @@ -149,7 +146,7 @@ public function propertyValues(array|null $names = null, array $except = []): ar * * @return bool Whether the record is new and should be inserted when calling {@see save()}. */ - public function getIsNewRecord(): bool; + public function isNewRecord(): bool; /** * Returns the old primary key value(s). @@ -194,22 +191,6 @@ public function getOldPrimaryKey(bool $asArray = false): mixed; */ public function getPrimaryKey(bool $asArray = false): mixed; - /** - * Return the name of the table associated with this AR class. - * - * ```php - * final class User extends ActiveRecord - * { - * public string const TABLE_NAME = 'user'; - * - * public function getTableName(): string - * { - * return self::TABLE_NAME; - * } - * } - */ - public function getTableName(): string; - /** * Returns a value indicating whether the record has a property with the specified name. * @@ -285,7 +266,7 @@ public function isPropertyChangedNonStrict(string $name): bool; * * @return bool Whether relation has been populated with records. * - * {@see relationQuery()} + * {@see ActiveRecordModelInterface::relationQuery()} */ public function isRelationPopulated(string $name): bool; @@ -303,12 +284,12 @@ public function isRelationPopulated(string $name): bool; * This method requires that the primary key value isn't `null`. * * @param string $relationName The relation name, for example, `orders` (case-sensitive). - * @param self $arClass The record to be linked with the current one. + * @param ActiveRecordModelInterface $model The record to be linked with the current one. * @param array $extraColumns More column values to be saved into the junction table. This parameter is only * meaningful for a relationship involving a junction table (that's a relation set with * {@see ActiveQueryInterface::via()}). */ - public function link(string $relationName, self $arClass, array $extraColumns = []): void; + public function link(string $relationName, ActiveRecordModelInterface $model, array $extraColumns = []): void; /** * Populates the named relation with the related records. @@ -316,9 +297,10 @@ public function link(string $relationName, self $arClass, array $extraColumns = * Note that this method doesn't check if the relation exists or not. * * @param string $name The relation name, for example, `orders` (case-sensitive). - * @param array|array[]|self|self[]|null $records The related records to be populated into the relation. + * @param ActiveRecordModelInterface|ActiveRecordModelInterface[]|array|array[]|null $records The related records + * to be populated into the relation. */ - public function populateRelation(string $name, array|self|null $records): void; + public function populateRelation(string $name, array|ActiveRecordModelInterface|null $records): void; /** * Returns the primary key name(s) for this AR class. @@ -343,36 +325,9 @@ public function primaryKey(): array; * * @param string $name The relation name, for example, `orders` (case-sensitive). * - * @return array|array[]|self|self[]|null The relation object. - */ - public function relation(string $name): self|array|null; - - /** - * Returns the relation query object with the specified name. - * - * A relation is defined by a getter method which returns an object implementing the {@see ActiveQueryInterface} - * (normally this would be a relational {@see ActiveQuery} object). - * - * Relations can be defined using {@see hasOne()} and {@see hasMany()} methods. For example: - * - * ```php - * public function relationQuery(string $name): ActiveQueryInterface - * { - * return match ($name) { - * 'orders' => $this->hasMany(Order::class, ['customer_id' => 'id']), - * 'country' => $this->hasOne(Country::class, ['id' => 'country_id']), - * default => parent::relationQuery($name), - * }; - * } - * ``` - * - * @param string $name The relation name, for example, `orders` (case-sensitive). - * - * @throws InvalidArgumentException - * - * @return ActiveQueryInterface The relational query object. + * @return ActiveRecordModelInterface|ActiveRecordModelInterface[]|array|array[]|null The relation object. */ - public function relationQuery(string $name): ActiveQueryInterface; + public function relation(string $name): ActiveRecordModelInterface|array|null; /** * Resets relation data for the specified name. @@ -384,8 +339,8 @@ public function resetRelation(string $name): void; /** * Saves the current record. * - * This method will call {@see insert()} when {@see getIsNewRecord()|isNewRecord} is true, or {@see update()} when - * {@see getIsNewRecord()|isNewRecord} is false. + * This method will call {@see insert()} when {@see isNewRecord()|isNewRecord} is true, or {@see update()} when + * {@see isNewRecord()|isNewRecord} is false. * * For example, to save a customer record: * @@ -511,15 +466,15 @@ public function updateProperties(array $properties): int; * * The record with the foreign key of the relationship will be deleted if `$delete` is true. * - * Otherwise, the foreign key will be set `null` and the record will be saved without validation. + * Otherwise, the foreign key will be set s`null` and the record will be saved without validation. * * @param string $relationName The relation name, for example, `orders` (case-sensitive). - * @param self $arClass The active record to be unlinked from the current one. + * @param ActiveRecordModelInterface $model The active record model to be unlinked from the current one. * @param bool $delete Whether to delete the active record that contains the foreign key. * If false, the active record's foreign key will be set `null` and saved. * If true, the active record containing the foreign key will be deleted. */ - public function unlink(string $relationName, self $arClass, bool $delete = false): void; + public function unlink(string $relationName, ActiveRecordModelInterface $model, bool $delete = false): void; /** * Returns the old property values. diff --git a/src/ActiveRecordModel.php b/src/ActiveRecordModel.php new file mode 100644 index 000000000..8dc1c8c75 --- /dev/null +++ b/src/ActiveRecordModel.php @@ -0,0 +1,79 @@ +name`. + * + * In this example, Active Record is providing an object-oriented interface for accessing data stored in the database. + * But Active Record provides much more functionality than this. + * + * To declare an Active Record model class, you need to extend {@see ActiveRecordModel} and implement the `tableName()` + * method: + * + * ```php + * class Customer extends ActiveRecordModel + * { + * public static function tableName(): string + * { + * return 'customer'; + * } + * } + * ``` + * + * The `tableName()` method only has to return the name of the database table associated with the class. + * + * Class instances are obtained in one of two ways: + * + * Using the `new` operator to create a new, empty object. + * Using a method to fetch an existing record (or records) from the database. + * + * Below is an example showing some typical usage of Active Record models: + * + * ```php + * $user = new User(); + * $user->name = 'Qiang'; + * $user->save(); // a new row is inserted into user table + * + * // the following will retrieve the user 'CeBe' from the database + * $userQuery = new ActiveQuery(User::class); + * $user = $userQuery->where(['name' => 'CeBe'])->one(); + * + * // this will get related records from orders table when relation is defined + * $orders = $user->orders; + * ``` + * + * For more details and usage information on ActiveRecord, + * {@see the [guide article on ActiveRecord](guide:db-active-record)} + * + * @psalm-suppress ClassMustBeFinal + */ +class ActiveRecordModel extends AbstractActiveRecordModel +{ + public function populateProperty(string $name, mixed $value): void + { + $this->$name = $value; + } + + public function propertyValues(): array + { + return get_object_vars($this); + } +} diff --git a/src/ActiveRecordModelInterface.php b/src/ActiveRecordModelInterface.php new file mode 100644 index 000000000..3202d39f2 --- /dev/null +++ b/src/ActiveRecordModelInterface.php @@ -0,0 +1,90 @@ + $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id']), + * 'country' => $this->activeRecord()->hasOne(Country::class, ['id' => 'country_id']), + * default => parent::relationQuery($name), + * }; + * } + * ``` + * + * @param string $name The relation name, for example, `orders` (case-sensitive). + * + * @throws InvalidArgumentException + * + * @return ActiveQueryInterface The relational query object. + */ + public function relationQuery(string $name): ActiveQueryInterface; + + /** + * Return the name of the table associated with this AR class. + * + * ```php + * final class User extends ActiveRecordModel + * { + * public string const TABLE_NAME = 'user'; + * + * public function tableName(): string + * { + * return self::TABLE_NAME; + * } + * } + */ + public function tableName(): string; + + /** + * Sets the value of the named property. + * + * @param string $name The property name. + * @param mixed $value The property value. + * + * @internal This method is for internal use only. + */ + public function populateProperty(string $name, mixed $value): void; + + /** + * Returns property values. + * + * @throws Exception + * @throws InvalidConfigException + * + * @return array Property values (name => value). + * @psalm-return array + * + * @internal This method is for internal use only. + */ + public function propertyValues(): array; +} diff --git a/src/ActiveRelationTrait.php b/src/ActiveRelationTrait.php index aab04161d..4e6c5bb7f 100644 --- a/src/ActiveRelationTrait.php +++ b/src/ActiveRelationTrait.php @@ -40,7 +40,7 @@ trait ActiveRelationTrait { private bool $multiple = false; - private ActiveRecordInterface|null $primaryModel = null; + private ActiveRecordModelInterface|null $primaryModel = null; /** @psalm-var string[] */ private array $link = []; /** @@ -102,7 +102,7 @@ public function __clone() * * @return static the relation object itself. */ - public function via(string $relationName, callable $callable = null): static + public function via(string $relationName, callable|null $callable = null): static { if ($this->primaryModel === null) { throw new InvalidConfigException('Setting via is only supported for relational queries.'); @@ -188,9 +188,9 @@ public function inverseOf(string $relationName): static * @throws ReflectionException * @throws Throwable If the relation is invalid. * - * @return ActiveRecordInterface|array|null The related record(s). + * @return ActiveRecordModelInterface|array|null The related record(s). */ - public function relatedRecords(): ActiveRecordInterface|array|null + public function relatedRecords(): ActiveRecordModelInterface|array|null { return $this->multiple ? $this->all() : $this->one(); } @@ -198,12 +198,12 @@ public function relatedRecords(): ActiveRecordInterface|array|null /** * If applicable, populate the query's primary model into the related records' inverse relationship. * - * @param ActiveRecordInterface[]|array[] $result the array of related records as generated by {@see populate()} + * @param ActiveRecordModelInterface[]|array[] $result the array of related records as generated by {@see populate()} * * @throws InvalidConfigException * - * @psalm-param non-empty-list $result - * @psalm-param-out non-empty-list $result + * @psalm-param non-empty-list $result + * @psalm-param-out non-empty-list $result */ private function addInverseRelations(array &$result): void { @@ -213,16 +213,16 @@ private function addInverseRelations(array &$result): void $relatedModel = reset($result); - if ($relatedModel instanceof ActiveRecordInterface) { + if ($relatedModel instanceof ActiveRecordModelInterface) { $inverseRelation = $relatedModel->relationQuery($this->inverseOf); $primaryModel = $inverseRelation->getMultiple() ? [$this->primaryModel] : $this->primaryModel; - /** @var ActiveRecordInterface $relatedModel */ + /** @var ActiveRecordModelInterface $relatedModel */ foreach ($result as $relatedModel) { - $relatedModel->populateRelation($this->inverseOf, $primaryModel); + $relatedModel->activeRecord()->populateRelation($this->inverseOf, $primaryModel); } } else { - $inverseRelation = $this->getARInstance()->relationQuery($this->inverseOf); + $inverseRelation = $this->getModelInstance()->relationQuery($this->inverseOf); $primaryModel = $inverseRelation->getMultiple() ? [$this->primaryModel] : $this->primaryModel; /** @var array $relatedModel */ @@ -233,10 +233,10 @@ private function addInverseRelations(array &$result): void } /** - * @psalm-param non-empty-list $primaryModels - * @psalm-param-out non-empty-list $primaryModels + * @psalm-param non-empty-list $primaryModels + * @psalm-param-out non-empty-list $primaryModels * - * @return ActiveRecordInterface[]|array[] + * @return ActiveRecordModelInterface[]|array[] */ public function populateRelation(string $name, array &$primaryModels): array { @@ -266,8 +266,8 @@ public function populateRelation(string $name, array &$primaryModels): array $primaryModel = $primaryModels[0]; - if ($primaryModel instanceof ActiveRecordInterface) { - $primaryModel->populateRelation($name, $models[0]); + if ($primaryModel instanceof ActiveRecordModelInterface) { + $primaryModel->activeRecord()->populateRelation($name, $models[0]); } else { /** * @psalm-var non-empty-list $primaryModels @@ -322,7 +322,7 @@ public function populateRelation(string $name, array &$primaryModels): array /** * @throws \Yiisoft\Definitions\Exception\InvalidConfigException * - * @psalm-param non-empty-list $primaryModels + * @psalm-param non-empty-list $primaryModels */ private function populateInverseRelation( array &$models, @@ -337,7 +337,7 @@ private function populateInverseRelation( /** @var ActiveQuery $relation */ $relation = is_array($model) - ? $this->getARInstance()->relationQuery($name) + ? $this->getModelInstance()->relationQuery($name) : $model->relationQuery($name); $link = $relation->getLink(); @@ -374,8 +374,8 @@ private function populateRelationFromBuckets( : array_merge(...array_intersect_key($buckets, array_flip($keys)))), }; - if ($model instanceof ActiveRecordInterface) { - $model->populateRelation($name, $value); + if ($model instanceof ActiveRecordModelInterface) { + $model->activeRecord()->populateRelation($name, $value); } else { /** @var array $model */ $model[$name] = $value; @@ -385,8 +385,8 @@ private function populateRelationFromBuckets( private function buildBuckets( array $models, - array $viaModels = null, - self $viaQuery = null + array|null $viaModels = null, + self|null $viaQuery = null ): array { if ($viaModels !== null) { $map = []; @@ -491,7 +491,7 @@ private function prefixKeyColumns(array $columnNames): array { if (!empty($this->join) || !empty($this->joinWith)) { if (empty($this->from)) { - $alias = $this->getARInstance()->getTableName(); + $alias = $this->getModelInstance()->tableName(); } else { $alias = array_key_first($this->from); @@ -509,9 +509,9 @@ private function prefixKeyColumns(array $columnNames): array } /** - * @param ActiveRecordInterface[]|array[] $models + * @param ActiveRecordModelInterface[]|array[] $models * - * @throws \Yiisoft\Definitions\Exception\InvalidConfigException + * @throws InvalidConfigException */ protected function filterByModels(array $models): void { @@ -525,10 +525,10 @@ protected function filterByModels(array $models): void /** @var string $linkedProperty single key */ $linkedProperty = reset($this->link); - if ($model instanceof ActiveRecordInterface) { - /** @var ActiveRecordInterface $model */ + if ($model instanceof ActiveRecordModelInterface) { + /** @var ActiveRecordModelInterface $model */ foreach ($models as $model) { - $value = $model->get($linkedProperty); + $value = $model->activeRecord()->get($linkedProperty); if ($value !== null) { if (is_array($value)) { @@ -569,7 +569,7 @@ protected function filterByModels(array $models): void /** @var string $propertyName */ $propertyName = array_key_first($this->link); - match ($this->getARInstance()->columnType($propertyName)) { + match ($this->getModelInstance()->activeRecord()->columnType($propertyName)) { ColumnType::ARRAY => $this->andWhere(new ArrayOverlapsCondition($columnName, $values)), ColumnType::JSON => $this->andWhere(new JsonOverlapsCondition($columnName, $values)), default => $this->andWhere(new InCondition($columnName, 'IN', $values)), @@ -580,10 +580,10 @@ protected function filterByModels(array $models): void $nulls = array_fill_keys($this->link, null); - if ($model instanceof ActiveRecordInterface) { - /** @var ActiveRecordInterface $model */ + if ($model instanceof ActiveRecordModelInterface) { + /** @var ActiveRecordModelInterface $model */ foreach ($models as $model) { - $value = $model->propertyValues($this->link); + $value = $model->activeRecord()->propertyValues($this->link); if (!empty($value)) { $values[] = array_combine($columnNames, array_merge($nulls, $value)); @@ -609,7 +609,7 @@ protected function filterByModels(array $models): void $this->andWhere(new InCondition($columnNames, 'IN', $values)); } - private function getModelKeys(ActiveRecordInterface|array $model, array $properties): array + private function getModelKeys(ActiveRecordModelInterface|array $model, array $properties): array { $key = []; @@ -623,7 +623,7 @@ private function getModelKeys(ActiveRecordInterface|array $model, array $propert } } else { foreach ($properties as $property) { - $value = $model->get($property); + $value = $model->activeRecord()->get($property); if ($value !== null) { $key[] = is_array($value) @@ -641,14 +641,15 @@ private function getModelKeys(ActiveRecordInterface|array $model, array $propert } /** - * @param ActiveRecordInterface[]|array[] $primaryModels either array of AR instances or arrays. + * @param ActiveRecordModelInterface[]|array[] $primaryModels either array of AR instances or arrays. * * @throws Exception * @throws Throwable * @throws \Yiisoft\Definitions\Exception\InvalidConfigException + * * @return array[] * - * @psalm-param non-empty-list $primaryModels + * @psalm-param non-empty-list $primaryModels */ private function findJunctionRows(array $primaryModels): array { @@ -664,11 +665,11 @@ public function getMultiple(): bool } /** - * @return ActiveRecordInterface|null the primary model of a relational query. + * @return ActiveRecordModelInterface|null the primary model of a relational query. * * This is used only in lazy loading with dynamic query options. */ - public function getPrimaryModel(): ActiveRecordInterface|null + public function getPrimaryModel(): ActiveRecordModelInterface|null { return $this->primaryModel; } @@ -693,7 +694,7 @@ public function multiple(bool $value): static return $this; } - public function primaryModel(ActiveRecordInterface|null $value): static + public function primaryModel(ActiveRecordModelInterface|null $value): static { $this->primaryModel = $value; diff --git a/src/ArArrayHelper.php b/src/ArArrayHelper.php index 34f5f8477..973f01253 100644 --- a/src/ArArrayHelper.php +++ b/src/ArArrayHelper.php @@ -20,7 +20,7 @@ /** * Array manipulation methods for ActiveRecord. * - * @psalm-type Row = ActiveRecordInterface|array + * @psalm-type Row = ActiveRecordModelInterface|array * @psalm-type IndexKey = string|Closure(Row):array-key */ final class ArArrayHelper @@ -28,7 +28,7 @@ final class ArArrayHelper /** * Returns the values of a specified column in an array. * - * The input array should be multidimensional or an array of {@see ActiveRecordInterface} instances. + * The input array should be multidimensional or an array of {@see ActiveRecordModelInterface} instances. * * For example, * @@ -41,7 +41,7 @@ final class ArArrayHelper * // the result is: ['123', '345'] * ``` * - * @param ActiveRecordInterface[]|array[] $array Array to extract values from. + * @param ActiveRecordModelInterface[]|array[] $array Array to extract values from. * @param string $name The column name. * * @return array The list of column values. @@ -49,22 +49,22 @@ final class ArArrayHelper public static function getColumn(array $array, string $name): array { return array_map( - static fn (ActiveRecordInterface|array $element): mixed => self::getValueByPath($element, $name), + static fn (ActiveRecordModelInterface|array $element): mixed => self::getValueByPath($element, $name), $array ); } /** - * Retrieves a value from the array by the given key or from the {@see ActiveRecordInterface} instance + * Retrieves a value from the array by the given key or from the {@see ActiveRecordModelInterface} instance * by the given property or relation name. * * If the key doesn't exist, the default value will be returned instead. * * The key may be specified in a dot format to retrieve the value of a sub-array or a property or relation of the - * {@see ActiveRecordInterface} instance. + * {@see ActiveRecordModelInterface} instance. * * In particular, if the key is `x.y.z`, then the returned value would be `$array['x']['y']['z']` or - * `$array->x->y->z` (if `$array` is an {@see ActiveRecordInterface} instance). + * `$array->x->y->z` (if `$array` is an {@see ActiveRecordModelInterface} instance). * * Note that if the array already has an element `x.y.z`, then its value will be returned instead of going through * the sub-arrays. @@ -74,32 +74,35 @@ public static function getColumn(array $array, string $name): array * ```php * // working with an array * $username = ArArrayHelper::getValueByPath($array, 'username'); - * // working with an {@see ActiveRecordInterface} instance + * // working with an {@see ActiveRecordModelInterface} instance * $username = ArArrayHelper::getValueByPath($user, 'username'); - * // using dot format to retrieve the property of an {@see ActiveRecordInterface} instance + * // using dot format to retrieve the property of an {@see ActiveRecordModelInterface} instance * $street = ArArrayHelper::getValue($users, 'address.street'); * ``` * - * @param ActiveRecordInterface|array $array Array or an {@see ActiveRecordInterface} instance to extract value from. + * @param ActiveRecordModelInterface|array $array Array or an {@see ActiveRecordModelInterface} instance to extract + * value from. * @param string $key Key name of the array element or a property or relation name - * of the {@see ActiveRecordInterface} instance. + * of the {@see ActiveRecordModelInterface} instance. * @param mixed|null $default The default value to be returned if the specified `$key` doesn't exist. * * @return mixed The value of the element if found, default value otherwise */ - public static function getValueByPath(ActiveRecordInterface|array $array, string $key, mixed $default = null): mixed + public static function getValueByPath(ActiveRecordModelInterface|array $array, string $key, mixed $default = null): mixed { - if ($array instanceof ActiveRecordInterface) { - if ($array->hasProperty($key)) { - return $array->get($key); + if ($array instanceof ActiveRecordModelInterface) { + $activeRecord = $array->activeRecord(); + + if ($activeRecord->hasProperty($key)) { + return $activeRecord->get($key); } if (property_exists($array, $key)) { return array_key_exists($key, get_object_vars($array)) ? $array->$key : $default; } - if ($array->isRelationPopulated($key)) { - return $array->relation($key); + if ($activeRecord->isRelationPopulated($key)) { + return $activeRecord->relation($key); } } elseif (array_key_exists($key, $array)) { return $array[$key]; @@ -118,7 +121,7 @@ public static function getValueByPath(ActiveRecordInterface|array $array, string /** * Indexes an array of rows with the specified column value as keys. * - * The input array should be multidimensional or an array of {@see ActiveRecordInterface} instances. + * The input array should be multidimensional or an array of {@see ActiveRecordModelInterface} instances. * * For example, * @@ -131,11 +134,11 @@ public static function getValueByPath(ActiveRecordInterface|array $array, string * // the result is: ['123' => ['id' => '123', 'data' => 'abc'], '345' => ['id' => '345', 'data' => 'def']] * ``` * - * @param ActiveRecordInterface[]|array[] $rows Array to populate. + * @param ActiveRecordModelInterface[]|array[] $rows Array to populate. * @param Closure|string|null $indexBy The column name or anonymous function that specifies the index by which to * populate the array of rows. * - * @return ActiveRecordInterface[]|array[] + * @return ActiveRecordModelInterface[]|array[] * * @psalm-template TRow of Row * @psalm-param array $rows @@ -175,8 +178,8 @@ public static function toArray(array|object $object): array return $object; } - if ($object instanceof ActiveRecordInterface) { - return $object->propertyValues(); + if ($object instanceof ActiveRecordModelInterface) { + return $object->activeRecord()->propertyValues(); } if ($object instanceof Traversable) { diff --git a/src/Trait/ArrayAccessTrait.php b/src/Trait/ArrayAccessTrait.php index 9e9fef60d..468246b6f 100644 --- a/src/Trait/ArrayAccessTrait.php +++ b/src/Trait/ArrayAccessTrait.php @@ -6,33 +6,16 @@ use InvalidArgumentException; use Yiisoft\ActiveRecord\ActiveRecordInterface; +use Yiisoft\ActiveRecord\ActiveRecordModelInterface; use function is_array; use function property_exists; /** - * Trait to implement {@see ArrayAccess} interface for ActiveRecord. + * Trait to implement {@see ArrayAccess} interface for ActiveRecordModel. * - * @method mixed get(string $name) - * @see ActiveRecordInterface::get() - * - * @method bool hasProperty(string $name) - * @see ActiveRecordInterface::hasProperty() - * - * @method void set(string $name, mixed $value) - * @see ActiveRecordInterface::set() - * - * @method ActiveRecordInterface|array|null relation(string $name) - * @see ActiveRecordInterface::relation() - * - * @method bool isRelationPopulated(string $name) - * @see ActiveRecordInterface::isRelationPopulated() - * - * @method void populateRelation(string $name, ActiveRecordInterface|array|null $record) - * @see ActiveRecordInterface::populateRelation() - * - * @method void resetRelation(string $name) - * @see ActiveRecordInterface::resetRelation() + * @method ActiveRecordInterface activeRecord() + * @see ActiveRecordModelInterface::activeRecord() */ trait ArrayAccessTrait { @@ -49,16 +32,18 @@ trait ArrayAccessTrait */ public function offsetExists(mixed $offset): bool { - if ($this->hasProperty($offset)) { - return $this->get($offset) !== null; + $activeRecord = $this->activeRecord(); + + if ($activeRecord->hasProperty($offset)) { + return $activeRecord->get($offset) !== null; } if (property_exists($this, $offset)) { return isset($this->$offset); } - if ($this->isRelationPopulated($offset)) { - return $this->relation($offset) !== null; + if ($activeRecord->isRelationPopulated($offset)) { + return $activeRecord->relation($offset) !== null; } return false; @@ -69,15 +54,17 @@ public function offsetExists(mixed $offset): bool */ public function offsetGet(mixed $offset): mixed { - if ($this->hasProperty($offset)) { - return $this->get($offset); + $activeRecord = $this->activeRecord(); + + if ($activeRecord->hasProperty($offset)) { + return $activeRecord->get($offset); } if (property_exists($this, $offset)) { return $this->$offset ?? null; } - return $this->relation($offset); + return $activeRecord->relation($offset); } /** @@ -91,8 +78,10 @@ public function offsetGet(mixed $offset): mixed */ public function offsetSet(mixed $offset, mixed $value): void { - if ($this->hasProperty($offset)) { - $this->set($offset, $value); + $activeRecord = $this->activeRecord(); + + if ($activeRecord->hasProperty($offset)) { + $activeRecord->set($offset, $value); return; } @@ -102,7 +91,7 @@ public function offsetSet(mixed $offset, mixed $value): void } if ($value instanceof ActiveRecordInterface || is_array($value) || $value === null) { - $this->populateRelation($offset, $value); + $activeRecord->populateRelation($offset, $value); return; } @@ -120,12 +109,14 @@ public function offsetSet(mixed $offset, mixed $value): void */ public function offsetUnset(mixed $offset): void { - if ($this->hasProperty($offset) || property_exists($this, $offset)) { - $this->set($offset, null); + $activeRecord = $this->activeRecord(); + + if ($activeRecord->hasProperty($offset) || property_exists($this, $offset)) { + $activeRecord->set($offset, null); unset($this->$offset); return; } - $this->resetRelation($offset); + $activeRecord->resetRelation($offset); } } diff --git a/src/Trait/ArrayIteratorTrait.php b/src/Trait/ArrayIteratorTrait.php index 35c6ff382..238e51a9a 100644 --- a/src/Trait/ArrayIteratorTrait.php +++ b/src/Trait/ArrayIteratorTrait.php @@ -6,12 +6,14 @@ use ArrayIterator; use IteratorAggregate; +use Yiisoft\ActiveRecord\ActiveRecordInterface; +use Yiisoft\ActiveRecord\ActiveRecordModelInterface; /** - * Trait to implement {@see IteratorAggregate} interface for ActiveRecord. + * Trait to implement {@see IteratorAggregate} interface for ActiveRecordModel. * - * @method array propertyValues(array|null $names = null, array $except = []) - * @see ActiveRecordInterface::propertyValues() + * @method ActiveRecordInterface activeRecord() + * @see ActiveRecordModelInterface::activeRecord() */ trait ArrayIteratorTrait { @@ -24,7 +26,7 @@ trait ArrayIteratorTrait */ public function getIterator(): ArrayIterator { - $values = $this->propertyValues(); + $values = $this->activeRecord()->propertyValues(); return new ArrayIterator($values); } diff --git a/src/Trait/ArrayableTrait.php b/src/Trait/ArrayableTrait.php index e9a5cd79f..67b3c6019 100644 --- a/src/Trait/ArrayableTrait.php +++ b/src/Trait/ArrayableTrait.php @@ -5,20 +5,17 @@ namespace Yiisoft\ActiveRecord\Trait; use Closure; -use Yiisoft\ActiveRecord\AbstractActiveRecord; use Yiisoft\ActiveRecord\ActiveRecordInterface; +use Yiisoft\ActiveRecord\ActiveRecordModelInterface; use function array_combine; use function array_keys; /** - * Trait to implement {@see \Yiisoft\Arrays\ArrayableInterface} interface for ActiveRecord. + * Trait to implement {@see \Yiisoft\Arrays\ArrayableInterface} interface for ActiveRecordModel. * - * @method string[] propertyNames() - * @see ActiveRecordInterface::propertyNames() - * - * @method array getRelatedRecords() - * @see AbstractActiveRecord::getRelatedRecords() + * @method ActiveRecordInterface activeRecord() + * @see ActiveRecordModelInterface::activeRecord() */ trait ArrayableTrait { @@ -30,7 +27,7 @@ trait ArrayableTrait */ public function extraFields(): array { - $fields = array_keys($this->getRelatedRecords()); + $fields = array_keys($this->activeRecord()->getRelatedRecords()); return array_combine($fields, $fields); } @@ -40,7 +37,7 @@ public function extraFields(): array */ public function fields(): array { - $fields = $this->propertyNames(); + $fields = $this->activeRecord()->propertyNames(); return array_combine($fields, $fields); } diff --git a/src/Trait/CustomConnectionTrait.php b/src/Trait/CustomConnectionTrait.php index 713500c15..31d560695 100644 --- a/src/Trait/CustomConnectionTrait.php +++ b/src/Trait/CustomConnectionTrait.php @@ -4,14 +4,14 @@ namespace Yiisoft\ActiveRecord\Trait; -use Yiisoft\ActiveRecord\AbstractActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModelInterface; use Yiisoft\ActiveRecord\ConnectionProvider; use Yiisoft\Db\Connection\ConnectionInterface; /** - * Trait to implement custom connection name for ActiveRecord. + * Trait to implement custom connection name for ActiveRecordModel. * - * @see AbstractActiveRecord::db() + * @see ActiveRecordModelInterface::db() */ trait CustomConnectionTrait { diff --git a/src/Trait/CustomTableNameTrait.php b/src/Trait/CustomTableNameTrait.php index 3a752a171..bb8c33ce9 100644 --- a/src/Trait/CustomTableNameTrait.php +++ b/src/Trait/CustomTableNameTrait.php @@ -5,9 +5,9 @@ namespace Yiisoft\ActiveRecord\Trait; /** - * Trait to implement custom table name for ActiveRecord. + * Trait to implement custom table name for ActiveRecordModel. * - * @see ActiveRecordInterface::getTableName() + * @see ActiveRecordModelInterface::tableName() */ trait CustomTableNameTrait { @@ -23,8 +23,8 @@ public function withTableName(string $tableName): static return $new; } - public function getTableName(): string + public function tableName(): string { - return $this->tableName ??= parent::getTableName(); + return $this->tableName ??= parent::tableName(); } } diff --git a/src/Trait/FactoryTrait.php b/src/Trait/FactoryTrait.php index f172d3bfd..9b6ed39f1 100644 --- a/src/Trait/FactoryTrait.php +++ b/src/Trait/FactoryTrait.php @@ -7,14 +7,14 @@ use Closure; use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecordInterface; +use Yiisoft\ActiveRecord\ActiveRecordModelInterface; use Yiisoft\Factory\Factory; use function is_string; use function method_exists; /** - * Trait to add factory support to ActiveRecord. + * Trait to add factory support to ActiveRecordModel. * * @see AbstractActiveRecord::instantiateQuery() */ @@ -32,26 +32,26 @@ public function withFactory(Factory $factory): static return $new; } - public function instantiateQuery(string|ActiveRecordInterface|Closure $arClass): ActiveQueryInterface + public function instantiateQuery(string|ActiveRecordModelInterface|Closure $modelClass): ActiveQueryInterface { if (!isset($this->factory)) { - return new ActiveQuery($arClass); + return new ActiveQuery($modelClass); } - if (is_string($arClass)) { - if (method_exists($arClass, 'withFactory')) { + if (is_string($modelClass)) { + if (method_exists($modelClass, 'withFactory')) { return new ActiveQuery( - fn (): ActiveRecordInterface => $this->factory->create($arClass)->withFactory($this->factory) + fn (): ActiveRecordModelInterface => $this->factory->create($modelClass)->withFactory($this->factory) ); } - return new ActiveQuery(fn (): ActiveRecordInterface => $this->factory->create($arClass)); + return new ActiveQuery(fn (): ActiveRecordModelInterface => $this->factory->create($modelClass)); } - if ($arClass instanceof ActiveRecordInterface && method_exists($arClass, 'withFactory')) { - return new ActiveQuery($arClass->withFactory($this->factory)); + if ($modelClass instanceof ActiveRecordModelInterface && method_exists($modelClass, 'withFactory')) { + return new ActiveQuery($modelClass->withFactory($this->factory)); } - return new ActiveQuery($arClass); + return new ActiveQuery($modelClass); } } diff --git a/src/Trait/MagicPropertiesTrait.php b/src/Trait/MagicPropertiesTrait.php index e8a29c80f..c0d676697 100644 --- a/src/Trait/MagicPropertiesTrait.php +++ b/src/Trait/MagicPropertiesTrait.php @@ -6,8 +6,8 @@ use ReflectionException; use Throwable; -use Yiisoft\ActiveRecord\AbstractActiveRecord; use Yiisoft\ActiveRecord\ActiveRecordInterface; +use Yiisoft\ActiveRecord\ActiveRecordModelInterface; use Yiisoft\Db\Exception\Exception; use Yiisoft\Db\Exception\InvalidArgumentException; use Yiisoft\Db\Exception\InvalidCallException; @@ -15,30 +15,14 @@ use Yiisoft\Db\Exception\UnknownPropertyException; use function array_merge; -use function in_array; use function method_exists; use function property_exists; /** * Trait to define magic methods to access values of an ActiveRecord instance. * - * @method array getRelatedRecords() - * @see AbstractActiveRecord::getRelatedRecords() - * - * @method bool hasDependentRelations(string $propertyName) - * @see AbstractActiveRecord::hasDependentRelations() - * - * @method bool isRelationPopulated(string $name) - * @see ActiveRecordInterface::isRelationPopulated() - * - * @method void resetDependentRelations(string $propertyName) - * @see AbstractActiveRecord::resetDependentRelations() - * - * @method void resetRelation(string $name) - * @see ActiveRecordInterface::resetRelation() - * - * @method ActiveRecordInterface|array|null retrieveRelation(string $name) - * @see AbstractActiveRecord::retrieveRelation() + * @method ActiveRecordInterface activeRecord() + * @see ActiveRecordModelInterface::activeRecord() */ trait MagicPropertiesTrait { @@ -66,17 +50,19 @@ public function __get(string $name) return $this->$getter(); } - if ($this->hasProperty($name)) { - return $this->get($name); + $activeRecord = $this->activeRecord(); + + if (isset($this->propertyValues[$name]) || $activeRecord->hasProperty($name)) { + return $activeRecord->get($name); } - if ($this->isRelationPopulated($name)) { - return $this->getRelatedRecords()[$name]; + if ($activeRecord->isRelationPopulated($name)) { + return $activeRecord->getRelatedRecords()[$name]; } if (method_exists($this, "get{$name}Query")) { /** Read relation query getter, e.g., getUserQuery() */ - return $this->retrieveRelation($name); + return $activeRecord->retrieveRelation($name); } if (method_exists($this, "set$name")) { @@ -109,14 +95,14 @@ public function __isset(string $name): bool */ public function __unset(string $name): void { - if ($this->hasProperty($name)) { + $activeRecord = $this->activeRecord(); + + if (isset($this->propertyValues[$name])) { unset($this->propertyValues[$name]); - if ($this->hasDependentRelations($name)) { - $this->resetDependentRelations($name); - } - } elseif ($this->isRelationPopulated($name)) { - $this->resetRelation($name); + $activeRecord->resetDependentRelations($name); + } elseif ($activeRecord->isRelationPopulated($name)) { + $activeRecord->resetRelation($name); } } @@ -135,8 +121,10 @@ public function __set(string $name, mixed $value): void return; } - if ($this->hasProperty($name)) { - parent::set($name, $value); + $activeRecord = $this->activeRecord(); + + if ($activeRecord->hasProperty($name)) { + $activeRecord->set($name, $value); return; } @@ -150,20 +138,6 @@ public function __set(string $name, mixed $value): void throw new UnknownPropertyException('Setting unknown property: ' . static::class . '::' . $name); } - public function hasProperty(string $name): bool - { - return isset($this->propertyValues[$name]) || in_array($name, $this->propertyNames(), true); - } - - public function set(string $propertyName, mixed $value): void - { - if ($this->hasProperty($propertyName)) { - parent::set($propertyName, $value); - } else { - throw new InvalidArgumentException(static::class . ' has no property named "' . $propertyName . '".'); - } - } - /** * Returns a value indicating whether a property is defined for this component. * @@ -183,40 +157,44 @@ public function set(string $propertyName, mixed $value): void */ public function isProperty(string $name, bool $checkVars = true): bool { - return method_exists($this, "get$name") + return isset($this->propertyValues[$name]) + || ($checkVars && property_exists($this, $name)) + || method_exists($this, "get$name") || method_exists($this, "set$name") || method_exists($this, "get{$name}Query") - || ($checkVars && property_exists($this, $name)) - || $this->hasProperty($name); + || $this->activeRecord()->hasProperty($name); } public function canGetProperty(string $name, bool $checkVars = true): bool { - return method_exists($this, "get$name") - || method_exists($this, "get{$name}Query") + return isset($this->propertyValues[$name]) || ($checkVars && property_exists($this, $name)) - || $this->hasProperty($name); + || method_exists($this, "get$name") + || method_exists($this, "get{$name}Query") + || $this->activeRecord()->hasProperty($name); } public function canSetProperty(string $name, bool $checkVars = true): bool { - return method_exists($this, "set$name") + return isset($this->propertyValues[$name]) || ($checkVars && property_exists($this, $name)) - || $this->hasProperty($name); + || method_exists($this, "set$name") + || $this->activeRecord()->hasProperty($name); } - /** @psalm-return array */ - protected function propertyValuesInternal(): array + public function propertyValues(): array { - return array_merge($this->propertyValues, parent::propertyValuesInternal()); + return array_merge($this->propertyValues, parent::propertyValues()); } - protected function populateProperty(string $name, mixed $value): void + public function populateProperty(string $name, mixed $value): void { if ($name !== 'propertyValues' && property_exists($this, $name)) { $this->$name = $value; - } else { + } elseif (isset($this->propertyValues[$name]) || $this->activeRecord()->hasProperty($name)) { $this->propertyValues[$name] = $value; + } else { + throw new InvalidArgumentException(static::class . ' has no property named "' . $name . '".'); } } } diff --git a/src/Trait/MagicRelationsTrait.php b/src/Trait/MagicRelationsTrait.php index 8689b0695..79956f1ea 100644 --- a/src/Trait/MagicRelationsTrait.php +++ b/src/Trait/MagicRelationsTrait.php @@ -7,7 +7,6 @@ use ReflectionException; use ReflectionMethod; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecordInterface; use Yiisoft\Db\Exception\InvalidArgumentException; use function get_class_methods; @@ -20,8 +19,8 @@ use function ucfirst; /** - * Trait to define {@see ActiveRecordInterface::relationQuery()} method to access relation queries of an ActiveRecord - * instance. Also, it defines {@see ActiveRecordInterface::relationNames()} method to get names of all relations + * Trait to define {@see relationQuery()} method to access relation queries of an ActiveRecordModel + * instance. Also, it defines {@see relationNames()} method to get names of all relations * defined in the ActiveRecord class. */ trait MagicRelationsTrait @@ -37,7 +36,7 @@ trait MagicRelationsTrait * ```php * public function getOrdersQuery(): ActiveQueryInterface * { - * return $this->hasMany(Order::class, ['customer_id' => 'id']); + * return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id']); * } * ``` * diff --git a/tests/ActiveQueryFindTest.php b/tests/ActiveQueryFindTest.php index a8232a477..aaf59c601 100644 --- a/tests/ActiveQueryFindTest.php +++ b/tests/ActiveQueryFindTest.php @@ -80,7 +80,7 @@ public function testFindBySql(): void /** find one() */ $customers = $customerQuery->findBySql('SELECT * FROM {{customer}} ORDER BY [[id]] DESC')->one(); $this->assertInstanceOf(Customer::class, $customers); - $this->assertEquals('user3', $customers->get('name')); + $this->assertEquals('user3', $customers->activeRecord()->get('name')); /** find all() */ $customers = $customerQuery->findBySql('SELECT * FROM {{customer}}')->all(); @@ -91,7 +91,7 @@ public function testFindBySql(): void ->findBySql('SELECT * FROM {{customer}} WHERE [[id]]=:id', [':id' => 2]) ->one(); $this->assertInstanceOf(Customer::class, $customers); - $this->assertEquals('user2', $customers->get('name')); + $this->assertEquals('user2', $customers->activeRecord()->get('name')); } public function testFindLazyViaTable(): void @@ -102,7 +102,7 @@ public function testFindLazyViaTable(): void $orders = $orderQuery->findOne(2); $this->assertCount(0, $orders->getBooks()); - $this->assertEquals(2, $orders->get('id')); + $this->assertEquals(2, $orders->activeRecord()->get('id')); $orders = $orderQuery->setWhere(['id' => 1])->asArray()->one(); $this->assertIsArray($orders); @@ -118,18 +118,18 @@ public function testFindEagerViaTable(): void $order = $orders[0]; $this->assertCount(2, $order->getBooks()); - $this->assertEquals(1, $order->get('id')); - $this->assertEquals(1, $order->getBooks()[0]->get('id')); - $this->assertEquals(2, $order->getBooks()[1]->get('id')); + $this->assertEquals(1, $order->activeRecord()->get('id')); + $this->assertEquals(1, $order->getBooks()[0]->activeRecord()->get('id')); + $this->assertEquals(2, $order->getBooks()[1]->activeRecord()->get('id')); $order = $orders[1]; $this->assertCount(0, $order->getBooks()); - $this->assertEquals(2, $order->get('id')); + $this->assertEquals(2, $order->activeRecord()->get('id')); $order = $orders[2]; $this->assertCount(1, $order->getBooks()); - $this->assertEquals(3, $order->get('id')); - $this->assertEquals(2, $order->getBooks()[0]->get('id')); + $this->assertEquals(3, $order->activeRecord()->get('id')); + $this->assertEquals(2, $order->getBooks()[0]->activeRecord()->get('id')); /** https://github.com/yiisoft/yii2/issues/1402 */ $orderQuery = new ActiveQuery(Order::class); @@ -487,11 +487,11 @@ public function testFindNullValues(): void $customer = $customerQuery->findOne(2); $customer->setName(null); - $customer->save(); + $customer->activeRecord()->save(); $result = $customerQuery->setWhere(['name' => null])->all(); $this->assertCount(1, $result); - $this->assertEquals(2, reset($result)->getPrimaryKey()); + $this->assertEquals(2, reset($result)->activeRecord()->getPrimaryKey()); } public function testFindEager(): void @@ -503,32 +503,32 @@ public function testFindEager(): void ksort($customers); $this->assertCount(3, $customers); - $this->assertTrue($customers[1]->isRelationPopulated('orders')); - $this->assertTrue($customers[2]->isRelationPopulated('orders')); - $this->assertTrue($customers[3]->isRelationPopulated('orders')); + $this->assertTrue($customers[1]->activeRecord()->isRelationPopulated('orders')); + $this->assertTrue($customers[2]->activeRecord()->isRelationPopulated('orders')); + $this->assertTrue($customers[3]->activeRecord()->isRelationPopulated('orders')); $this->assertCount(1, $customers[1]->getOrders()); $this->assertCount(2, $customers[2]->getOrders()); $this->assertCount(0, $customers[3]->getOrders()); - $customers[1]->resetRelation('orders'); - $this->assertFalse($customers[1]->isRelationPopulated('orders')); + $customers[1]->activeRecord()->resetRelation('orders'); + $this->assertFalse($customers[1]->activeRecord()->isRelationPopulated('orders')); $customer = $customerQuery->where(['id' => 1])->with('orders')->one(); - $this->assertTrue($customer->isRelationPopulated('orders')); + $this->assertTrue($customer->activeRecord()->isRelationPopulated('orders')); $this->assertCount(1, $customer->getOrders()); - $this->assertCount(1, $customer->getRelatedRecords()); + $this->assertCount(1, $customer->activeRecord()->getRelatedRecords()); /** multiple with() calls */ $orderQuery = new ActiveQuery(Order::class); $orders = $orderQuery->with('customer', 'items')->all(); $this->assertCount(3, $orders); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[0]->isRelationPopulated('items')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); $orders = $orderQuery->with('customer')->with('items')->all(); $this->assertCount(3, $orders); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[0]->isRelationPopulated('items')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); } public function testFindEagerViaRelation(): void @@ -541,7 +541,7 @@ public function testFindEagerViaRelation(): void $order = $orders[0]; $this->assertEquals(1, $order->getId()); - $this->assertTrue($order->isRelationPopulated('items')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('items')); $this->assertCount(2, $order->getItems()); $this->assertEquals(1, $order->getItems()[0]->getId()); $this->assertEquals(2, $order->getItems()[1]->getId()); @@ -556,25 +556,25 @@ public function testFindNestedRelation(): void ksort($customers); $this->assertCount(3, $customers); - $this->assertTrue($customers[1]->isRelationPopulated('orders')); - $this->assertTrue($customers[2]->isRelationPopulated('orders')); - $this->assertTrue($customers[3]->isRelationPopulated('orders')); + $this->assertTrue($customers[1]->activeRecord()->isRelationPopulated('orders')); + $this->assertTrue($customers[2]->activeRecord()->isRelationPopulated('orders')); + $this->assertTrue($customers[3]->activeRecord()->isRelationPopulated('orders')); $this->assertCount(1, $customers[1]->getOrders()); $this->assertCount(2, $customers[2]->getOrders()); $this->assertCount(0, $customers[3]->getOrders()); - $this->assertTrue($customers[1]->getOrders()[0]->isRelationPopulated('items')); - $this->assertTrue($customers[2]->getOrders()[0]->isRelationPopulated('items')); - $this->assertTrue($customers[2]->getOrders()[1]->isRelationPopulated('items')); + $this->assertTrue($customers[1]->getOrders()[0]->activeRecord()->isRelationPopulated('items')); + $this->assertTrue($customers[2]->getOrders()[0]->activeRecord()->isRelationPopulated('items')); + $this->assertTrue($customers[2]->getOrders()[1]->activeRecord()->isRelationPopulated('items')); $this->assertCount(2, $customers[1]->getOrders()[0]->getItems()); $this->assertCount(3, $customers[2]->getOrders()[0]->getItems()); $this->assertCount(1, $customers[2]->getOrders()[1]->getItems()); $customers = $customerQuery->where(['id' => 1])->with('ordersWithItems')->one(); - $this->assertTrue($customers->isRelationPopulated('ordersWithItems')); + $this->assertTrue($customers->activeRecord()->isRelationPopulated('ordersWithItems')); $this->assertCount(1, $customers->getOrdersWithItems()); $order = $customers->getOrdersWithItems()[0]; - $this->assertTrue($order->isRelationPopulated('orderItems')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('orderItems')); $this->assertCount(2, $order->getOrderItems()); } @@ -593,14 +593,14 @@ public function testFindEagerViaRelationPreserveOrder(): void $order = $orders[0]; $this->assertEquals(1, $order->getId()); - $this->assertTrue($order->isRelationPopulated('itemsInOrder1')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('itemsInOrder1')); $this->assertCount(2, $order->getItemsInOrder1()); $this->assertEquals(1, $order->getItemsInOrder1()[0]->getId()); $this->assertEquals(2, $order->getItemsInOrder1()[1]->getId()); $order = $orders[1]; $this->assertEquals(2, $order->getId()); - $this->assertTrue($order->isRelationPopulated('itemsInOrder1')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('itemsInOrder1')); $this->assertCount(3, $order->getItemsInOrder1()); $this->assertEquals(5, $order->getItemsInOrder1()[0]->getId()); $this->assertEquals(3, $order->getItemsInOrder1()[1]->getId()); @@ -608,7 +608,7 @@ public function testFindEagerViaRelationPreserveOrder(): void $order = $orders[2]; $this->assertEquals(3, $order->getId()); - $this->assertTrue($order->isRelationPopulated('itemsInOrder1')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('itemsInOrder1')); $this->assertCount(1, $order->getItemsInOrder1()); $this->assertEquals(2, $order->getItemsInOrder1()[0]->getId()); } @@ -624,14 +624,14 @@ public function testFindEagerViaRelationPreserveOrderB(): void $order = $orders[0]; $this->assertEquals(1, $order->getId()); - $this->assertTrue($order->isRelationPopulated('itemsInOrder2')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('itemsInOrder2')); $this->assertCount(2, $order->getItemsInOrder2()); $this->assertEquals(1, $order->getItemsInOrder2()[0]->getId()); $this->assertEquals(2, $order->getItemsInOrder2()[1]->getId()); $order = $orders[1]; $this->assertEquals(2, $order->getId()); - $this->assertTrue($order->isRelationPopulated('itemsInOrder2')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('itemsInOrder2')); $this->assertCount(3, $order->getItemsInOrder2()); $this->assertEquals(5, $order->getItemsInOrder2()[0]->getId()); $this->assertEquals(3, $order->getItemsInOrder2()[1]->getId()); @@ -639,7 +639,7 @@ public function testFindEagerViaRelationPreserveOrderB(): void $order = $orders[2]; $this->assertEquals(3, $order->getId()); - $this->assertTrue($order->isRelationPopulated('itemsInOrder2')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('itemsInOrder2')); $this->assertCount(1, $order->getItemsInOrder2()); $this->assertEquals(2, $order->getItemsInOrder2()[0]->getId()); } @@ -668,7 +668,7 @@ public function testFindEagerIndexBy(): void $orderQuery = new ActiveQuery(Order::class); $order = $orderQuery->with('itemsIndexed')->where(['id' => 1])->one(); - $this->assertTrue($order->isRelationPopulated('itemsIndexed')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('itemsIndexed')); $items = $order->getItemsIndexed(); $this->assertCount(2, $items); @@ -676,7 +676,7 @@ public function testFindEagerIndexBy(): void $this->assertTrue(isset($items[2])); $order = $orderQuery->with('itemsIndexed')->setWhere(['id' => 2])->one(); - $this->assertTrue($order->isRelationPopulated('itemsIndexed')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('itemsIndexed')); $items = $order->getItemsIndexed(); $this->assertCount(3, $items); @@ -691,22 +691,22 @@ public function testFindLazy(): void $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(2); - $this->assertFalse($customer->isRelationPopulated('orders')); + $this->assertFalse($customer->activeRecord()->isRelationPopulated('orders')); $orders = $customer->getOrders(); - $this->assertTrue($customer->isRelationPopulated('orders')); + $this->assertTrue($customer->activeRecord()->isRelationPopulated('orders')); $this->assertCount(2, $orders); - $this->assertCount(1, $customer->getRelatedRecords()); + $this->assertCount(1, $customer->activeRecord()->getRelatedRecords()); - $customer->resetRelation('orders'); - $this->assertFalse($customer->isRelationPopulated('orders')); + $customer->activeRecord()->resetRelation('orders'); + $this->assertFalse($customer->activeRecord()->isRelationPopulated('orders')); $customer = $customerQuery->findOne(2); - $this->assertFalse($customer->isRelationPopulated('orders')); + $this->assertFalse($customer->activeRecord()->isRelationPopulated('orders')); $orders = $customer->getOrdersQuery()->where(['id' => 3])->all(); - $this->assertFalse($customer->isRelationPopulated('orders')); - $this->assertCount(0, $customer->getRelatedRecords()); + $this->assertFalse($customer->activeRecord()->isRelationPopulated('orders')); + $this->assertCount(0, $customer->activeRecord()->getRelatedRecords()); $this->assertCount(1, $orders); $this->assertEquals(3, $orders[0]->getId()); } diff --git a/tests/ActiveQueryTest.php b/tests/ActiveQueryTest.php index b159cbee6..02de673fe 100644 --- a/tests/ActiveQueryTest.php +++ b/tests/ActiveQueryTest.php @@ -43,7 +43,7 @@ public function testOptions(): void $customerQuery = new ActiveQuery(Customer::class); $query = $customerQuery->on(['a' => 'b'])->joinWith('profile'); - $this->assertEquals(Customer::class, $query->getARClass()); + $this->assertEquals(Customer::class, $query->getModelClass()); $this->assertEquals(['a' => 'b'], $query->getOn()); $this->assertEquals([[['profile'], true, 'LEFT JOIN']], $query->getJoinWith()); $customerQuery->resetJoinWith(); @@ -382,7 +382,7 @@ public function testCustomColumns(): void ->where(['name' => 'user3'])->one(); } - $this->assertEquals(3, $customers->get('id')); + $this->assertEquals(3, $customers->activeRecord()->get('id')); $this->assertEquals(4, $customers->status2); } @@ -429,8 +429,8 @@ public function testDeeplyNestedTableRelation(): void $items = $customers->getOrderItems(); $this->assertCount(2, $items); - $this->assertEquals(1, $items[0]->get('id')); - $this->assertEquals(2, $items[1]->get('id')); + $this->assertEquals(1, $items[0]->activeRecord()->get('id')); + $this->assertEquals(2, $items[1]->activeRecord()->get('id')); $this->assertInstanceOf(Item::class, $items[0]); $this->assertInstanceOf(Item::class, $items[1]); } @@ -455,7 +455,7 @@ public function testDeeplyNestedTableRelation2(): void $this->assertInstanceOf(Order::class, $orders[0]); $this->assertInstanceOf(Order::class, $orders[1]); - $ids = [$orders[0]->getId(), $orders[1]->get('id')]; + $ids = [$orders[0]->getId(), $orders[1]->activeRecord()->get('id')]; sort($ids); $this->assertEquals([1, 3], $ids); @@ -464,7 +464,7 @@ public function testDeeplyNestedTableRelation2(): void $orders = $categories->getOrders(); $this->assertCount(1, $orders); - $this->assertEquals(2, $orders[0]->get('id')); + $this->assertEquals(2, $orders[0]->activeRecord()->get('id')); $this->assertInstanceOf(Order::class, $orders[0]); } @@ -479,9 +479,9 @@ public function testJoinWith(): void $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); $this->assertEquals(1, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); - $this->assertTrue($orders[2]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('customer')); /** inner join filtering and eager loading */ $orderQuery = new ActiveQuery(Order::class); @@ -495,8 +495,8 @@ public function testJoinWith(): void $this->assertCount(2, $orders); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); /** inner join filtering, eager loading, conditions on both primary and relation */ $orderQuery = new ActiveQuery(Order::class); @@ -509,7 +509,7 @@ public function testJoinWith(): void )->where(['order.id' => [1, 2]])->orderBy('order.id')->all(); $this->assertCount(1, $orders); $this->assertEquals(2, $orders[0]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); /** inner join filtering without eager loading */ $orderQuery = new ActiveQuery(Order::class); @@ -524,8 +524,8 @@ public function testJoinWith(): void $this->assertCount(2, $orders); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertFalse($orders[0]->isRelationPopulated('customer')); - $this->assertFalse($orders[1]->isRelationPopulated('customer')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertFalse($orders[1]->activeRecord()->isRelationPopulated('customer')); /** inner join filtering without eager loading, conditions on both primary and relation */ $orderQuery = new ActiveQuery(Order::class); @@ -539,7 +539,7 @@ public function testJoinWith(): void )->where(['order.id' => [1, 2]])->orderBy('order.id')->all(); $this->assertCount(1, $orders); $this->assertEquals(2, $orders[0]->getId()); - $this->assertFalse($orders[0]->isRelationPopulated('customer')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('customer')); /** join with via-relation */ $orderQuery = new ActiveQuery(Order::class); @@ -549,8 +549,8 @@ public function testJoinWith(): void $this->assertCount(1, $orders[1]->getBooks()); $this->assertEquals(1, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('books')); - $this->assertTrue($orders[1]->isRelationPopulated('books')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('books')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('books')); /** join with sub-relation */ $orderQuery = new ActiveQuery(Order::class); @@ -568,8 +568,8 @@ public function testJoinWith(): void $this->assertCount(3, $orders[0]->getItems()); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('items')); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); /** join with table alias */ $orderQuery = new ActiveQuery(Order::class); @@ -584,9 +584,9 @@ public function testJoinWith(): void $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); $this->assertEquals(1, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); - $this->assertTrue($orders[2]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('customer')); /** join with table alias */ $orderQuery = new ActiveQuery(Order::class); @@ -595,9 +595,9 @@ public function testJoinWith(): void $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); $this->assertEquals(1, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); - $this->assertTrue($orders[2]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('customer')); /** join with table alias sub-relation */ $orderQuery = new ActiveQuery(Order::class); @@ -615,8 +615,8 @@ public function testJoinWith(): void $this->assertCount(3, $orders[0]->getItems()); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('items')); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); /** join with ON condition */ $orderQuery = new ActiveQuery(Order::class); @@ -628,9 +628,9 @@ public function testJoinWith(): void $this->assertEquals(1, $orders[0]->getId()); $this->assertEquals(2, $orders[1]->getId()); $this->assertEquals(3, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('books2')); - $this->assertTrue($orders[1]->isRelationPopulated('books2')); - $this->assertTrue($orders[2]->isRelationPopulated('books2')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('books2')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('books2')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('books2')); /** lazy loading with ON condition */ $orderQuery = new ActiveQuery(Order::class); @@ -655,9 +655,9 @@ public function testJoinWith(): void $this->assertEquals(1, $orders[0]->getId()); $this->assertEquals(2, $orders[1]->getId()); $this->assertEquals(3, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('books2')); - $this->assertTrue($orders[1]->isRelationPopulated('books2')); - $this->assertTrue($orders[2]->isRelationPopulated('books2')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('books2')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('books2')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('books2')); /** join with count and query */ $orderQuery = new ActiveQuery(Order::class); @@ -707,8 +707,8 @@ public function testJoinWith(): void $this->assertCount(3, $orders[0]->getItems()); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('items')); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); } /** @@ -723,7 +723,7 @@ public function testJoinWithAndScope(): void $customers = $customer->active()->innerJoinWith('profile')->orderBy('customer.id')->all(); $this->assertCount(1, $customers); $this->assertEquals(1, $customers[0]->getId()); - $this->assertTrue($customers[0]->isRelationPopulated('profile')); + $this->assertTrue($customers[0]->activeRecord()->isRelationPopulated('profile')); /** hasOne outer join */ $customer = new CustomerQuery(Customer::class); @@ -733,8 +733,8 @@ public function testJoinWithAndScope(): void $this->assertEquals(2, $customers[1]->getId()); $this->assertInstanceOf(Profile::class, $customers[0]->getProfile()); $this->assertNull($customers[1]->getProfile()); - $this->assertTrue($customers[0]->isRelationPopulated('profile')); - $this->assertTrue($customers[1]->isRelationPopulated('profile')); + $this->assertTrue($customers[0]->activeRecord()->isRelationPopulated('profile')); + $this->assertTrue($customers[1]->activeRecord()->isRelationPopulated('profile')); /** hasMany */ $customer = new CustomerQuery(Customer::class); @@ -748,8 +748,8 @@ public function testJoinWithAndScope(): void $this->assertCount(2, $customers); $this->assertEquals(2, $customers[0]->getId()); $this->assertEquals(1, $customers[1]->getId()); - $this->assertTrue($customers[0]->isRelationPopulated('orders')); - $this->assertTrue($customers[1]->isRelationPopulated('orders')); + $this->assertTrue($customers[0]->activeRecord()->isRelationPopulated('orders')); + $this->assertTrue($customers[1]->activeRecord()->isRelationPopulated('orders')); } /** @@ -818,9 +818,9 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); $this->assertEquals(1, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); - $this->assertTrue($orders[2]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('customer')); /** inner join filtering and eager loading */ $orderQuery = new ActiveQuery(Order::class); @@ -839,8 +839,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(2, $orders); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); /** inner join filtering without eager loading */ $orderQuery = new ActiveQuery(Order::class); @@ -859,8 +859,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(2, $orders); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertFalse($orders[0]->isRelationPopulated('customer')); - $this->assertFalse($orders[1]->isRelationPopulated('customer')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertFalse($orders[1]->activeRecord()->isRelationPopulated('customer')); /** join with via-relation */ $orderQuery = new ActiveQuery(Order::class); @@ -885,8 +885,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(1, $orders[1]->getBooks()); $this->assertEquals(1, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('books')); - $this->assertTrue($orders[1]->isRelationPopulated('books')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('books')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('books')); /** joining sub relations */ $orderQuery = new ActiveQuery(Order::class); @@ -927,8 +927,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(3, $orders[0]->getItems()); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('items')); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); /** join with ON condition */ if ($aliasMethod === 'explicit' || $aliasMethod === 'querysyntax') { @@ -938,15 +938,15 @@ public function testJoinWithAlias(string $aliasMethod): void $orders = $orderQuery->joinWith(["$relationName b"])->orderBy('order.id')->all(); $this->assertCount(3, $orders); - $this->assertCount(2, $orders[0]->relation($relationName)); - $this->assertCount(0, $orders[1]->relation($relationName)); - $this->assertCount(1, $orders[2]->relation($relationName)); + $this->assertCount(2, $orders[0]->activeRecord()->relation($relationName)); + $this->assertCount(0, $orders[1]->activeRecord()->relation($relationName)); + $this->assertCount(1, $orders[2]->activeRecord()->relation($relationName)); $this->assertEquals(1, $orders[0]->getId()); $this->assertEquals(2, $orders[1]->getId()); $this->assertEquals(3, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated($relationName)); - $this->assertTrue($orders[1]->isRelationPopulated($relationName)); - $this->assertTrue($orders[2]->isRelationPopulated($relationName)); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated($relationName)); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated($relationName)); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated($relationName)); } /** join with ON condition and alias in relation definition */ @@ -957,15 +957,15 @@ public function testJoinWithAlias(string $aliasMethod): void $orders = $orderQuery->joinWith([$relationName])->orderBy('order.id')->all(); $this->assertCount(3, $orders); - $this->assertCount(2, $orders[0]->relation($relationName)); - $this->assertCount(0, $orders[1]->relation($relationName)); - $this->assertCount(1, $orders[2]->relation($relationName)); + $this->assertCount(2, $orders[0]->activeRecord()->relation($relationName)); + $this->assertCount(0, $orders[1]->activeRecord()->relation($relationName)); + $this->assertCount(1, $orders[2]->activeRecord()->relation($relationName)); $this->assertEquals(1, $orders[0]->getId()); $this->assertEquals(2, $orders[1]->getId()); $this->assertEquals(3, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated($relationName)); - $this->assertTrue($orders[1]->isRelationPopulated($relationName)); - $this->assertTrue($orders[2]->isRelationPopulated($relationName)); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated($relationName)); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated($relationName)); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated($relationName)); } /** join with count and query */ @@ -1026,8 +1026,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(3, $orders[0]->getItems()); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('items')); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); } /** @@ -1050,8 +1050,8 @@ public function testJoinWithSameTable(): void $query->createCommand()->getRawSql() . print_r($orders, true) ); $this->assertEquals(2, $orders[0]->getId()); - $this->assertFalse($orders[0]->isRelationPopulated('bookItems')); - $this->assertFalse($orders[0]->isRelationPopulated('movieItems')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('bookItems')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('movieItems')); /** with eager loading */ $query = new ActiveQuery(Order::class); @@ -1065,8 +1065,8 @@ public function testJoinWithSameTable(): void $this->assertCount(0, $orders[0]->getBookItems()); $this->assertCount(3, $orders[0]->getMovieItems()); $this->assertEquals(2, $orders[0]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('bookItems')); - $this->assertTrue($orders[0]->isRelationPopulated('movieItems')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('bookItems')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('movieItems')); /** * join with the same table but different aliases alias is defined in the call to joinWith() without eager @@ -1096,7 +1096,7 @@ public function testJoinWithSameTable(): void $query->createCommand()->getRawSql() . print_r($orders, true) ); $this->assertEquals(2, $orders[0]->getId()); - $this->assertFalse($orders[0]->isRelationPopulated('itemsIndexed')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('itemsIndexed')); /** with eager loading, only for one relation as it would be overwritten otherwise. */ $query = new ActiveQuery(Order::class); @@ -1121,7 +1121,7 @@ public function testJoinWithSameTable(): void $this->assertCount(1, $orders, $query->createCommand()->getRawSql() . print_r($orders, true)); $this->assertCount(3, $orders[0]->getItemsIndexed()); $this->assertEquals(2, $orders[0]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('itemsIndexed')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('itemsIndexed')); /** with eager loading, and the other relation */ $query = new ActiveQuery(Order::class); @@ -1147,7 +1147,7 @@ public function testJoinWithSameTable(): void $this->assertCount(1, $orders, $query->createCommand()->getRawSql() . print_r($orders, true)); $this->assertCount(0, $orders[0]->getItemsIndexed()); $this->assertEquals(2, $orders[0]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('itemsIndexed')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('itemsIndexed')); } /** @@ -1170,9 +1170,9 @@ public function testJoinWithDuplicateSimple(): void $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); $this->assertEquals(1, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); - $this->assertTrue($orders[2]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('customer')); } /** @@ -1196,8 +1196,8 @@ public function testJoinWithDuplicateCallbackFiltering(): void $this->assertCount(2, $orders); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); } /** @@ -1220,7 +1220,7 @@ public function testJoinWithDuplicateCallbackFilteringConditionsOnPrimary(): voi $this->assertCount(1, $orders); $this->assertEquals(2, $orders[0]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); } /** @@ -1242,10 +1242,10 @@ public function testJoinWithDuplicateWithSubRelation(): void ])->orderBy('order.id')->all(); $this->assertCount(1, $orders); - $this->assertTrue($orders[0]->isRelationPopulated('items')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); $this->assertEquals(2, $orders[0]->getId()); $this->assertCount(3, $orders[0]->getItems()); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); } @@ -1271,9 +1271,9 @@ public function testJoinWithDuplicateTableAlias1(): void $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); $this->assertEquals(1, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); - $this->assertTrue($orders[2]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('customer')); } /** @@ -1296,9 +1296,9 @@ public function testJoinWithDuplicateTableAlias2(): void $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); $this->assertEquals(1, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); - $this->assertTrue($orders[2]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('customer')); } /** @@ -1324,10 +1324,10 @@ public function testJoinWithDuplicateTableAliasSubRelation(): void ])->orderBy('order.id')->all(); $this->assertCount(1, $orders); - $this->assertTrue($orders[0]->isRelationPopulated('items')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); $this->assertEquals(2, $orders[0]->getId()); $this->assertCount(3, $orders[0]->getItems()); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); } @@ -1357,10 +1357,10 @@ public function testJoinWithDuplicateSubRelationCalledInsideClosure(): void ->all(); $this->assertCount(1, $orders); - $this->assertTrue($orders[0]->isRelationPopulated('items')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); $this->assertEquals(2, $orders[0]->getId()); $this->assertCount(3, $orders[0]->getItems()); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); } @@ -1412,11 +1412,11 @@ public function testInverseOf(): void $this->assertSame($orders[0]->getCustomer2(), $customer); $this->assertSame($orders[1]->getCustomer2(), $customer); $this->assertTrue( - $orders[0]->isRelationPopulated('customer2'), + $orders[0]->activeRecord()->isRelationPopulated('customer2'), 'inverse relation did not populate the relation' ); $this->assertTrue( - $orders[1]->isRelationPopulated('customer2'), + $orders[1]->activeRecord()->isRelationPopulated('customer2'), 'inverse relation did not populate the relation' ); @@ -1479,7 +1479,7 @@ public function testUnlinkAllViaTable(): void $itemQuery = new ActiveQuery(Item::class); $this->assertEquals(5, $itemQuery->count()); - $order->unlinkAll('booksViaTable', true); + $order->activeRecord()->unlinkAll('booksViaTable', true); $this->assertEquals(5, $itemQuery->count()); $this->assertEquals($orderItemCount - 2, $orderItemQuery->count()); $this->assertCount(0, $order->getBooksViaTable()); @@ -1491,7 +1491,7 @@ public function testUnlinkAllViaTable(): void $orderItemCount = $orderItemsWithNullFKQuery->count(); $this->assertEquals(5, $itemQuery->count()); - $order->unlinkAll('booksWithNullFKViaTable', false); + $order->activeRecord()->unlinkAll('booksWithNullFKViaTable', false); $this->assertCount(0, $order->getBooksWithNullFKViaTable()); $this->assertEquals(2, $orderItemsWithNullFKQuery->where( ['AND', ['item_id' => [1, 2]], ['order_id' => null]] @@ -1540,9 +1540,9 @@ public function testIssues(): void $arClass->setName('test'); $arClass->setEmail('test'); - $arClass->save(); + $arClass->activeRecord()->save(); - $arClass->updateCounters(['status' => 1]); + $arClass->activeRecord()->updateCounters(['status' => 1]); $this->assertEquals(1, $arClass->getStatus()); } @@ -1680,7 +1680,7 @@ public function testLinkWhenRelationIsIndexed2(): void $orderItem->setQuantity(1); $orderItem->setSubtotal(10.0); - $order->link('orderItems2', $orderItem); + $order->activeRecord()->link('orderItems2', $orderItem); $this->assertTrue(isset($order->getOrderItems2()['3'])); } @@ -1725,7 +1725,7 @@ public function testUnlinkAllOnCondition(): void $this->assertCount(1, $category->getLimitedItems()); /** Unlink all items in the limitedItems relation */ - $category->unlinkAll('limitedItems', true); + $category->activeRecord()->unlinkAll('limitedItems', true); /** Make sure that only one item was unlinked */ $itemsCount = $itemQuery->setWhere(['category_id' => 2])->count(); @@ -1757,7 +1757,7 @@ public function testUnlinkAllOnConditionViaTable(): void $this->assertCount(2, $category->getLimitedItems()); /** Unlink all items in the limitedItems relation */ - $category->unlinkAll('limitedItems', true); + $category->activeRecord()->unlinkAll('limitedItems', true); /** Call $orderQuery again to ensure that links are removed */ $this->assertCount(0, $orderQuery->one()->getLimitedItems()); @@ -1775,7 +1775,7 @@ public function testIndexByAfterLoadingRelations(): void $orderQuery = new ActiveQuery(Order::class); $orderQuery->with('customer')->indexBy(function (Order $order) { - $this->assertTrue($order->isRelationPopulated('customer')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('customer')); $this->assertNotEmpty($order->getCustomer()?->getId()); return $order->getCustomer()?->getId(); @@ -1815,7 +1815,7 @@ public function testFilterTableNamesFromAliases(array|string $fromParams, array $query = $customerQuery->from($fromParams); - $aliases = Assert::invokeMethod(new Customer(), 'filterValidAliases', [$query]); + $aliases = Assert::invokeMethod((new Customer())->activeRecord(), 'filterValidAliases', [$query]); $this->assertEquals($expectedAliases, $aliases); } @@ -1827,9 +1827,9 @@ public function testExtraFields(): void $customerQuery = new ActiveQuery(Customer::class); $query = $customerQuery->with('orders2')->where(['id' => 1])->one(); - $this->assertCount(1, $query->getRelatedRecords()); + $this->assertCount(1, $query->activeRecord()->getRelatedRecords()); $this->assertCount(1, $query->extraFields()); - $this->assertArrayHasKey('orders2', $query->getRelatedRecords()); + $this->assertArrayHasKey('orders2', $query->activeRecord()->getRelatedRecords()); $this->assertContains('orders2', $query->extraFields()); } @@ -1861,14 +1861,14 @@ public function testRelationWhereParams(string $orderTableName, string $orderIte $order = new Order(); $orderItem = new OrderItem(); - $this->assertSame('order', $order->getTableName()); - $this->assertSame('order_item', $orderItem->getTableName()); + $this->assertSame('order', $order->tableName()); + $this->assertSame('order_item', $orderItem->tableName()); $order = $order->withTableName($orderTableName); $orderItem = $orderItem->withTableName($orderItemTableName); - $this->assertSame($orderTableName, $order->getTableName()); - $this->assertSame($orderItemTableName, $orderItem->getTableName()); + $this->assertSame($orderTableName, $order->tableName()); + $this->assertSame($orderItemTableName, $orderItem->tableName()); $orderQuery = new ActiveQuery(Order::class); $order = $orderQuery->findOne(1); @@ -1908,8 +1908,8 @@ public function testOutdatedRelationsAreResetForExistingRecords(): void $this->assertEquals(1, $orderItems->getItem()->getId()); /** Test `set()`. */ - $orderItems->set('order_id', 3); - $orderItems->set('item_id', 1); + $orderItems->activeRecord()->set('order_id', 3); + $orderItems->activeRecord()->set('item_id', 1); $this->assertEquals(3, $orderItems->getOrder()->getId()); $this->assertEquals(1, $orderItems->getItem()->getId()); } @@ -2012,7 +2012,7 @@ public function testOptimisticLock(): void $record = $documentQuery->findOne(1); $record->content = 'New Content'; - $record->save(); + $record->activeRecord()->save(); $this->assertEquals(1, $record->version); $record = $documentQuery->findOne(1); @@ -2020,7 +2020,7 @@ public function testOptimisticLock(): void $record->content = 'Rewrite attempt content'; $record->version = 0; $this->expectException(OptimisticLockException::class); - $record->save(); + $record->activeRecord()->save(); } public function testOptimisticLockOnDelete(): void @@ -2035,7 +2035,7 @@ public function testOptimisticLockOnDelete(): void $document->version = 1; $this->expectException(OptimisticLockException::class); - $document->delete(); + $document->activeRecord()->delete(); } public function testOptimisticLockAfterDelete(): void @@ -2046,11 +2046,11 @@ public function testOptimisticLockAfterDelete(): void $document = $documentQuery->findOne(1); $this->assertSame(0, $document->version); - $this->assertSame(1, $document->delete()); - $this->assertTrue($document->getIsNewRecord()); + $this->assertSame(1, $document->activeRecord()->delete()); + $this->assertTrue($document->activeRecord()->isNewRecord()); $this->expectException(OptimisticLockException::class); - $document->delete(); + $document->activeRecord()->delete(); } /** @link https://github.com/yiisoft/yii2/issues/9006 */ @@ -2074,7 +2074,7 @@ public function testUpdateProperties(): void $orderQuery = new ActiveQuery(Order::class); $order = $orderQuery->findOne(1); $newTotal = 978; - $this->assertSame(1, $order->updateProperties(['total' => $newTotal])); + $this->assertSame(1, $order->activeRecord()->updateProperties(['total' => $newTotal])); $this->assertEquals($newTotal, $order->getTotal()); $order = $orderQuery->findOne(1); @@ -2082,11 +2082,11 @@ public function testUpdateProperties(): void /** @see https://github.com/yiisoft/yii2/issues/12143 */ $newOrder = new Order(); - $this->assertTrue($newOrder->getIsNewRecord()); + $this->assertTrue($newOrder->activeRecord()->isNewRecord()); $newTotal = 200; - $this->assertSame(0, $newOrder->updateProperties(['total' => $newTotal])); - $this->assertTrue($newOrder->getIsNewRecord()); + $this->assertSame(0, $newOrder->activeRecord()->updateProperties(['total' => $newTotal])); + $this->assertTrue($newOrder->activeRecord()->isNewRecord()); $this->assertEquals($newTotal, $newOrder->getTotal()); } @@ -2105,7 +2105,7 @@ public function testAmbiguousColumnFindOne(): void $arClass = $customerQuery->findOne(1); - $this->assertTrue($arClass->refresh()); + $this->assertTrue($arClass->activeRecord()->refresh()); $customerQuery->joinWithProfile = false; } @@ -2137,7 +2137,7 @@ public function testPropertyValues(): void $customer = new ActiveQuery(Customer::class); - $values = $customer->findOne(1)->propertyValues(); + $values = $customer->findOne(1)->activeRecord()->propertyValues(); $this->assertEquals($expectedValues, $values); } @@ -2148,7 +2148,7 @@ public function testPropertyValuesOnly(): void $customer = new ActiveQuery(Customer::class); - $values = $customer->findOne(1)->propertyValues(['id', 'email', 'name']); + $values = $customer->findOne(1)->activeRecord()->propertyValues(['id', 'email', 'name']); $this->assertEquals(['id' => 1, 'email' => 'user1@example.com', 'name' => 'user1'], $values); } @@ -2159,7 +2159,7 @@ public function testPropertyValuesExcept(): void $customer = new ActiveQuery(Customer::class); - $values = $customer->findOne(1)->propertyValues(null, ['status', 'bool_status', 'profile_id']); + $values = $customer->findOne(1)->activeRecord()->propertyValues(null, ['status', 'bool_status', 'profile_id']); $this->assertEquals( ['id' => 1, 'email' => 'user1@example.com', 'name' => 'user1', 'address' => 'address1'], @@ -2174,13 +2174,13 @@ public function testGetOldValue(): void $customer = new ActiveQuery(Customer::class); $query = $customer->findOne(1); - $this->assertEquals('user1', $query->oldValue('name')); - $this->assertEquals($query->propertyValues(), $query->oldValues()); + $this->assertEquals('user1', $query->activeRecord()->oldValue('name')); + $this->assertEquals($query->activeRecord()->propertyValues(), $query->activeRecord()->oldValues()); - $query->set('name', 'samdark'); - $this->assertEquals('samdark', $query->get('name')); - $this->assertEquals('user1', $query->oldValue('name')); - $this->assertNotEquals($query->get('name'), $query->oldValue('name')); + $query->activeRecord()->set('name', 'samdark'); + $this->assertEquals('samdark', $query->activeRecord()->get('name')); + $this->assertEquals('user1', $query->activeRecord()->oldValue('name')); + $this->assertNotEquals($query->activeRecord()->get('name'), $query->activeRecord()->oldValue('name')); } public function testGetOldValues(): void @@ -2200,17 +2200,17 @@ public function testGetOldValues(): void $customer = new ActiveQuery(Customer::class); $query = $customer->findOne(1); - $this->assertEquals($expectedValues, $query->propertyValues()); - $this->assertEquals($query->propertyValues(), $query->oldValues()); + $this->assertEquals($expectedValues, $query->activeRecord()->propertyValues()); + $this->assertEquals($query->activeRecord()->propertyValues(), $query->activeRecord()->oldValues()); - $query->set('name', 'samdark'); + $query->activeRecord()->set('name', 'samdark'); $expectedNewValues = $expectedValues; $expectedNewValues['name'] = 'samdark'; - $this->assertEquals($expectedNewValues, $query->propertyValues()); - $this->assertEquals($expectedValues, $query->oldValues()); - $this->assertNotEquals($query->propertyValues(), $query->oldValues()); + $this->assertEquals($expectedNewValues, $query->activeRecord()->propertyValues()); + $this->assertEquals($expectedValues, $query->activeRecord()->oldValues()); + $this->assertNotEquals($query->activeRecord()->propertyValues(), $query->activeRecord()->oldValues()); } public function testIsPropertyChanged(): void @@ -2220,18 +2220,18 @@ public function testIsPropertyChanged(): void $query = new ActiveQuery(Customer::class); $customer = $query->findOne(1); - $this->assertTrue($customer->get('bool_status')); - $this->assertTrue($customer->oldValue('bool_status')); + $this->assertTrue($customer->activeRecord()->get('bool_status')); + $this->assertTrue($customer->activeRecord()->oldValue('bool_status')); - $customer->set('bool_status', 1); + $customer->activeRecord()->set('bool_status', 1); - $this->assertTrue($customer->isPropertyChanged('bool_status')); - $this->assertFalse($customer->isPropertyChangedNonStrict('bool_status')); + $this->assertTrue($customer->activeRecord()->isPropertyChanged('bool_status')); + $this->assertFalse($customer->activeRecord()->isPropertyChangedNonStrict('bool_status')); - $customer->set('bool_status', 0); + $customer->activeRecord()->set('bool_status', 0); - $this->assertTrue($customer->isPropertyChanged('bool_status')); - $this->assertTrue($customer->isPropertyChangedNonStrict('bool_status')); + $this->assertTrue($customer->activeRecord()->isPropertyChanged('bool_status')); + $this->assertTrue($customer->activeRecord()->isPropertyChangedNonStrict('bool_status')); } public function testOldPropertyAfterInsertAndUpdate(): void @@ -2240,21 +2240,21 @@ public function testOldPropertyAfterInsertAndUpdate(): void $customer = new Customer(); - $customer->populateProperties([ + $customer->activeRecord()->populateProperties([ 'email' => 'info@example.com', 'name' => 'Jack', 'address' => '123 Ocean Dr', 'status' => 1, ]); - $this->assertNull($customer->oldValue('name')); - $this->assertTrue($customer->save()); - $this->assertSame('Jack', $customer->oldValue('name')); + $this->assertNull($customer->activeRecord()->oldValue('name')); + $this->assertTrue($customer->activeRecord()->save()); + $this->assertSame('Jack', $customer->activeRecord()->oldValue('name')); - $customer->set('name', 'Harry'); + $customer->activeRecord()->set('name', 'Harry'); - $this->assertTrue($customer->save()); - $this->assertSame('Harry', $customer->oldValue('name')); + $this->assertTrue($customer->activeRecord()->save()); + $this->assertSame('Harry', $customer->activeRecord()->oldValue('name')); } public function testCheckRelationUnknownPropertyException(): void @@ -2364,7 +2364,7 @@ public function testUnlink(): void $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(2); $this->assertCount(2, $customer->getOrdersWithNullFK()); - $customer->unlink('ordersWithNullFK', $customer->getOrdersWithNullFK()[1], false); + $customer->activeRecord()->unlink('ordersWithNullFK', $customer->getOrdersWithNullFK()[1], false); $this->assertCount(1, $customer->getOrdersWithNullFK()); $orderWithNullFKQuery = new ActiveQuery(OrderWithNullFK::class); @@ -2377,7 +2377,7 @@ public function testUnlink(): void $customer = $customerQuery->findOne(2); $this->assertCount(2, $customer->getOrders()); - $customer->unlink('orders', $customer->getOrders()[1], true); + $customer->activeRecord()->unlink('orders', $customer->getOrders()[1], true); $this->assertCount(1, $customer->getOrders()); $orderQuery = new ActiveQuery(Order::class); @@ -2388,13 +2388,13 @@ public function testUnlink(): void $order = $orderQuery->findOne(2); $this->assertCount(3, $order->getItems()); $this->assertCount(3, $order->getOrderItems()); - $order->unlink('items', $order->getItems()[2], true); + $order->activeRecord()->unlink('items', $order->getItems()[2], true); $this->assertCount(2, $order->getItems()); $this->assertCount(2, $order->getOrderItems()); /** via model without delete */ $this->assertCount(2, $order->getItemsWithNullFK()); - $order->unlink('itemsWithNullFK', $order->getItemsWithNullFK()[1], false); + $order->activeRecord()->unlink('itemsWithNullFK', $order->getItemsWithNullFK()[1], false); $this->assertCount(1, $order->getItemsWithNullFK()); $this->assertCount(2, $order->getOrderItems()); @@ -2406,7 +2406,7 @@ public function testUnlinkAllAndConditionSetNull(): void /** in this test all orders are owned by customer 1 */ $orderWithNullFKInstance = new OrderWithNullFK(); - $orderWithNullFKInstance->updateAll(['customer_id' => 1]); + $orderWithNullFKInstance->activeRecord()->updateAll(['customer_id' => 1]); $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); @@ -2416,7 +2416,7 @@ public function testUnlinkAllAndConditionSetNull(): void $orderWithNullFKQuery = new ActiveQuery(OrderWithNullFK::class); $this->assertEquals(3, $orderWithNullFKQuery->count()); - $customer->unlinkAll('expensiveOrdersWithNullFK'); + $customer->activeRecord()->unlinkAll('expensiveOrdersWithNullFK'); $this->assertCount(3, $customer->getOrdersWithNullFK()); $this->assertCount(0, $customer->getExpensiveOrdersWithNullFK()); $this->assertEquals(3, $orderWithNullFKQuery->count()); @@ -2432,7 +2432,7 @@ public function testUnlinkAllAndConditionDelete(): void /** in this test all orders are owned by customer 1 */ $orderInstance = new Order(); - $orderInstance->updateAll(['customer_id' => 1]); + $orderInstance->activeRecord()->updateAll(['customer_id' => 1]); $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); @@ -2442,7 +2442,7 @@ public function testUnlinkAllAndConditionDelete(): void $orderQuery = new ActiveQuery(Order::class); $this->assertEquals(3, $orderQuery->count()); - $customer->unlinkAll('expensiveOrders', true); + $customer->activeRecord()->unlinkAll('expensiveOrders', true); $this->assertCount(3, $customer->getOrders()); $this->assertCount(0, $customer->getExpensiveOrders()); $this->assertEquals(2, $orderQuery->count()); @@ -2459,40 +2459,40 @@ public function testUpdate(): void $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(2); $this->assertInstanceOf(Customer::class, $customer); - $this->assertEquals('user2', $customer->get('name')); - $this->assertFalse($customer->getIsNewRecord()); - $this->assertEmpty($customer->newValues()); + $this->assertEquals('user2', $customer->activeRecord()->get('name')); + $this->assertFalse($customer->activeRecord()->isNewRecord()); + $this->assertEmpty($customer->activeRecord()->newValues()); - $customer->set('name', 'user2x'); - $customer->save(); - $this->assertEquals('user2x', $customer->get('name')); - $this->assertFalse($customer->getIsNewRecord()); + $customer->activeRecord()->set('name', 'user2x'); + $customer->activeRecord()->save(); + $this->assertEquals('user2x', $customer->activeRecord()->get('name')); + $this->assertFalse($customer->activeRecord()->isNewRecord()); $customer2 = $customerQuery->findOne(2); - $this->assertEquals('user2x', $customer2->get('name')); + $this->assertEquals('user2x', $customer2->activeRecord()->get('name')); /** no update */ $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); - $customer->set('name', 'user1'); - $this->assertEquals(0, $customer->update()); + $customer->activeRecord()->set('name', 'user1'); + $this->assertEquals(0, $customer->activeRecord()->update()); /** updateAll */ $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(3); - $this->assertEquals('user3', $customer->get('name')); + $this->assertEquals('user3', $customer->activeRecord()->get('name')); - $ret = $customer->updateAll(['name' => 'temp'], ['id' => 3]); + $ret = $customer->activeRecord()->updateAll(['name' => 'temp'], ['id' => 3]); $this->assertEquals(1, $ret); $customer = $customerQuery->findOne(3); - $this->assertEquals('temp', $customer->get('name')); + $this->assertEquals('temp', $customer->activeRecord()->get('name')); - $ret = $customer->updateAll(['name' => 'tempX']); + $ret = $customer->activeRecord()->updateAll(['name' => 'tempX']); $this->assertEquals(3, $ret); - $ret = $customer->updateAll(['name' => 'temp'], ['name' => 'user6']); + $ret = $customer->activeRecord()->updateAll(['name' => 'temp'], ['name' => 'user6']); $this->assertEquals(0, $ret); } @@ -2506,7 +2506,7 @@ public function testUpdateCounters(): void $orderItem = $orderItemQuery->findOne($pk); $this->assertEquals(1, $orderItem->getQuantity()); - $ret = $orderItem->updateCounters(['quantity' => -1]); + $ret = $orderItem->activeRecord()->updateCounters(['quantity' => -1]); $this->assertTrue($ret); $this->assertEquals(0, $orderItem->getQuantity()); @@ -2520,7 +2520,7 @@ public function testUpdateCounters(): void $this->assertEquals(2, $orderItem->getQuantity()); $orderItem = new OrderItem(); - $ret = $orderItem->updateAllCounters(['quantity' => 3, 'subtotal' => -10], $pk); + $ret = $orderItem->activeRecord()->updateAllCounters(['quantity' => 3, 'subtotal' => -10], $pk); $this->assertEquals(1, $ret); $orderItem = $orderItemQuery->findOne($pk); @@ -2538,7 +2538,7 @@ public function testDelete(): void $this->assertInstanceOf(Customer::class, $customer); $this->assertEquals('user2', $customer->getName()); - $customer->delete(); + $customer->activeRecord()->delete(); $customer = $customerQuery->findOne(2); $this->assertNull($customer); @@ -2549,13 +2549,13 @@ public function testDelete(): void $this->assertCount(2, $customers); $customer = new Customer(); - $ret = $customer->deleteAll(); + $ret = $customer->activeRecord()->deleteAll(); $this->assertEquals(2, $ret); $customers = $customerQuery->all(); $this->assertCount(0, $customers); - $ret = $customer->deleteAll(); + $ret = $customer->activeRecord()->deleteAll(); $this->assertEquals(0, $ret); } @@ -2593,23 +2593,23 @@ public function testLink(): void $order->setTotal(100); $order->setCreatedAt(time()); - $this->assertTrue($order->getIsNewRecord()); + $this->assertTrue($order->activeRecord()->isNewRecord()); /** belongs to */ $order = new Order(); $order->setTotal(100); $order->setCreatedAt(time()); - $this->assertTrue($order->getIsNewRecord()); + $this->assertTrue($order->activeRecord()->isNewRecord()); $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); $this->assertNull($order->getCustomer()); - $order->link('customer', $customer); - $this->assertFalse($order->getIsNewRecord()); + $order->activeRecord()->link('customer', $customer); + $this->assertFalse($order->activeRecord()->isNewRecord()); $this->assertEquals(1, $order->getCustomerId()); - $this->assertEquals(1, $order->getCustomer()->getPrimaryKey()); + $this->assertEquals(1, $order->getCustomer()->activeRecord()->getPrimaryKey()); /** via model */ $orderQuery = new ActiveQuery(Order::class); @@ -2623,7 +2623,7 @@ public function testLink(): void $itemQuery = new ActiveQuery(Item::class); $item = $itemQuery->findOne(3); - $order->link('items', $item, ['quantity' => 10, 'subtotal' => 100]); + $order->activeRecord()->link('items', $item, ['quantity' => 10, 'subtotal' => 100]); $this->assertCount(3, $order->getItems()); $this->assertCount(3, $order->getOrderItems()); @@ -2640,22 +2640,22 @@ public function testEqual(): void $customerA = (new ActiveQuery(Customer::class))->findOne(1); $customerB = (new ActiveQuery(Customer::class))->findOne(2); - $this->assertFalse($customerA->equals($customerB)); + $this->assertFalse($customerA->activeRecord()->equals($customerB)); $customerB = (new ActiveQuery(Customer::class))->findOne(1); - $this->assertTrue($customerA->equals($customerB)); + $this->assertTrue($customerA->activeRecord()->equals($customerB)); $customerA = (new ActiveQuery(Customer::class))->findOne(1); $customerB = (new ActiveQuery(Item::class))->findOne(1); - $this->assertFalse($customerA->equals($customerB)); + $this->assertFalse($customerA->activeRecord()->equals($customerB)); } public function testARClassAsString(): void { $query = new ActiveQuery(Customer::class); - $this->assertSame(Customer::class, $query->getARClass()); - $this->assertInstanceOf(Customer::class, $query->getARInstance()); + $this->assertSame(Customer::class, $query->getModelClass()); + $this->assertInstanceOf(Customer::class, $query->getModelInstance()); } public function testARClassAsInstance(): void @@ -2663,8 +2663,8 @@ public function testARClassAsInstance(): void $customer = new Customer(); $query = new ActiveQuery($customer); - $this->assertSame($customer, $query->getARClass()); - $this->assertInstanceOf(Customer::class, $query->getARInstance()); + $this->assertSame($customer, $query->getModelClass()); + $this->assertInstanceOf(Customer::class, $query->getModelInstance()); } public function testARClassAsClosure(): void @@ -2672,7 +2672,7 @@ public function testARClassAsClosure(): void $closure = fn (): Customer => new Customer(); $query = new ActiveQuery($closure); - $this->assertSame($closure, $query->getARClass()); - $this->assertInstanceOf(Customer::class, $query->getARInstance()); + $this->assertSame($closure, $query->getModelClass()); + $this->assertInstanceOf(Customer::class, $query->getModelInstance()); } } diff --git a/tests/ActiveRecordTest.php b/tests/ActiveRecordTest.php index acb190a4b..efe591115 100644 --- a/tests/ActiveRecordTest.php +++ b/tests/ActiveRecordTest.php @@ -48,46 +48,46 @@ public function testStoreNull(): void $record = new NullValues(); - $this->assertNull($record->get('var1')); - $this->assertNull($record->get('var2')); - $this->assertNull($record->get('var3')); - $this->assertNull($record->get('stringcol')); - - $record->set('var1', 123); - $record->set('var2', 456); - $record->set('var3', 789); - $record->set('stringcol', 'hello!'); - $record->save(); - - $this->assertTrue($record->refresh()); - $this->assertEquals(123, $record->get('var1')); - $this->assertEquals(456, $record->get('var2')); - $this->assertEquals(789, $record->get('var3')); - $this->assertEquals('hello!', $record->get('stringcol')); - - $record->set('var1', null); - $record->set('var2', null); - $record->set('var3', null); - $record->set('stringcol', null); - $record->save(); - - $this->assertTrue($record->refresh()); - $this->assertNull($record->get('var1')); - $this->assertNull($record->get('var2')); - $this->assertNull($record->get('var3')); - $this->assertNull($record->get('>stringcol')); - - $record->set('var1', 0); - $record->set('var2', 0); - $record->set('var3', 0); - $record->set('stringcol', ''); - $record->save(); - - $this->assertTrue($record->refresh()); - $this->assertEquals(0, $record->get('var1')); - $this->assertEquals(0, $record->get('var2')); - $this->assertEquals(0, $record->get('var3')); - $this->assertEquals('', $record->get('stringcol')); + $this->assertNull($record->activeRecord()->get('var1')); + $this->assertNull($record->activeRecord()->get('var2')); + $this->assertNull($record->activeRecord()->get('var3')); + $this->assertNull($record->activeRecord()->get('stringcol')); + + $record->activeRecord()->set('var1', 123); + $record->activeRecord()->set('var2', 456); + $record->activeRecord()->set('var3', 789); + $record->activeRecord()->set('stringcol', 'hello!'); + $record->activeRecord()->save(); + + $this->assertTrue($record->activeRecord()->refresh()); + $this->assertEquals(123, $record->activeRecord()->get('var1')); + $this->assertEquals(456, $record->activeRecord()->get('var2')); + $this->assertEquals(789, $record->activeRecord()->get('var3')); + $this->assertEquals('hello!', $record->activeRecord()->get('stringcol')); + + $record->activeRecord()->set('var1', null); + $record->activeRecord()->set('var2', null); + $record->activeRecord()->set('var3', null); + $record->activeRecord()->set('stringcol', null); + $record->activeRecord()->save(); + + $this->assertTrue($record->activeRecord()->refresh()); + $this->assertNull($record->activeRecord()->get('var1')); + $this->assertNull($record->activeRecord()->get('var2')); + $this->assertNull($record->activeRecord()->get('var3')); + $this->assertNull($record->activeRecord()->get('>stringcol')); + + $record->activeRecord()->set('var1', 0); + $record->activeRecord()->set('var2', 0); + $record->activeRecord()->set('var3', 0); + $record->activeRecord()->set('stringcol', ''); + $record->activeRecord()->save(); + + $this->assertTrue($record->activeRecord()->refresh()); + $this->assertEquals(0, $record->activeRecord()->get('var1')); + $this->assertEquals(0, $record->activeRecord()->get('var2')); + $this->assertEquals(0, $record->activeRecord()->get('var3')); + $this->assertEquals('', $record->activeRecord()->get('stringcol')); } public function testStoreEmpty(): void @@ -101,9 +101,9 @@ public function testStoreEmpty(): void $record->var2 = ''; $record->var3 = ''; $record->stringcol = ''; - $record->save(); + $record->activeRecord()->save(); - $this->assertTrue($record->refresh()); + $this->assertTrue($record->activeRecord()->refresh()); /** {@see https://github.com/yiisoft/yii2/commit/34945b0b69011bc7cab684c7f7095d837892a0d4#commitcomment-4458225} */ $this->assertSame($record->var1, $record->var2); @@ -117,19 +117,19 @@ public function testIsPrimaryKey(): void $customer = new Customer(); $orderItem = new OrderItem(); - $this->assertTrue($customer->isPrimaryKey(['id'])); - $this->assertFalse($customer->isPrimaryKey([])); - $this->assertFalse($customer->isPrimaryKey(['id', 'name'])); - $this->assertFalse($customer->isPrimaryKey(['name'])); - $this->assertFalse($customer->isPrimaryKey(['name', 'email'])); - - $this->assertTrue($orderItem->isPrimaryKey(['order_id', 'item_id'])); - $this->assertFalse($orderItem->isPrimaryKey([])); - $this->assertFalse($orderItem->isPrimaryKey(['order_id'])); - $this->assertFalse($orderItem->isPrimaryKey(['item_id'])); - $this->assertFalse($orderItem->isPrimaryKey(['quantity'])); - $this->assertFalse($orderItem->isPrimaryKey(['quantity', 'subtotal'])); - $this->assertFalse($orderItem->isPrimaryKey(['order_id', 'item_id', 'quantity'])); + $this->assertTrue($customer->activeRecord()->isPrimaryKey(['id'])); + $this->assertFalse($customer->activeRecord()->isPrimaryKey([])); + $this->assertFalse($customer->activeRecord()->isPrimaryKey(['id', 'name'])); + $this->assertFalse($customer->activeRecord()->isPrimaryKey(['name'])); + $this->assertFalse($customer->activeRecord()->isPrimaryKey(['name', 'email'])); + + $this->assertTrue($orderItem->activeRecord()->isPrimaryKey(['order_id', 'item_id'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey([])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['order_id'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['item_id'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['quantity'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['quantity', 'subtotal'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['order_id', 'item_id', 'quantity'])); } public function testOutdatedRelationsAreResetForNewRecords(): void @@ -149,8 +149,8 @@ public function testOutdatedRelationsAreResetForNewRecords(): void $this->assertEquals(1, $orderItem->getItem()->getId()); /** test `set()`. */ - $orderItem->set('order_id', 2); - $orderItem->set('item_id', 2); + $orderItem->activeRecord()->set('order_id', 2); + $orderItem->activeRecord()->set('item_id', 2); $this->assertEquals(2, $orderItem->getOrder()->getId()); $this->assertEquals(2, $orderItem->getItem()->getId()); } @@ -161,7 +161,7 @@ public function testDefaultValues(): void $arClass = new Type(); - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertSame(1, $arClass->int_col2); $this->assertSame('something', $arClass->char_col2); @@ -177,13 +177,13 @@ public function testDefaultValues(): void $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertSame('not something', $arClass->char_col2); $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(false); + $arClass->activeRecord()->loadDefaultValues(false); $this->assertSame('something', $arClass->char_col2); } @@ -206,7 +206,7 @@ public function testCastValues(): void $arClass->time = new Expression('CURRENT_TIMESTAMP'); $arClass->json_col = ['a' => 'b', 'c' => null, 'd' => [1, 2, 3]]; - $arClass->save(); + $arClass->activeRecord()->save(); /** @var $model Type */ $aqClass = new ActiveQuery(Type::class); @@ -230,10 +230,10 @@ public function testPopulateRecordCallWhenQueryingOnParentClass(): void $this->checkFixture($this->db(), 'cat'); $cat = new Cat(); - $cat->save(); + $cat->activeRecord()->save(); $dog = new Dog(); - $dog->save(); + $dog->activeRecord()->save(); $animal = (new ActiveQuery(Animal::class))->resultCallback(ModelFactory::create(...)); @@ -250,7 +250,7 @@ public function testSaveEmpty(): void $record = new NullValues(); - $this->assertTrue($record->save()); + $this->assertTrue($record->activeRecord()->save()); $this->assertEquals(1, $record->id); } @@ -266,15 +266,15 @@ public function testNoTablenameReplacement(): void $customer->setName('Some {{weird}} name'); $customer->setEmail('test@example.com'); $customer->setAddress('Some {{%weird}} address'); - $customer->insert(); - $customer->refresh(); + $customer->activeRecord()->insert(); + $customer->activeRecord()->refresh(); $this->assertEquals('Some {{weird}} name', $customer->getName()); $this->assertEquals('Some {{%weird}} address', $customer->getAddress()); $customer->setName('Some {{updated}} name'); $customer->setAddress('Some {{%updated}} address'); - $customer->update(); + $customer->activeRecord()->update(); $this->assertEquals('Some {{updated}} name', $customer->getName()); $this->assertEquals('Some {{%updated}} address', $customer->getAddress()); @@ -382,7 +382,7 @@ public function testRefreshQuerySetAliasFindRecord(): void $customer = new CustomerWithAlias(); $customer->id = 1; - $customer->refresh(); + $customer->activeRecord()->refresh(); $this->assertEquals(1, $customer->id); } @@ -401,9 +401,9 @@ public function testResetNotSavedRelation(): void $order->getOrderItems(); - $order->populateRelation('orderItems', [$orderItem]); + $order->activeRecord()->populateRelation('orderItems', [$orderItem]); - $order->save(); + $order->activeRecord()->save(); $this->assertCount(1, $order->getOrderItems()); } @@ -460,9 +460,9 @@ public function testSetProperties(): void $customer = new Customer(); - $customer->populateProperties($properties); + $customer->activeRecord()->populateProperties($properties); - $this->assertTrue($customer->save()); + $this->assertTrue($customer->activeRecord()->save()); } public function testSetPropertyNoExist(): void @@ -478,7 +478,7 @@ public function testSetPropertyNoExist(): void 'Yiisoft\ActiveRecord\Tests\Stubs\MagicActiveRecord\Cat has no property named "noExist"' ); - $cat->set('noExist', 1); + $cat->activeRecord()->set('noExist', 1); } public function testAssignOldValue(): void @@ -487,11 +487,11 @@ public function testAssignOldValue(): void $customer = new Customer(); - $this->assertEmpty($customer->oldValue('name')); + $this->assertEmpty($customer->activeRecord()->oldValue('name')); - $customer->assignOldValue('name', 'samdark'); + $customer->activeRecord()->assignOldValue('name', 'samdark'); - $this->assertEquals('samdark', $customer->oldValue('name')); + $this->assertEquals('samdark', $customer->activeRecord()->oldValue('name')); } public function testaAssignOldValueException(): void @@ -500,13 +500,13 @@ public function testaAssignOldValueException(): void $customer = new Customer(); - $this->assertEmpty($customer->oldValue('name')); + $this->assertEmpty($customer->activeRecord()->oldValue('name')); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Customer has no property named "noExist"' ); - $customer->assignOldValue('noExist', 'samdark'); + $customer->activeRecord()->assignOldValue('noExist', 'samdark'); } public function testIsPropertyChangedNotChanged(): void @@ -515,10 +515,10 @@ public function testIsPropertyChangedNotChanged(): void $customer = new Customer(); - $this->assertEmpty($customer->get('email')); - $this->assertEmpty($customer->oldValue('email')); - $this->assertFalse($customer->isPropertyChanged('email')); - $this->assertFalse($customer->isPropertyChangedNonStrict('email')); + $this->assertEmpty($customer->activeRecord()->get('email')); + $this->assertEmpty($customer->activeRecord()->oldValue('email')); + $this->assertFalse($customer->activeRecord()->isPropertyChanged('email')); + $this->assertFalse($customer->activeRecord()->isPropertyChangedNonStrict('email')); } public function testTableSchemaException(): void @@ -527,7 +527,8 @@ public function testTableSchemaException(): void $this->expectException(InvalidConfigException::class); $this->expectExceptionMessage('The table does not exist: NoExist'); - $noExist->getTableSchema(); + + $noExist->activeRecord()->getTableSchema(); } public function testInsert(): void @@ -540,13 +541,13 @@ public function testInsert(): void $customer->setName('user4'); $customer->setAddress('address4'); - $this->assertNull($customer->get('id')); - $this->assertTrue($customer->getIsNewRecord()); + $this->assertNull($customer->activeRecord()->get('id')); + $this->assertTrue($customer->activeRecord()->isNewRecord()); - $customer->save(); + $customer->activeRecord()->save(); $this->assertNotNull($customer->getId()); - $this->assertFalse($customer->getIsNewRecord()); + $this->assertFalse($customer->activeRecord()->isNewRecord()); } /** @@ -564,14 +565,14 @@ public function testBooleanProperty(): void $customer->setEmail('mail@example.com'); $customer->setBoolStatus(true); - $customer->save(); - $customer->refresh(); + $customer->activeRecord()->save(); + $customer->activeRecord()->refresh(); $this->assertTrue($customer->getBoolStatus()); $customer->setBoolStatus(false); - $customer->save(); + $customer->activeRecord()->save(); - $customer->refresh(); + $customer->activeRecord()->refresh(); $this->assertFalse($customer->getBoolStatus()); $customerQuery = new ActiveQuery(Customer::class); @@ -604,7 +605,7 @@ public function testPropertyAccess(): void /** {@see https://github.com/yiisoft/yii2-gii/issues/190} */ $baseModel = new Customer(); - $this->assertFalse($baseModel->hasProperty('unExistingColumn')); + $this->assertFalse($baseModel->activeRecord()->hasProperty('unExistingColumn')); $customer = new Customer(); $this->assertInstanceOf(Customer::class, $customer); @@ -647,15 +648,15 @@ public function testHasProperty(): void $customer = new Customer(); - $this->assertTrue($customer->hasProperty('id')); - $this->assertTrue($customer->hasProperty('email')); - $this->assertFalse($customer->hasProperty('notExist')); + $this->assertTrue($customer->activeRecord()->hasProperty('id')); + $this->assertTrue($customer->activeRecord()->hasProperty('email')); + $this->assertFalse($customer->activeRecord()->hasProperty('notExist')); $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); - $this->assertTrue($customer->hasProperty('id')); - $this->assertTrue($customer->hasProperty('email')); - $this->assertFalse($customer->hasProperty('notExist')); + $this->assertTrue($customer->activeRecord()->hasProperty('id')); + $this->assertTrue($customer->activeRecord()->hasProperty('email')); + $this->assertFalse($customer->activeRecord()->hasProperty('notExist')); } public function testRefresh(): void @@ -664,13 +665,13 @@ public function testRefresh(): void $customer = new Customer(); - $this->assertFalse($customer->refresh()); + $this->assertFalse($customer->activeRecord()->refresh()); $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); $customer->setName('to be refreshed'); - $this->assertTrue($customer->refresh()); + $this->assertTrue($customer->activeRecord()->refresh()); $this->assertEquals('user1', $customer->getName()); } @@ -680,11 +681,11 @@ public function testEquals(): void $customerA = new Customer(); $customerB = new Customer(); - $this->assertFalse($customerA->equals($customerB)); + $this->assertFalse($customerA->activeRecord()->equals($customerB)); $customerA = new Customer(); $customerB = new Item(); - $this->assertFalse($customerA->equals($customerB)); + $this->assertFalse($customerA->activeRecord()->equals($customerB)); } public static function providerForUnlinkDelete(): array @@ -709,7 +710,7 @@ public function testUnlinkWithViaOnCondition($delete, $count): void $order = $orderQuery->findOne(2); $this->assertCount(1, $order->getItemsFor8()); - $order->unlink('itemsFor8', $order->getItemsFor8()[0], $delete); + $order->activeRecord()->unlink('itemsFor8', $order->getItemsFor8()[0], $delete); $order = $orderQuery->findOne(2); $this->assertCount(0, $order->getItemsFor8()); @@ -772,7 +773,7 @@ public function testSaveWithoutChanges(): void $customer = $customerQuery->findOne(1); - $this->assertTrue($customer->save()); + $this->assertTrue($customer->activeRecord()->save()); } public function testGetPrimaryKey(): void @@ -783,8 +784,8 @@ public function testGetPrimaryKey(): void $customer = $customerQuery->findOne(1); - $this->assertSame(1, $customer->getPrimaryKey()); - $this->assertSame(['id' => 1], $customer->getPrimaryKey(true)); + $this->assertSame(1, $customer->activeRecord()->getPrimaryKey()); + $this->assertSame(['id' => 1], $customer->activeRecord()->getPrimaryKey(true)); } public function testGetOldPrimaryKey(): void @@ -796,8 +797,8 @@ public function testGetOldPrimaryKey(): void $customer = $customerQuery->findOne(1); $customer->setId(2); - $this->assertSame(1, $customer->getOldPrimaryKey()); - $this->assertSame(['id' => 1], $customer->getOldPrimaryKey(true)); + $this->assertSame(1, $customer->activeRecord()->getOldPrimaryKey()); + $this->assertSame(['id' => 1], $customer->activeRecord()->getOldPrimaryKey(true)); } public function testGetDirtyValuesOnNewRecord(): void @@ -814,14 +815,14 @@ public function testGetDirtyValuesOnNewRecord(): void 'bool_status' => false, 'profile_id' => null, ], - $customer->newValues() + $customer->activeRecord()->newValues() ); - $customer->set('name', 'Adam'); - $customer->set('email', 'adam@example.com'); - $customer->set('address', null); + $customer->activeRecord()->set('name', 'Adam'); + $customer->activeRecord()->set('email', 'adam@example.com'); + $customer->activeRecord()->set('address', null); - $this->assertSame([], $customer->newValues([])); + $this->assertSame([], $customer->activeRecord()->newValues([])); $this->assertEquals( [ @@ -832,7 +833,7 @@ public function testGetDirtyValuesOnNewRecord(): void 'bool_status' => false, 'profile_id' => null, ], - $customer->newValues() + $customer->activeRecord()->newValues() ); $this->assertSame( [ @@ -840,15 +841,15 @@ public function testGetDirtyValuesOnNewRecord(): void 'address' => null, 'status' => 0, ], - $customer->newValues(['id', 'email', 'address', 'status', 'unknown']), + $customer->activeRecord()->newValues(['id', 'email', 'address', 'status', 'unknown']), ); - $this->assertTrue($customer->save()); - $this->assertSame([], $customer->newValues()); + $this->assertTrue($customer->activeRecord()->save()); + $this->assertSame([], $customer->activeRecord()->newValues()); - $customer->set('address', ''); + $customer->activeRecord()->set('address', ''); - $this->assertSame(['address' => ''], $customer->newValues()); + $this->assertSame(['address' => ''], $customer->activeRecord()->newValues()); } public function testGetDirtyValuesAfterFind(): void @@ -858,19 +859,19 @@ public function testGetDirtyValuesAfterFind(): void $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); - $this->assertSame([], $customer->newValues()); + $this->assertSame([], $customer->activeRecord()->newValues()); - $customer->set('name', 'Adam'); - $customer->set('email', 'adam@example.com'); - $customer->set('address', null); + $customer->activeRecord()->set('name', 'Adam'); + $customer->activeRecord()->set('email', 'adam@example.com'); + $customer->activeRecord()->set('address', null); $this->assertEquals( ['name' => 'Adam', 'email' => 'adam@example.com', 'address' => null], - $customer->newValues(), + $customer->activeRecord()->newValues(), ); $this->assertEquals( ['email' => 'adam@example.com', 'address' => null], - $customer->newValues(['id', 'email', 'address', 'status', 'unknown']), + $customer->activeRecord()->newValues(['id', 'email', 'address', 'status', 'unknown']), ); } @@ -883,7 +884,7 @@ public function testRelationWithInstance(): void $orders = $customer->getOrdersUsingInstance(); - $this->assertTrue($customer->isRelationPopulated('ordersUsingInstance')); + $this->assertTrue($customer->activeRecord()->isRelationPopulated('ordersUsingInstance')); $this->assertCount(2, $orders); $this->assertSame(2, $orders[0]->getId()); $this->assertSame(3, $orders[1]->getId()); @@ -919,7 +920,7 @@ public function testWithFactory(): void $order = $orderQuery->with('customerWithFactory')->findOne(2); $this->assertInstanceOf(OrderWithFactory::class, $order); - $this->assertTrue($order->isRelationPopulated('customerWithFactory')); + $this->assertTrue($order->activeRecord()->isRelationPopulated('customerWithFactory')); $this->assertInstanceOf(CustomerWithFactory::class, $order->getCustomerWithFactory()); } @@ -972,7 +973,7 @@ public function testWithFactoryLazyRelation(): void $order = $orderQuery->findOne(2); $this->assertInstanceOf(OrderWithFactory::class, $order); - $this->assertFalse($order->isRelationPopulated('customerWithFactory')); + $this->assertFalse($order->activeRecord()->isRelationPopulated('customerWithFactory')); $this->assertInstanceOf(CustomerWithFactory::class, $order->getCustomerWithFactory()); } @@ -986,7 +987,7 @@ public function testWithFactoryWithConstructor(): void $customer = $customerQuery->findOne(2); $this->assertInstanceOf(CustomerWithFactory::class, $customer); - $this->assertFalse($customer->isRelationPopulated('ordersWithFactory')); + $this->assertFalse($customer->activeRecord()->isRelationPopulated('ordersWithFactory')); $this->assertInstanceOf(OrderWithFactory::class, $customer->getOrdersWithFactory()[0]); } @@ -1014,7 +1015,7 @@ public function testSerialization(): void $profile = new Profile(); $this->assertEquals( - "O:53:\"Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Profile\":3:{s:52:\"\0Yiisoft\ActiveRecord\AbstractActiveRecord\0oldValues\";N;s:50:\"\0Yiisoft\ActiveRecord\AbstractActiveRecord\0related\";a:0:{}s:64:\"\0Yiisoft\ActiveRecord\AbstractActiveRecord\0relationsDependencies\";a:0:{}}", + "O:53:\"Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Profile\":0:{}", serialize($profile) ); @@ -1022,7 +1023,7 @@ public function testSerialization(): void $profile = $profileQuery->findOne(1); $this->assertEquals( - "O:53:\"Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Profile\":5:{s:52:\"\0Yiisoft\ActiveRecord\AbstractActiveRecord\0oldValues\";a:2:{s:2:\"id\";i:1;s:11:\"description\";s:18:\"profile customer 1\";}s:50:\"\0Yiisoft\ActiveRecord\AbstractActiveRecord\0related\";a:0:{}s:64:\"\0Yiisoft\ActiveRecord\AbstractActiveRecord\0relationsDependencies\";a:0:{}s:5:\"\0*\0id\";i:1;s:14:\"\0*\0description\";s:18:\"profile customer 1\";}", + "O:53:\"Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Profile\":3:{s:60:\"\0Yiisoft\ActiveRecord\AbstractActiveRecordModel\0activeRecord\";O:33:\"Yiisoft\ActiveRecord\ActiveRecord\":4:{s:52:\"\0Yiisoft\ActiveRecord\AbstractActiveRecord\0oldValues\";a:2:{s:2:\"id\";i:1;s:11:\"description\";s:18:\"profile customer 1\";}s:50:\"\0Yiisoft\ActiveRecord\AbstractActiveRecord\0related\";a:0:{}s:64:\"\0Yiisoft\ActiveRecord\AbstractActiveRecord\0relationsDependencies\";a:0:{}s:8:\"\0*\0model\";r:1;}s:5:\"\0*\0id\";i:1;s:14:\"\0*\0description\";s:18:\"profile customer 1\";}", serialize($profile) ); } @@ -1047,7 +1048,7 @@ public function testRelationViaJson(): void /** Test inverse relation */ foreach ($promotions as $promotion) { foreach ($promotion->getItemsViaJson() as $item) { - $this->assertTrue($item->isRelationPopulated('promotionsViaJson')); + $this->assertTrue($item->activeRecord()->isRelationPopulated('promotionsViaJson')); } } @@ -1072,11 +1073,11 @@ public function testLazzyRelationViaJson(): void /** @var Item[] $items */ $items = $itemQuery->all(); - $this->assertFalse($items[0]->isRelationPopulated('promotionsViaJson')); - $this->assertFalse($items[1]->isRelationPopulated('promotionsViaJson')); - $this->assertFalse($items[2]->isRelationPopulated('promotionsViaJson')); - $this->assertFalse($items[3]->isRelationPopulated('promotionsViaJson')); - $this->assertFalse($items[4]->isRelationPopulated('promotionsViaJson')); + $this->assertFalse($items[0]->activeRecord()->isRelationPopulated('promotionsViaJson')); + $this->assertFalse($items[1]->activeRecord()->isRelationPopulated('promotionsViaJson')); + $this->assertFalse($items[2]->activeRecord()->isRelationPopulated('promotionsViaJson')); + $this->assertFalse($items[3]->activeRecord()->isRelationPopulated('promotionsViaJson')); + $this->assertFalse($items[4]->activeRecord()->isRelationPopulated('promotionsViaJson')); $this->assertSame([1, 3], ArArrayHelper::getColumn($items[0]->getPromotionsViaJson(), 'id')); $this->assertSame([1], ArArrayHelper::getColumn($items[1]->getPromotionsViaJson(), 'id')); @@ -1092,20 +1093,20 @@ public function testIsChanged(): void $itemQuery = new ActiveQuery(Item::class); $item = $itemQuery->findOne(1); - $this->assertFalse($item->isChanged()); + $this->assertFalse($item->activeRecord()->isChanged()); - $item->set('name', 'New name'); + $item->activeRecord()->set('name', 'New name'); - $this->assertTrue($item->isChanged()); + $this->assertTrue($item->activeRecord()->isChanged()); $newItem = new Item(); - $this->assertFalse($newItem->isChanged()); + $this->assertFalse($newItem->activeRecord()->isChanged()); - $newItem->set('name', 'New name'); + $newItem->activeRecord()->set('name', 'New name'); - $this->assertTrue($newItem->isChanged()); + $this->assertTrue($newItem->activeRecord()->isChanged()); - $this->assertTrue((new Customer())->isChanged()); + $this->assertTrue((new Customer())->activeRecord()->isChanged()); } } diff --git a/tests/BatchQueryResultTest.php b/tests/BatchQueryResultTest.php index 038cc426f..22e0f9403 100644 --- a/tests/BatchQueryResultTest.php +++ b/tests/BatchQueryResultTest.php @@ -126,7 +126,7 @@ public function testActiveQuery(): void $customers = $this->getAllRowsFromBatch($query->batch(2)); foreach ($customers as $customer) { - $this->assertTrue($customer->isRelationPopulated('orders')); + $this->assertTrue($customer->activeRecord()->isRelationPopulated('orders')); } $this->assertCount(3, $customers); diff --git a/tests/Driver/Mssql/ActiveRecordTest.php b/tests/Driver/Mssql/ActiveRecordTest.php index a15944aa9..cd7c05956 100644 --- a/tests/Driver/Mssql/ActiveRecordTest.php +++ b/tests/Driver/Mssql/ActiveRecordTest.php @@ -53,7 +53,7 @@ public function testSaveWithTrigger(): void $record->stringcol = 'test'; - $this->assertTrue($record->save()); + $this->assertTrue($record->activeRecord()->save()); $this->assertEquals(1, $record->id); $testRecordQuery = new ActiveQuery(TestTriggerAlert::class); diff --git a/tests/Driver/Mssql/MagicActiveRecordTest.php b/tests/Driver/Mssql/MagicActiveRecordTest.php index 174f74d0d..818a79e03 100644 --- a/tests/Driver/Mssql/MagicActiveRecordTest.php +++ b/tests/Driver/Mssql/MagicActiveRecordTest.php @@ -47,7 +47,7 @@ public function testSaveWithTrigger(): void $record->stringcol = 'test'; - $this->assertTrue($record->save()); + $this->assertTrue($record->activeRecord()->save()); $this->assertEquals(1, $record->id); $testRecordQuery = new ActiveQuery(TestTriggerAlert::class); diff --git a/tests/Driver/Mysql/ActiveRecordTest.php b/tests/Driver/Mysql/ActiveRecordTest.php index 0147aa732..0e79ff106 100644 --- a/tests/Driver/Mysql/ActiveRecordTest.php +++ b/tests/Driver/Mysql/ActiveRecordTest.php @@ -30,7 +30,7 @@ public function testCastValues(): void $arClass = new Type(); - $arClass->deleteAll(); + $arClass->activeRecord()->deleteAll(); $arClass->int_col = 123; $arClass->int_col2 = 456; @@ -45,7 +45,7 @@ public function testCastValues(): void $arClass->bool_col2 = false; $arClass->json_col = ['a' => 'b', 'c' => null, 'd' => [1, 2, 3]]; - $arClass->save(); + $arClass->activeRecord()->save(); /** @var $model Type */ $aqClass = new ActiveQuery(Type::class); @@ -76,12 +76,12 @@ public function testExplicitPkOnAutoIncrement(): void $customer->setName('user1337'); $customer->setAddress('address1337'); - $this->assertTrue($customer->getIsNewRecord()); + $this->assertTrue($customer->activeRecord()->isNewRecord()); - $customer->save(); + $customer->activeRecord()->save(); $this->assertEquals(1337, $customer->getId()); - $this->assertFalse($customer->getIsNewRecord()); + $this->assertFalse($customer->activeRecord()->isNewRecord()); } /** diff --git a/tests/Driver/Mysql/MagicActiveRecordTest.php b/tests/Driver/Mysql/MagicActiveRecordTest.php index f63839acb..823e429cd 100644 --- a/tests/Driver/Mysql/MagicActiveRecordTest.php +++ b/tests/Driver/Mysql/MagicActiveRecordTest.php @@ -28,12 +28,12 @@ public function testExplicitPkOnAutoIncrement(): void $customer->name = 'user1337'; $customer->address = 'address1337'; - $this->assertTrue($customer->isNewRecord); + $this->assertTrue($customer->activeRecord()->isNewRecord()); - $customer->save(); + $customer->activeRecord()->save(); $this->assertEquals(1337, $customer->id); - $this->assertFalse($customer->isNewRecord); + $this->assertFalse($customer->activeRecord()->isNewRecord()); } /** diff --git a/tests/Driver/Oracle/ActiveQueryTest.php b/tests/Driver/Oracle/ActiveQueryTest.php index 924088bf7..4bfeff34c 100644 --- a/tests/Driver/Oracle/ActiveQueryTest.php +++ b/tests/Driver/Oracle/ActiveQueryTest.php @@ -53,9 +53,9 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); $this->assertEquals(1, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); - $this->assertTrue($orders[2]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated('customer')); /** inner join filtering and eager loading */ $orderQuery = new ActiveQuery(Order::class); @@ -74,8 +74,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(2, $orders); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('customer')); - $this->assertTrue($orders[1]->isRelationPopulated('customer')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('customer')); /** inner join filtering without eager loading */ $orderQuery = new ActiveQuery(Order::class); @@ -94,8 +94,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(2, $orders); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertFalse($orders[0]->isRelationPopulated('customer')); - $this->assertFalse($orders[1]->isRelationPopulated('customer')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('customer')); + $this->assertFalse($orders[1]->activeRecord()->isRelationPopulated('customer')); /** join with via-relation */ $orderQuery = new ActiveQuery(Order::class); @@ -120,8 +120,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(1, $orders[1]->getBooks()); $this->assertEquals(1, $orders[0]->getId()); $this->assertEquals(3, $orders[1]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('books')); - $this->assertTrue($orders[1]->isRelationPopulated('books')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('books')); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated('books')); /** joining sub relations */ $orderQuery = new ActiveQuery(Order::class); @@ -162,8 +162,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(3, $orders[0]->getItems()); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('items')); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); /** join with ON condition */ if ($aliasMethod === 'explicit' || $aliasMethod === 'querysyntax') { @@ -173,15 +173,15 @@ public function testJoinWithAlias(string $aliasMethod): void $orders = $orderQuery->joinWith(["$relationName b"])->orderBy('order.id')->all(); $this->assertCount(3, $orders); - $this->assertCount(2, $orders[0]->relation($relationName)); - $this->assertCount(0, $orders[1]->relation($relationName)); - $this->assertCount(1, $orders[2]->relation($relationName)); + $this->assertCount(2, $orders[0]->activeRecord()->relation($relationName)); + $this->assertCount(0, $orders[1]->activeRecord()->relation($relationName)); + $this->assertCount(1, $orders[2]->activeRecord()->relation($relationName)); $this->assertEquals(1, $orders[0]->getId()); $this->assertEquals(2, $orders[1]->getId()); $this->assertEquals(3, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated($relationName)); - $this->assertTrue($orders[1]->isRelationPopulated($relationName)); - $this->assertTrue($orders[2]->isRelationPopulated($relationName)); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated($relationName)); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated($relationName)); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated($relationName)); } /** join with ON condition and alias in relation definition */ @@ -192,15 +192,15 @@ public function testJoinWithAlias(string $aliasMethod): void $orders = $orderQuery->joinWith([$relationName])->orderBy('order.id')->all(); $this->assertCount(3, $orders); - $this->assertCount(2, $orders[0]->relation($relationName)); - $this->assertCount(0, $orders[1]->relation($relationName)); - $this->assertCount(1, $orders[2]->relation($relationName)); + $this->assertCount(2, $orders[0]->activeRecord()->relation($relationName)); + $this->assertCount(0, $orders[1]->activeRecord()->relation($relationName)); + $this->assertCount(1, $orders[2]->activeRecord()->relation($relationName)); $this->assertEquals(1, $orders[0]->getId()); $this->assertEquals(2, $orders[1]->getId()); $this->assertEquals(3, $orders[2]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated($relationName)); - $this->assertTrue($orders[1]->isRelationPopulated($relationName)); - $this->assertTrue($orders[2]->isRelationPopulated($relationName)); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated($relationName)); + $this->assertTrue($orders[1]->activeRecord()->isRelationPopulated($relationName)); + $this->assertTrue($orders[2]->activeRecord()->isRelationPopulated($relationName)); } /** join with count and query */ @@ -261,8 +261,8 @@ public function testJoinWithAlias(string $aliasMethod): void $this->assertCount(3, $orders[0]->getItems()); $this->assertEquals(2, $orders[0]->getId()); $this->assertEquals(2, $orders[0]->getItems()[0]->getCategory()->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('items')); - $this->assertTrue($orders[0]->getItems()[0]->isRelationPopulated('category')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('items')); + $this->assertTrue($orders[0]->getItems()[0]->activeRecord()->isRelationPopulated('category')); } /** @@ -288,8 +288,8 @@ public function testJoinWithSameTable(): void $query->createCommand()->getRawSql() . print_r($orders, true) ); $this->assertEquals(2, $orders[0]->getId()); - $this->assertFalse($orders[0]->isRelationPopulated('bookItems')); - $this->assertFalse($orders[0]->isRelationPopulated('movieItems')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('bookItems')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('movieItems')); /** with eager loading */ $query = new ActiveQuery(Order::class); @@ -303,8 +303,8 @@ public function testJoinWithSameTable(): void $this->assertCount(0, $orders[0]->getBookItems()); $this->assertCount(3, $orders[0]->getMovieItems()); $this->assertEquals(2, $orders[0]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('bookItems')); - $this->assertTrue($orders[0]->isRelationPopulated('movieItems')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('bookItems')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('movieItems')); /** * join with the same table but different aliases alias is defined in the call to joinWith() without eager @@ -334,7 +334,7 @@ public function testJoinWithSameTable(): void $query->createCommand()->getRawSql() . print_r($orders, true) ); $this->assertEquals(2, $orders[0]->getId()); - $this->assertFalse($orders[0]->isRelationPopulated('itemsIndexed')); + $this->assertFalse($orders[0]->activeRecord()->isRelationPopulated('itemsIndexed')); /** with eager loading, only for one relation as it would be overwritten otherwise. */ $query = new ActiveQuery(Order::class); @@ -359,7 +359,7 @@ public function testJoinWithSameTable(): void $this->assertCount(1, $orders, $query->createCommand()->getRawSql() . print_r($orders, true)); $this->assertCount(3, $orders[0]->getItemsIndexed()); $this->assertEquals(2, $orders[0]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('itemsIndexed')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('itemsIndexed')); /** with eager loading, and the other relation */ $query = new ActiveQuery(Order::class); @@ -385,6 +385,6 @@ public function testJoinWithSameTable(): void $this->assertCount(1, $orders, $query->createCommand()->getRawSql() . print_r($orders, true)); $this->assertCount(0, $orders[0]->getItemsIndexed()); $this->assertEquals(2, $orders[0]->getId()); - $this->assertTrue($orders[0]->isRelationPopulated('itemsIndexed')); + $this->assertTrue($orders[0]->activeRecord()->isRelationPopulated('itemsIndexed')); } } diff --git a/tests/Driver/Oracle/ActiveRecordTest.php b/tests/Driver/Oracle/ActiveRecordTest.php index 12c125cfe..2a491fa7d 100644 --- a/tests/Driver/Oracle/ActiveRecordTest.php +++ b/tests/Driver/Oracle/ActiveRecordTest.php @@ -28,7 +28,7 @@ public function testDefaultValues(): void $this->checkFixture($this->db(), 'customer'); $arClass = new Type(); - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertSame(1, $arClass->int_col2); $this->assertSame('something', $arClass->char_col2); $this->assertSame(1.23, $arClass->float_col2); @@ -40,13 +40,13 @@ public function testDefaultValues(): void $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertSame('not something', $arClass->char_col2); $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(false); + $arClass->activeRecord()->loadDefaultValues(false); $this->assertSame('something', $arClass->char_col2); } @@ -65,14 +65,14 @@ public function testBooleanProperty(): void $customer->setEmail('mail@example.com'); $customer->setBoolStatus(true); - $customer->save(); - $customer->refresh(); + $customer->activeRecord()->save(); + $customer->activeRecord()->refresh(); $this->assertTrue($customer->getBoolStatus()); $customer->setBoolStatus(false); - $customer->save(); + $customer->activeRecord()->save(); - $customer->refresh(); + $customer->activeRecord()->refresh(); $this->assertFalse($customer->getBoolStatus()); $customerQuery = new ActiveQuery(Customer::class); diff --git a/tests/Driver/Oracle/MagicActiveRecordTest.php b/tests/Driver/Oracle/MagicActiveRecordTest.php index 0b09e8885..3b40724f9 100644 --- a/tests/Driver/Oracle/MagicActiveRecordTest.php +++ b/tests/Driver/Oracle/MagicActiveRecordTest.php @@ -22,7 +22,7 @@ public function testDefaultValues(): void $this->checkFixture($this->db(), 'customer'); $arClass = new Type(); - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertSame(1, $arClass->int_col2); $this->assertSame('something', $arClass->char_col2); $this->assertSame(1.23, $arClass->float_col2); @@ -34,13 +34,13 @@ public function testDefaultValues(): void $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertSame('not something', $arClass->char_col2); $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(false); + $arClass->activeRecord()->loadDefaultValues(false); $this->assertSame('something', $arClass->char_col2); } @@ -59,14 +59,14 @@ public function testBooleanProperty(): void $customer->email = 'mail@example.com'; $customer->bool_status = true; - $customer->save(); - $customer->refresh(); + $customer->activeRecord()->save(); + $customer->activeRecord()->refresh(); $this->assertTrue($customer->bool_status); $customer->bool_status = false; - $customer->save(); + $customer->activeRecord()->save(); - $customer->refresh(); + $customer->activeRecord()->refresh(); $this->assertFalse($customer->bool_status); $customerQuery = new ActiveQuery(Customer::class); diff --git a/tests/Driver/Oracle/Stubs/Customer.php b/tests/Driver/Oracle/Stubs/Customer.php index e341e5f64..fe777fd8e 100644 --- a/tests/Driver/Oracle/Stubs/Customer.php +++ b/tests/Driver/Oracle/Stubs/Customer.php @@ -15,6 +15,6 @@ final class Customer extends \Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Cust public function getOrdersQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('{{customer}}.[[id]]'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('{{customer}}.[[id]]'); } } diff --git a/tests/Driver/Oracle/Stubs/MagicCustomer.php b/tests/Driver/Oracle/Stubs/MagicCustomer.php index 2f29499a3..0bffa52c3 100644 --- a/tests/Driver/Oracle/Stubs/MagicCustomer.php +++ b/tests/Driver/Oracle/Stubs/MagicCustomer.php @@ -20,6 +20,6 @@ final class MagicCustomer extends \Yiisoft\ActiveRecord\Tests\Stubs\MagicActiveR { public function getOrdersQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('{{customer}}.[[id]]'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('{{customer}}.[[id]]'); } } diff --git a/tests/Driver/Oracle/Stubs/MagicOrder.php b/tests/Driver/Oracle/Stubs/MagicOrder.php index 89d526c15..969474d4d 100644 --- a/tests/Driver/Oracle/Stubs/MagicOrder.php +++ b/tests/Driver/Oracle/Stubs/MagicOrder.php @@ -18,6 +18,6 @@ final class MagicOrder extends \Yiisoft\ActiveRecord\Tests\Stubs\MagicActiveReco { public function getCustomerQuery(): ActiveQuery { - return $this->hasOne(MagicCustomer::class, ['id' => 'customer_id']); + return $this->activeRecord()->hasOne(MagicCustomer::class, ['id' => 'customer_id']); } } diff --git a/tests/Driver/Oracle/Stubs/Order.php b/tests/Driver/Oracle/Stubs/Order.php index d0e67c16c..512036779 100644 --- a/tests/Driver/Oracle/Stubs/Order.php +++ b/tests/Driver/Oracle/Stubs/Order.php @@ -18,6 +18,6 @@ final class Order extends \Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Order { public function getCustomerQuery(): ActiveQuery { - return $this->hasOne(Customer::class, ['id' => 'customer_id']); + return $this->activeRecord()->hasOne(Customer::class, ['id' => 'customer_id']); } } diff --git a/tests/Driver/Pgsql/ActiveRecordTest.php b/tests/Driver/Pgsql/ActiveRecordTest.php index 473cb495d..2be9a4828 100644 --- a/tests/Driver/Pgsql/ActiveRecordTest.php +++ b/tests/Driver/Pgsql/ActiveRecordTest.php @@ -41,7 +41,7 @@ public function testDefaultValues(): void $arClass = new Type(); - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertSame(1, $arClass->int_col2); $this->assertSame('something', $arClass->char_col2); @@ -54,13 +54,13 @@ public function testDefaultValues(): void $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertSame('not something', $arClass->char_col2); $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(false); + $arClass->activeRecord()->loadDefaultValues(false); $this->assertSame('something', $arClass->char_col2); } @@ -82,7 +82,7 @@ public function testCastValues(): void $arClass->bool_col2 = false; $arClass->json_col = ['a' => 'b', 'c' => null, 'd' => [1, 2, 3]]; - $arClass->save(); + $arClass->activeRecord()->save(); /** @var $model Type */ $aqClass = new ActiveQuery(Type::class); @@ -110,11 +110,11 @@ public function testExplicitPkOnAutoIncrement(): void $customer->setEmail('user1337@example.com'); $customer->setName('user1337'); $customer->setAddress('address1337'); - $this->assertTrue($customer->getIsNewRecord()); + $this->assertTrue($customer->activeRecord()->isNewRecord()); - $customer->save(); + $customer->activeRecord()->save(); $this->assertEquals(1337, $customer->getId()); - $this->assertFalse($customer->getIsNewRecord()); + $this->assertFalse($customer->activeRecord()->isNewRecord()); } /** @@ -197,7 +197,7 @@ public function testBooleanValues2(): void $user->email = 'test@example.com'; $user->created_at = time(); $user->updated_at = time(); - $user->save(); + $user->activeRecord()->save(); $userQuery = new ActiveQuery(UserAR::class); $this->assertCount(1, $userQuery->where(['is_deleted' => false])->all()); @@ -215,12 +215,12 @@ public function testBooleanDefaultValues(): void $this->assertTrue($arClass->default_true); $this->assertFalse($arClass->default_false); - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertNull($arClass->bool_col); $this->assertTrue($arClass->default_true); $this->assertFalse($arClass->default_false); - $this->assertTrue($arClass->save()); + $this->assertTrue($arClass->activeRecord()->save()); } public function testPrimaryKeyAfterSave(): void @@ -231,9 +231,9 @@ public function testPrimaryKeyAfterSave(): void $record->type = 'type'; - $record->save(); + $record->activeRecord()->save(); - $this->assertEquals(5, $record->getPrimaryKey()); + $this->assertEquals(5, $record->activeRecord()->getPrimaryKey()); } public static function arrayValuesProvider(): array @@ -316,10 +316,10 @@ public function testArrayValues($properties): void $type = new ArrayAndJsonTypes(); foreach ($properties as $property => $expected) { - $type->set($property, $expected[0]); + $type->activeRecord()->set($property, $expected[0]); } - $type->save(); + $type->activeRecord()->save(); $typeQuery = new ActiveQuery($type::class); @@ -327,7 +327,7 @@ public function testArrayValues($properties): void foreach ($properties as $property => $expected) { $expected = $expected[1] ?? $expected[0]; - $value = $type->get($property); + $value = $type->activeRecord()->get($property); if ($expected instanceof ArrayExpression) { $expected = $expected->getValue(); @@ -338,10 +338,10 @@ public function testArrayValues($properties): void /** Testing update */ foreach ($properties as $property => $expected) { - $type->markPropertyChanged($property); + $type->activeRecord()->markPropertyChanged($property); } - $this->assertSame(1, $type->update(), 'The record got updated'); + $this->assertSame(1, $type->activeRecord()->update(), 'The record got updated'); } public function testRelationViaArray(): void @@ -360,7 +360,7 @@ public function testRelationViaArray(): void /** Test inverse relation */ foreach ($promotions as $promotion) { foreach ($promotion->getItemsViaArray() as $item) { - $this->assertTrue($item->isRelationPopulated('promotionsViaArray')); + $this->assertTrue($item->activeRecord()->isRelationPopulated('promotionsViaArray')); } } @@ -381,11 +381,11 @@ public function testLazzyRelationViaArray(): void /** @var Item[] $items */ $items = $itemQuery->all(); - $this->assertFalse($items[0]->isRelationPopulated('promotionsViaArray')); - $this->assertFalse($items[1]->isRelationPopulated('promotionsViaArray')); - $this->assertFalse($items[2]->isRelationPopulated('promotionsViaArray')); - $this->assertFalse($items[3]->isRelationPopulated('promotionsViaArray')); - $this->assertFalse($items[4]->isRelationPopulated('promotionsViaArray')); + $this->assertFalse($items[0]->activeRecord()->isRelationPopulated('promotionsViaArray')); + $this->assertFalse($items[1]->activeRecord()->isRelationPopulated('promotionsViaArray')); + $this->assertFalse($items[2]->activeRecord()->isRelationPopulated('promotionsViaArray')); + $this->assertFalse($items[3]->activeRecord()->isRelationPopulated('promotionsViaArray')); + $this->assertFalse($items[4]->activeRecord()->isRelationPopulated('promotionsViaArray')); $this->assertSame([1, 3], ArArrayHelper::getColumn($items[0]->getPromotionsViaArray(), 'id')); $this->assertSame([1], ArArrayHelper::getColumn($items[1]->getPromotionsViaArray(), 'id')); diff --git a/tests/Driver/Pgsql/MagicActiveRecordTest.php b/tests/Driver/Pgsql/MagicActiveRecordTest.php index 90e3ac3f9..aee377a30 100644 --- a/tests/Driver/Pgsql/MagicActiveRecordTest.php +++ b/tests/Driver/Pgsql/MagicActiveRecordTest.php @@ -34,11 +34,11 @@ public function testExplicitPkOnAutoIncrement(): void $customer->email = 'user1337@example.com'; $customer->name = 'user1337'; $customer->address = 'address1337'; - $this->assertTrue($customer->isNewRecord); + $this->assertTrue($customer->activeRecord()->isNewRecord()); - $customer->save(); + $customer->activeRecord()->save(); $this->assertEquals(1337, $customer->id); - $this->assertFalse($customer->isNewRecord); + $this->assertFalse($customer->activeRecord()->isNewRecord()); } /** @@ -72,15 +72,15 @@ public function testBooleanProperty(): void $customer->name = 'boolean customer'; $customer->email = 'mail@example.com'; $customer->bool_status = false; - $customer->save(); + $customer->activeRecord()->save(); - $customer->refresh(); + $customer->activeRecord()->refresh(); $this->assertFalse($customer->bool_status); $customer->bool_status = true; - $customer->save(); - $customer->refresh(); + $customer->activeRecord()->save(); + $customer->activeRecord()->refresh(); $this->assertTrue($customer->bool_status); $customerQuery = new ActiveQuery(Customer::class); @@ -148,7 +148,7 @@ public function testBooleanValues2(): void $user->email = 'test@example.com'; $user->created_at = time(); $user->updated_at = time(); - $user->save(); + $user->activeRecord()->save(); $userQuery = new ActiveQuery(UserAR::class); $this->assertCount(1, $userQuery->where(['is_deleted' => false])->all()); @@ -166,12 +166,12 @@ public function testBooleanDefaultValues(): void $this->assertNull($arClass->default_true); $this->assertNull($arClass->default_false); - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertNull($arClass->bool_col); $this->assertTrue($arClass->default_true); $this->assertFalse($arClass->default_false); - $this->assertTrue($arClass->save()); + $this->assertTrue($arClass->activeRecord()->save()); } public function testPrimaryKeyAfterSave(): void @@ -182,9 +182,10 @@ public function testPrimaryKeyAfterSave(): void $record->type = 'type'; - $record->save(); + $record->activeRecord()->save(); - $this->assertEquals(5, $record->primaryKey); + $this->assertEquals(5, $record->id); + $this->assertEquals(5, $record->activeRecord()->getPrimaryKey()); } public static function arrayValuesProvider(): array @@ -270,7 +271,7 @@ public function testArrayValues($properties): void $type->$property = $expected[0]; } - $type->save(); + $type->activeRecord()->save(); $typeQuery = new ActiveQuery($type::class); @@ -289,9 +290,9 @@ public function testArrayValues($properties): void /** Testing update */ foreach ($properties as $property => $expected) { - $type->markPropertyChanged($property); + $type->activeRecord()->markPropertyChanged($property); } - $this->assertSame(1, $type->update(), 'The record got updated'); + $this->assertSame(1, $type->activeRecord()->update(), 'The record got updated'); } } diff --git a/tests/Driver/Pgsql/Stubs/Item.php b/tests/Driver/Pgsql/Stubs/Item.php index 07be93d07..5c7a2a1d9 100644 --- a/tests/Driver/Pgsql/Stubs/Item.php +++ b/tests/Driver/Pgsql/Stubs/Item.php @@ -14,7 +14,7 @@ final class Item extends \Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Item public function relationQuery(string $name): ActiveQueryInterface { return match ($name) { - 'promotionsViaArray' => $this->hasMany(Promotion::class, ['array_item_ids' => 'id']), + 'promotionsViaArray' => $this->activeRecord()->hasMany(Promotion::class, ['array_item_ids' => 'id']), default => parent::relationQuery($name), }; } @@ -22,6 +22,6 @@ public function relationQuery(string $name): ActiveQueryInterface /** @return Promotion[] */ public function getPromotionsViaArray(): array { - return $this->relation('promotionsViaArray'); + return $this->activeRecord()->relation('promotionsViaArray'); } } diff --git a/tests/Driver/Pgsql/Stubs/Promotion.php b/tests/Driver/Pgsql/Stubs/Promotion.php index 2b447babb..323afd055 100644 --- a/tests/Driver/Pgsql/Stubs/Promotion.php +++ b/tests/Driver/Pgsql/Stubs/Promotion.php @@ -16,7 +16,7 @@ public function getTableName(): string public function relationQuery(string $name): ActiveQueryInterface { return match ($name) { - 'itemsViaArray' => $this->hasMany(Item::class, ['id' => 'array_item_ids']) + 'itemsViaArray' => $this->activeRecord()->hasMany(Item::class, ['id' => 'array_item_ids']) ->inverseOf('promotionsViaArray'), default => parent::relationQuery($name), }; @@ -25,6 +25,6 @@ public function relationQuery(string $name): ActiveQueryInterface /** @return Item[] */ public function getItemsViaArray(): array { - return $this->relation('itemsViaArray'); + return $this->activeRecord()->relation('itemsViaArray'); } } diff --git a/tests/Driver/Sqlite/ActiveRecordTest.php b/tests/Driver/Sqlite/ActiveRecordTest.php index d47fc396a..bc4d80802 100644 --- a/tests/Driver/Sqlite/ActiveRecordTest.php +++ b/tests/Driver/Sqlite/ActiveRecordTest.php @@ -34,11 +34,11 @@ public function testExplicitPkOnAutoIncrement(): void $customer->setName('user1337'); $customer->setAddress('address1337'); - $this->assertTrue($customer->getIsNewRecord()); - $customer->save(); + $this->assertTrue($customer->activeRecord()->isNewRecord()); + $customer->activeRecord()->save(); $this->assertEquals(1337, $customer->getId()); - $this->assertFalse($customer->getIsNewRecord()); + $this->assertFalse($customer->activeRecord()->isNewRecord()); } /** diff --git a/tests/Driver/Sqlite/MagicActiveRecordTest.php b/tests/Driver/Sqlite/MagicActiveRecordTest.php index a198cda0c..7ce9370f3 100644 --- a/tests/Driver/Sqlite/MagicActiveRecordTest.php +++ b/tests/Driver/Sqlite/MagicActiveRecordTest.php @@ -28,11 +28,11 @@ public function testExplicitPkOnAutoIncrement(): void $customer->name = 'user1337'; $customer->address = 'address1337'; - $this->assertTrue($customer->isNewRecord); - $customer->save(); + $this->assertTrue($customer->activeRecord()->isNewRecord()); + $customer->activeRecord()->save(); $this->assertEquals(1337, $customer->id); - $this->assertFalse($customer->isNewRecord); + $this->assertFalse($customer->activeRecord()->isNewRecord()); } /** diff --git a/tests/MagicActiveRecordTest.php b/tests/MagicActiveRecordTest.php index 23167fb91..c5707cfd8 100644 --- a/tests/MagicActiveRecordTest.php +++ b/tests/MagicActiveRecordTest.php @@ -39,46 +39,46 @@ public function testStoreNull(): void $record = new NullValues(); - $this->assertNull($record->get('var1')); - $this->assertNull($record->get('var2')); - $this->assertNull($record->get('var3')); - $this->assertNull($record->get('stringcol')); - - $record->set('var1', 123); - $record->set('var2', 456); - $record->set('var3', 789); - $record->set('stringcol', 'hello!'); - $record->save(); - - $this->assertTrue($record->refresh()); - $this->assertEquals(123, $record->get('var1')); - $this->assertEquals(456, $record->get('var2')); - $this->assertEquals(789, $record->get('var3')); - $this->assertEquals('hello!', $record->get('stringcol')); - - $record->set('var1', null); - $record->set('var2', null); - $record->set('var3', null); - $record->set('stringcol', null); - $record->save(); - - $this->assertTrue($record->refresh()); - $this->assertNull($record->get('var1')); - $this->assertNull($record->get('var2')); - $this->assertNull($record->get('var3')); - $this->assertNull($record->get('>stringcol')); - - $record->set('var1', 0); - $record->set('var2', 0); - $record->set('var3', 0); - $record->set('stringcol', ''); - $record->save(); - - $this->assertTrue($record->refresh()); - $this->assertEquals(0, $record->get('var1')); - $this->assertEquals(0, $record->get('var2')); - $this->assertEquals(0, $record->get('var3')); - $this->assertEquals('', $record->get('stringcol')); + $this->assertNull($record->activeRecord()->get('var1')); + $this->assertNull($record->activeRecord()->get('var2')); + $this->assertNull($record->activeRecord()->get('var3')); + $this->assertNull($record->activeRecord()->get('stringcol')); + + $record->activeRecord()->set('var1', 123); + $record->activeRecord()->set('var2', 456); + $record->activeRecord()->set('var3', 789); + $record->activeRecord()->set('stringcol', 'hello!'); + $record->activeRecord()->save(); + + $this->assertTrue($record->activeRecord()->refresh()); + $this->assertEquals(123, $record->activeRecord()->get('var1')); + $this->assertEquals(456, $record->activeRecord()->get('var2')); + $this->assertEquals(789, $record->activeRecord()->get('var3')); + $this->assertEquals('hello!', $record->activeRecord()->get('stringcol')); + + $record->activeRecord()->set('var1', null); + $record->activeRecord()->set('var2', null); + $record->activeRecord()->set('var3', null); + $record->activeRecord()->set('stringcol', null); + $record->activeRecord()->save(); + + $this->assertTrue($record->activeRecord()->refresh()); + $this->assertNull($record->activeRecord()->get('var1')); + $this->assertNull($record->activeRecord()->get('var2')); + $this->assertNull($record->activeRecord()->get('var3')); + $this->assertNull($record->activeRecord()->get('>stringcol')); + + $record->activeRecord()->set('var1', 0); + $record->activeRecord()->set('var2', 0); + $record->activeRecord()->set('var3', 0); + $record->activeRecord()->set('stringcol', ''); + $record->activeRecord()->save(); + + $this->assertTrue($record->activeRecord()->refresh()); + $this->assertEquals(0, $record->activeRecord()->get('var1')); + $this->assertEquals(0, $record->activeRecord()->get('var2')); + $this->assertEquals(0, $record->activeRecord()->get('var3')); + $this->assertEquals('', $record->activeRecord()->get('stringcol')); } public function testStoreEmpty(): void @@ -92,9 +92,9 @@ public function testStoreEmpty(): void $record->var2 = ''; $record->var3 = ''; $record->stringcol = ''; - $record->save(); + $record->activeRecord()->save(); - $this->assertTrue($record->refresh()); + $this->assertTrue($record->activeRecord()->refresh()); /** {@see https://github.com/yiisoft/yii2/commit/34945b0b69011bc7cab684c7f7095d837892a0d4#commitcomment-4458225} */ $this->assertSame($record->var1, $record->var2); @@ -108,19 +108,19 @@ public function testIsPrimaryKey(): void $customer = new Customer(); $orderItem = new OrderItem(); - $this->assertTrue($customer->isPrimaryKey(['id'])); - $this->assertFalse($customer->isPrimaryKey([])); - $this->assertFalse($customer->isPrimaryKey(['id', 'name'])); - $this->assertFalse($customer->isPrimaryKey(['name'])); - $this->assertFalse($customer->isPrimaryKey(['name', 'email'])); + $this->assertTrue($customer->activeRecord()->isPrimaryKey(['id'])); + $this->assertFalse($customer->activeRecord()->isPrimaryKey([])); + $this->assertFalse($customer->activeRecord()->isPrimaryKey(['id', 'name'])); + $this->assertFalse($customer->activeRecord()->isPrimaryKey(['name'])); + $this->assertFalse($customer->activeRecord()->isPrimaryKey(['name', 'email'])); - $this->assertTrue($orderItem->isPrimaryKey(['order_id', 'item_id'])); - $this->assertFalse($orderItem->isPrimaryKey([])); - $this->assertFalse($orderItem->isPrimaryKey(['order_id'])); - $this->assertFalse($orderItem->isPrimaryKey(['item_id'])); - $this->assertFalse($orderItem->isPrimaryKey(['quantity'])); - $this->assertFalse($orderItem->isPrimaryKey(['quantity', 'subtotal'])); - $this->assertFalse($orderItem->isPrimaryKey(['order_id', 'item_id', 'quantity'])); + $this->assertTrue($orderItem->activeRecord()->isPrimaryKey(['order_id', 'item_id'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey([])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['order_id'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['item_id'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['quantity'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['quantity', 'subtotal'])); + $this->assertFalse($orderItem->activeRecord()->isPrimaryKey(['order_id', 'item_id', 'quantity'])); } public function testOutdatedRelationsAreResetForNewRecords(): void @@ -141,8 +141,8 @@ public function testOutdatedRelationsAreResetForNewRecords(): void $this->assertEquals(1, $orderItem->item->id); /** test `set()`. */ - $orderItem->set('order_id', 2); - $orderItem->set('item_id', 2); + $orderItem->activeRecord()->set('order_id', 2); + $orderItem->activeRecord()->set('item_id', 2); $this->assertEquals(2, $orderItem->order->id); $this->assertEquals(2, $orderItem->item->id); } @@ -153,7 +153,7 @@ public function testDefaultValues(): void $arClass = new Type(); - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertEquals(1, $arClass->int_col2); $this->assertEquals('something', $arClass->char_col2); @@ -169,13 +169,13 @@ public function testDefaultValues(): void $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(); + $arClass->activeRecord()->loadDefaultValues(); $this->assertEquals('not something', $arClass->char_col2); $arClass = new Type(); $arClass->char_col2 = 'not something'; - $arClass->loadDefaultValues(false); + $arClass->activeRecord()->loadDefaultValues(false); $this->assertEquals('something', $arClass->char_col2); } @@ -185,7 +185,7 @@ public function testCastValues(): void $arClass = new Type(); - $arClass->deleteAll(); + $arClass->activeRecord()->deleteAll(); $arClass->int_col = 123; $arClass->int_col2 = 456; @@ -199,7 +199,7 @@ public function testCastValues(): void $arClass->bool_col2 = false; $arClass->json_col = ['a' => 'b', 'c' => null, 'd' => [1, 2, 3]]; - $arClass->save(); + $arClass->activeRecord()->save(); /** @var $model Type */ $aqClass = new ActiveQuery(Type::class); @@ -223,10 +223,10 @@ public function testPopulateRecordCallWhenQueryingOnParentClass(): void $this->checkFixture($this->db(), 'cat'); $cat = new Cat(); - $cat->save(); + $cat->activeRecord()->save(); $dog = new Dog(); - $dog->save(); + $dog->activeRecord()->save(); $animal = (new ActiveQuery(Animal::class))->resultCallback(ModelFactory::create(...)); @@ -243,7 +243,7 @@ public function testSaveEmpty(): void $record = new NullValues(); - $this->assertTrue($record->save()); + $this->assertTrue($record->activeRecord()->save()); $this->assertEquals(1, $record->id); } @@ -259,15 +259,15 @@ public function testNoTablenameReplacement(): void $customer->name = 'Some {{weird}} name'; $customer->email = 'test@example.com'; $customer->address = 'Some {{%weird}} address'; - $customer->insert(); - $customer->refresh(); + $customer->activeRecord()->insert(); + $customer->activeRecord()->refresh(); $this->assertEquals('Some {{weird}} name', $customer->name); $this->assertEquals('Some {{%weird}} address', $customer->address); $customer->name = 'Some {{updated}} name'; $customer->address = 'Some {{%updated}} address'; - $customer->update(); + $customer->activeRecord()->update(); $this->assertEquals('Some {{updated}} name', $customer->name); $this->assertEquals('Some {{%updated}} address', $customer->address); @@ -375,7 +375,7 @@ public function testRefreshQuerySetAliasFindRecord(): void $customer = new CustomerWithAlias(); $customer->id = 1; - $customer->refresh(); + $customer->activeRecord()->refresh(); $this->assertEquals(1, $customer->id); } @@ -394,9 +394,9 @@ public function testResetNotSavedRelation(): void $order->orderItems; - $order->populateRelation('orderItems', [$orderItem]); + $order->activeRecord()->populateRelation('orderItems', [$orderItem]); - $order->save(); + $order->activeRecord()->save(); $this->assertCount(1, $order->orderItems); } @@ -450,9 +450,9 @@ public function testAssignProperties(): void $customer = new Customer(); - $customer->populateProperties($properties); + $customer->activeRecord()->populateProperties($properties); - $this->assertTrue($customer->save()); + $this->assertTrue($customer->activeRecord()->save()); } public function testSetNoExistProperty(): void @@ -466,7 +466,7 @@ public function testSetNoExistProperty(): void 'Yiisoft\ActiveRecord\Tests\Stubs\MagicActiveRecord\Cat has no property named "noExist"' ); - $cat->set('noExist', 1); + $cat->activeRecord()->set('noExist', 1); } public function testAssignOldValue(): void @@ -475,11 +475,11 @@ public function testAssignOldValue(): void $customer = new Customer(); - $this->assertEmpty($customer->oldValue('name')); + $this->assertEmpty($customer->activeRecord()->oldValue('name')); - $customer->assignOldValue('name', 'samdark'); + $customer->activeRecord()->assignOldValue('name', 'samdark'); - $this->assertEquals('samdark', $customer->oldValue('name')); + $this->assertEquals('samdark', $customer->activeRecord()->oldValue('name')); } public function testAssignOldValueException(): void @@ -488,13 +488,13 @@ public function testAssignOldValueException(): void $customer = new Customer(); - $this->assertEmpty($customer->oldValue('name')); + $this->assertEmpty($customer->activeRecord()->oldValue('name')); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Yiisoft\ActiveRecord\Tests\Stubs\MagicActiveRecord\Customer has no property named "noExist"' ); - $customer->assignOldValue('noExist', 'samdark'); + $customer->activeRecord()->assignOldValue('noExist', 'samdark'); } public function testIsPropertyChangedNotChanged(): void @@ -503,10 +503,10 @@ public function testIsPropertyChangedNotChanged(): void $customer = new Customer(); - $this->assertEmpty($customer->get('name')); - $this->assertEmpty($customer->oldValue('name')); - $this->assertFalse($customer->isPropertyChanged('name')); - $this->assertFalse($customer->isPropertyChangedNonStrict('name')); + $this->assertEmpty($customer->activeRecord()->get('name')); + $this->assertEmpty($customer->activeRecord()->oldValue('name')); + $this->assertFalse($customer->activeRecord()->isPropertyChanged('name')); + $this->assertFalse($customer->activeRecord()->isPropertyChangedNonStrict('name')); } public function testTableSchemaException(): void @@ -515,7 +515,8 @@ public function testTableSchemaException(): void $this->expectException(InvalidConfigException::class); $this->expectExceptionMessage('The table does not exist: NoExist'); - $noExist->getTableSchema(); + + $noExist->activeRecord()->getTableSchema(); } public function testInsert(): void @@ -529,12 +530,12 @@ public function testInsert(): void $customer->address = 'address4'; $this->assertNull($customer->id); - $this->assertTrue($customer->isNewRecord); + $this->assertTrue($customer->activeRecord()->isNewRecord()); - $customer->save(); + $customer->activeRecord()->save(); $this->assertNotNull($customer->id); - $this->assertFalse($customer->isNewRecord); + $this->assertFalse($customer->activeRecord()->isNewRecord()); } /** @@ -552,14 +553,14 @@ public function testBooleanProperty(): void $customer->email = 'mail@example.com'; $customer->bool_status = true; - $customer->save(); - $customer->refresh(); + $customer->activeRecord()->save(); + $customer->activeRecord()->refresh(); $this->assertTrue($customer->bool_status); $customer->bool_status = false; - $customer->save(); + $customer->activeRecord()->save(); - $customer->refresh(); + $customer->activeRecord()->refresh(); $this->assertFalse($customer->bool_status); $customerQuery = new ActiveQuery(Customer::class); @@ -590,7 +591,7 @@ public function testPropertyAccess(): void /** {@see https://github.com/yiisoft/yii2-gii/issues/190} */ $baseModel = new Customer(); - $this->assertFalse($baseModel->hasProperty('unExistingColumn')); + $this->assertFalse($baseModel->activeRecord()->hasProperty('unExistingColumn')); $customer = new Customer(); $this->assertInstanceOf(Customer::class, $customer); @@ -633,15 +634,15 @@ public function testHasProperty(): void $customer = new Customer(); - $this->assertTrue($customer->hasProperty('id')); - $this->assertTrue($customer->hasProperty('email')); - $this->assertFalse($customer->hasProperty('notExist')); + $this->assertTrue($customer->activeRecord()->hasProperty('id')); + $this->assertTrue($customer->activeRecord()->hasProperty('email')); + $this->assertFalse($customer->activeRecord()->hasProperty('notExist')); $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); - $this->assertTrue($customer->hasProperty('id')); - $this->assertTrue($customer->hasProperty('email')); - $this->assertFalse($customer->hasProperty('notExist')); + $this->assertTrue($customer->activeRecord()->hasProperty('id')); + $this->assertTrue($customer->activeRecord()->hasProperty('email')); + $this->assertFalse($customer->activeRecord()->hasProperty('notExist')); } public function testRefresh(): void @@ -650,13 +651,13 @@ public function testRefresh(): void $customer = new Customer(); - $this->assertFalse($customer->refresh()); + $this->assertFalse($customer->activeRecord()->refresh()); $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); $customer->name = 'to be refreshed'; - $this->assertTrue($customer->refresh()); + $this->assertTrue($customer->activeRecord()->refresh()); $this->assertEquals('user1', $customer->name); } @@ -666,11 +667,11 @@ public function testEquals(): void $customerA = new Customer(); $customerB = new Customer(); - $this->assertFalse($customerA->equals($customerB)); + $this->assertFalse($customerA->activeRecord()->equals($customerB)); $customerA = new Customer(); $customerB = new Item(); - $this->assertFalse($customerA->equals($customerB)); + $this->assertFalse($customerA->activeRecord()->equals($customerB)); } public static function providerForUnlinkDelete(): array @@ -695,7 +696,7 @@ public function testUnlinkWithViaOnCondition($delete, $count): void $order = $orderQuery->findOne(2); $this->assertCount(1, $order->itemsFor8); - $order->unlink('itemsFor8', $order->itemsFor8[0], $delete); + $order->activeRecord()->unlink('itemsFor8', $order->itemsFor8[0], $delete); $order = $orderQuery->findOne(2); $this->assertCount(0, $order->itemsFor8); @@ -758,7 +759,7 @@ public function testSaveWithoutChanges(): void $customer = $customerQuery->findOne(1); - $this->assertTrue($customer->save()); + $this->assertTrue($customer->activeRecord()->save()); } public function testGetPrimaryKey(): void @@ -769,8 +770,8 @@ public function testGetPrimaryKey(): void $customer = $customerQuery->findOne(1); - $this->assertSame(1, $customer->getPrimaryKey()); - $this->assertSame(['id' => 1], $customer->getPrimaryKey(true)); + $this->assertSame(1, $customer->activeRecord()->getPrimaryKey()); + $this->assertSame(['id' => 1], $customer->activeRecord()->getPrimaryKey(true)); } public function testGetOldPrimaryKey(): void @@ -782,8 +783,8 @@ public function testGetOldPrimaryKey(): void $customer = $customerQuery->findOne(1); $customer->id = 2; - $this->assertSame(1, $customer->getOldPrimaryKey()); - $this->assertSame(['id' => 1], $customer->getOldPrimaryKey(true)); + $this->assertSame(1, $customer->activeRecord()->getOldPrimaryKey()); + $this->assertSame(['id' => 1], $customer->activeRecord()->getOldPrimaryKey(true)); } public function testGetDirtyValuesOnNewRecord(): void @@ -792,27 +793,27 @@ public function testGetDirtyValuesOnNewRecord(): void $customer = new Customer(); - $this->assertSame([], $customer->newValues()); + $this->assertSame([], $customer->activeRecord()->newValues()); - $customer->set('name', 'Adam'); - $customer->set('email', 'adam@example.com'); - $customer->set('address', null); + $customer->activeRecord()->set('name', 'Adam'); + $customer->activeRecord()->set('email', 'adam@example.com'); + $customer->activeRecord()->set('address', null); $this->assertEquals( ['name' => 'Adam', 'email' => 'adam@example.com', 'address' => null], - $customer->newValues() + $customer->activeRecord()->newValues() ); $this->assertEquals( ['email' => 'adam@example.com', 'address' => null], - $customer->newValues(['id', 'email', 'address', 'status', 'unknown']), + $customer->activeRecord()->newValues(['id', 'email', 'address', 'status', 'unknown']), ); - $this->assertTrue($customer->save()); - $this->assertSame([], $customer->newValues()); + $this->assertTrue($customer->activeRecord()->save()); + $this->assertSame([], $customer->activeRecord()->newValues()); - $customer->set('address', ''); + $customer->activeRecord()->set('address', ''); - $this->assertSame(['address' => ''], $customer->newValues()); + $this->assertSame(['address' => ''], $customer->activeRecord()->newValues()); } public function testGetDirtyValuesAfterFind(): void @@ -822,19 +823,19 @@ public function testGetDirtyValuesAfterFind(): void $customerQuery = new ActiveQuery(Customer::class); $customer = $customerQuery->findOne(1); - $this->assertSame([], $customer->newValues()); + $this->assertSame([], $customer->activeRecord()->newValues()); - $customer->set('name', 'Adam'); - $customer->set('email', 'adam@example.com'); - $customer->set('address', null); + $customer->activeRecord()->set('name', 'Adam'); + $customer->activeRecord()->set('email', 'adam@example.com'); + $customer->activeRecord()->set('address', null); $this->assertEquals( ['name' => 'Adam', 'email' => 'adam@example.com', 'address' => null], - $customer->newValues(), + $customer->activeRecord()->newValues(), ); $this->assertEquals( ['email' => 'adam@example.com', 'address' => null], - $customer->newValues(['id', 'email', 'address', 'status', 'unknown']), + $customer->activeRecord()->newValues(['id', 'email', 'address', 'status', 'unknown']), ); } @@ -846,12 +847,12 @@ public function testGetDirtyValuesWithProperties(): void $this->assertSame([ 'name' => null, 'address' => null, - ], $customer->newValues()); + ], $customer->activeRecord()->newValues()); $customerQuery = new ActiveQuery(CustomerWithProperties::class); $customer = $customerQuery->findOne(1); - $this->assertSame([], $customer->newValues()); + $this->assertSame([], $customer->activeRecord()->newValues()); $customer->setEmail('adam@example.com'); $customer->setName('Adam'); @@ -860,11 +861,11 @@ public function testGetDirtyValuesWithProperties(): void $this->assertEquals( ['email' => 'adam@example.com', 'name' => 'Adam', 'address' => null, 'status' => null], - $customer->newValues(), + $customer->activeRecord()->newValues(), ); $this->assertEquals( ['email' => 'adam@example.com', 'address' => null], - $customer->newValues(['id', 'email', 'address', 'unknown']), + $customer->activeRecord()->newValues(['id', 'email', 'address', 'unknown']), ); } @@ -907,7 +908,7 @@ public function testGetSetMethodsPriority(): void $order = new Order(); $order->created_at = $datetime; - $this->assertSame(1_325_502_201, $order->get('created_at')); + $this->assertSame(1_325_502_201, $order->activeRecord()->get('created_at')); $this->assertEquals($datetime, $order->created_at); } @@ -918,18 +919,18 @@ public function testIsChanged(): void $itemQuery = new ActiveQuery(Item::class); $item = $itemQuery->findOne(1); - $this->assertFalse($item->isChanged()); + $this->assertFalse($item->activeRecord()->isChanged()); - $item->set('name', 'New name'); + $item->activeRecord()->set('name', 'New name'); - $this->assertTrue($item->isChanged()); + $this->assertTrue($item->activeRecord()->isChanged()); $newItem = new Item(); - $this->assertFalse($newItem->isChanged()); + $this->assertFalse($newItem->activeRecord()->isChanged()); - $newItem->set('name', 'New name'); + $newItem->activeRecord()->set('name', 'New name'); - $this->assertTrue($newItem->isChanged()); + $this->assertTrue($newItem->activeRecord()->isChanged()); } } diff --git a/tests/Stubs/ActiveRecord/Alpha.php b/tests/Stubs/ActiveRecord/Alpha.php index ba7ac208b..d81405053 100644 --- a/tests/Stubs/ActiveRecord/Alpha.php +++ b/tests/Stubs/ActiveRecord/Alpha.php @@ -6,9 +6,9 @@ use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; -final class Alpha extends ActiveRecord +final class Alpha extends ActiveRecordModel { public const TABLE_NAME = 'alpha'; @@ -16,7 +16,7 @@ final class Alpha extends ActiveRecord protected string $string_identifier; - public function getTableName(): string + public function tableName(): string { return self::TABLE_NAME; } @@ -41,11 +41,11 @@ public function relationQuery(string $name): ActiveQueryInterface public function getBetas(): array|null { - return $this->relation('betas'); + return $this->activeRecord()->relation('betas'); } public function getBetasQuery(): ActiveQuery { - return $this->hasMany(Beta::class, ['alpha_string_identifier' => 'string_identifier']); + return $this->activeRecord()->hasMany(Beta::class, ['alpha_string_identifier' => 'string_identifier']); } } diff --git a/tests/Stubs/ActiveRecord/Animal.php b/tests/Stubs/ActiveRecord/Animal.php index b5e5e1e4a..e6e458096 100644 --- a/tests/Stubs/ActiveRecord/Animal.php +++ b/tests/Stubs/ActiveRecord/Animal.php @@ -4,19 +4,19 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class Animal. */ -class Animal extends ActiveRecord +class Animal extends ActiveRecordModel { private string $does; protected int $id; protected string $type; - public function getTableName(): string + public function tableName(): string { return 'animal'; } diff --git a/tests/Stubs/ActiveRecord/ArrayAndJsonTypes.php b/tests/Stubs/ActiveRecord/ArrayAndJsonTypes.php index be17258c4..08e4c775f 100644 --- a/tests/Stubs/ActiveRecord/ArrayAndJsonTypes.php +++ b/tests/Stubs/ActiveRecord/ArrayAndJsonTypes.php @@ -4,12 +4,12 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; use Yiisoft\Db\Expression\ArrayExpression; use Yiisoft\Db\Expression\Expression; use Yiisoft\Db\Expression\JsonExpression; -final class ArrayAndJsonTypes extends ActiveRecord +final class ArrayAndJsonTypes extends ActiveRecordModel { public int $id; public array|ArrayExpression|null $intarray_col = null; diff --git a/tests/Stubs/ActiveRecord/Beta.php b/tests/Stubs/ActiveRecord/Beta.php index 9e7a9cde2..f93ee413a 100644 --- a/tests/Stubs/ActiveRecord/Beta.php +++ b/tests/Stubs/ActiveRecord/Beta.php @@ -6,15 +6,15 @@ use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; -final class Beta extends ActiveRecord +final class Beta extends ActiveRecordModel { protected int $id; protected string $alpha_string_identifier; protected Alpha $alpha; - public function getTableName(): string + public function tableName(): string { return 'beta'; } @@ -39,11 +39,11 @@ public function relationQuery(string $name): ActiveQueryInterface public function getAlpha(): Alpha|null { - return $this->relation('alpha'); + return $this->activeRecord()->relation('alpha'); } public function getAlphaQuery(): ActiveQuery { - return $this->hasOne(Alpha::class, ['string_identifier' => 'alpha_string_identifier']); + return $this->activeRecord()->hasOne(Alpha::class, ['string_identifier' => 'alpha_string_identifier']); } } diff --git a/tests/Stubs/ActiveRecord/BitValues.php b/tests/Stubs/ActiveRecord/BitValues.php index 7d61c2c66..26761fd2d 100644 --- a/tests/Stubs/ActiveRecord/BitValues.php +++ b/tests/Stubs/ActiveRecord/BitValues.php @@ -4,12 +4,12 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * {@see https://github.com/yiisoft/yii2/issues/9006} */ -final class BitValues extends ActiveRecord +final class BitValues extends ActiveRecordModel { public int $id; public bool|int $val; diff --git a/tests/Stubs/ActiveRecord/BoolAR.php b/tests/Stubs/ActiveRecord/BoolAR.php index 058f6bd1c..4ab6d1cb2 100644 --- a/tests/Stubs/ActiveRecord/BoolAR.php +++ b/tests/Stubs/ActiveRecord/BoolAR.php @@ -4,16 +4,16 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; -final class BoolAR extends ActiveRecord +final class BoolAR extends ActiveRecordModel { public int $id; public bool|null $bool_col = null; public bool $default_true = true; public bool $default_false = false; - public function getTableName(): string + public function tableName(): string { return 'bool_values'; } diff --git a/tests/Stubs/ActiveRecord/Cat.php b/tests/Stubs/ActiveRecord/Cat.php index 97ff4cf28..7239f1115 100644 --- a/tests/Stubs/ActiveRecord/Cat.php +++ b/tests/Stubs/ActiveRecord/Cat.php @@ -8,10 +8,8 @@ final class Cat extends Animal { - public function populateRecord($row): void + public function initialize(): void { - parent::populateRecord($row); - $this->setDoes('meow'); } diff --git a/tests/Stubs/ActiveRecord/Category.php b/tests/Stubs/ActiveRecord/Category.php index 382f94556..294d1cb20 100644 --- a/tests/Stubs/ActiveRecord/Category.php +++ b/tests/Stubs/ActiveRecord/Category.php @@ -6,17 +6,17 @@ use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class Category. */ -final class Category extends ActiveRecord +final class Category extends ActiveRecordModel { protected int|null $id; protected string $name; - public function getTableName(): string + public function tableName(): string { return 'category'; } @@ -44,46 +44,46 @@ public function getName(): string public function setId(int|null $id): void { - $this->set('id', $id); + $this->activeRecord()->set('id', $id); } public function getLimitedItems(): array { - return $this->relation('limitedItems'); + return $this->activeRecord()->relation('limitedItems'); } public function getLimitedItemsQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['category_id' => 'id'])->onCondition(['item.id' => [1, 2, 3]]); + return $this->activeRecord()->hasMany(Item::class, ['category_id' => 'id'])->onCondition(['item.id' => [1, 2, 3]]); } public function getItems(): array { - return $this->relation('items'); + return $this->activeRecord()->relation('items'); } public function getItemsQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['category_id' => 'id']); + return $this->activeRecord()->hasMany(Item::class, ['category_id' => 'id']); } public function getOrderItems(): array { - return $this->relation('orderItems'); + return $this->activeRecord()->relation('orderItems'); } public function getOrderItemsQuery(): ActiveQuery { - return $this->hasMany(OrderItem::class, ['item_id' => 'id'])->via('items'); + return $this->activeRecord()->hasMany(OrderItem::class, ['item_id' => 'id'])->via('items'); } public function getOrders(): array { - return $this->relation('orders'); + return $this->activeRecord()->relation('orders'); } public function getOrdersQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['id' => 'order_id'])->via('orderItems'); + return $this->activeRecord()->hasMany(Order::class, ['id' => 'order_id'])->via('orderItems'); } } diff --git a/tests/Stubs/ActiveRecord/Customer.php b/tests/Stubs/ActiveRecord/Customer.php index f002b7d1c..7a4394d78 100644 --- a/tests/Stubs/ActiveRecord/Customer.php +++ b/tests/Stubs/ActiveRecord/Customer.php @@ -33,7 +33,7 @@ class Customer extends ArrayableActiveRecord */ public $sumTotal; - public function getTableName(): string + public function tableName(): string { return 'customer'; } @@ -53,7 +53,7 @@ public function relationQuery(string $name): ActiveQueryInterface 'orderItems' => $this->getOrderItemsQuery(), 'orderItems2' => $this->getOrderItems2Query(), 'items2' => $this->getItems2Query(), - 'ordersUsingInstance' => $this->hasMany(new Order(), ['customer_id' => 'id']), + 'ordersUsingInstance' => $this->activeRecord()->hasMany(new Order(), ['customer_id' => 'id']), default => parent::relationQuery($name), }; } @@ -125,57 +125,57 @@ public function setBoolStatus(bool|null $bool_status): void public function setProfileId(int|null $profile_id): void { - $this->set('profile_id', $profile_id); + $this->activeRecord()->set('profile_id', $profile_id); } public function getProfile(): Profile|null { - return $this->relation('profile'); + return $this->activeRecord()->relation('profile'); } public function getProfileQuery(): ActiveQuery { - return $this->hasOne(Profile::class, ['id' => 'profile_id']); + return $this->activeRecord()->hasOne(Profile::class, ['id' => 'profile_id']); } public function getOrdersPlain(): array { - return $this->relation('ordersPlain'); + return $this->activeRecord()->relation('ordersPlain'); } public function getOrdersPlainQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id']); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id']); } public function getOrders(): array { - return $this->relation('orders'); + return $this->activeRecord()->relation('orders'); } public function getOrdersQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('[[id]]'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('[[id]]'); } public function getOrdersNoOrder(): array { - return $this->relation('ordersNoOrder'); + return $this->activeRecord()->relation('ordersNoOrder'); } public function getOrdersNoOrderQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id']); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id']); } public function getExpensiveOrders(): array { - return $this->relation('expensiveOrders'); + return $this->activeRecord()->relation('expensiveOrders'); } public function getExpensiveOrdersQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->andWhere('[[total]] > 50')->orderBy('id'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->andWhere('[[total]] > 50')->orderBy('id'); } public function getItem(): void @@ -184,22 +184,22 @@ public function getItem(): void public function getOrdersWithItems(): array { - return $this->relation('ordersWithItems'); + return $this->activeRecord()->relation('ordersWithItems'); } public function getOrdersWithItemsQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->with('orderItems'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->with('orderItems'); } public function getExpensiveOrdersWithNullFK(): array { - return $this->relation('expensiveOrdersWithNullFK'); + return $this->activeRecord()->relation('expensiveOrdersWithNullFK'); } public function getExpensiveOrdersWithNullFKQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( OrderWithNullFK::class, ['customer_id' => 'id'] )->andWhere('[[total]] > 50')->orderBy('id'); @@ -207,33 +207,33 @@ public function getExpensiveOrdersWithNullFKQuery(): ActiveQuery public function getOrdersWithNullFK(): array { - return $this->relation('ordersWithNullFK'); + return $this->activeRecord()->relation('ordersWithNullFK'); } public function getOrdersWithNullFKQuery(): ActiveQuery { - return $this->hasMany(OrderWithNullFK::class, ['customer_id' => 'id'])->orderBy('id'); + return $this->activeRecord()->hasMany(OrderWithNullFK::class, ['customer_id' => 'id'])->orderBy('id'); } public function getOrders2(): array { - return $this->relation('orders2'); + return $this->activeRecord()->relation('orders2'); } public function getOrders2Query(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer2')->orderBy('id'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer2')->orderBy('id'); } public function getOrderItems(): array { - return $this->relation('orderItems'); + return $this->activeRecord()->relation('orderItems'); } /** deeply nested table relation */ public function getOrderItemsQuery(): ActiveQuery { - $rel = $this->hasMany(Item::class, ['id' => 'item_id']); + $rel = $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id']); return $rel->viaTable('order_item', ['order_id' => 'id'], function ($q) { /* @var $q ActiveQuery */ @@ -243,28 +243,28 @@ public function getOrderItemsQuery(): ActiveQuery public function getOrderItems2(): array { - return $this->relation('orderItems2'); + return $this->activeRecord()->relation('orderItems2'); } public function getOrderItems2Query(): ActiveQuery { - return $this->hasMany(OrderItem::class, ['order_id' => 'id']) + return $this->activeRecord()->hasMany(OrderItem::class, ['order_id' => 'id']) ->via('ordersNoOrder'); } public function getItems2(): array { - return $this->relation('items2'); + return $this->activeRecord()->relation('items2'); } public function getItems2Query(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id']) + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id']) ->via('orderItems2'); } public function getOrdersUsingInstance(): array { - return $this->relation('ordersUsingInstance'); + return $this->activeRecord()->relation('ordersUsingInstance'); } } diff --git a/tests/Stubs/ActiveRecord/CustomerClosureField.php b/tests/Stubs/ActiveRecord/CustomerClosureField.php index 69346fb93..977da7e51 100644 --- a/tests/Stubs/ActiveRecord/CustomerClosureField.php +++ b/tests/Stubs/ActiveRecord/CustomerClosureField.php @@ -19,7 +19,7 @@ final class CustomerClosureField extends ArrayableActiveRecord protected bool|string|null $bool_status = false; protected int|null $profile_id = null; - public function getTableName(): string + public function tableName(): string { return 'customer'; } diff --git a/tests/Stubs/ActiveRecord/CustomerForArrayable.php b/tests/Stubs/ActiveRecord/CustomerForArrayable.php index fb2bfb2df..d680e5873 100644 --- a/tests/Stubs/ActiveRecord/CustomerForArrayable.php +++ b/tests/Stubs/ActiveRecord/CustomerForArrayable.php @@ -23,7 +23,7 @@ class CustomerForArrayable extends ArrayableActiveRecord protected bool|string|null $bool_status = false; protected int|null $profile_id = null; - public function getTableName(): string + public function tableName(): string { return 'customer'; } diff --git a/tests/Stubs/ActiveRecord/CustomerWithAlias.php b/tests/Stubs/ActiveRecord/CustomerWithAlias.php index b5b7aab7a..5d48a4be6 100644 --- a/tests/Stubs/ActiveRecord/CustomerWithAlias.php +++ b/tests/Stubs/ActiveRecord/CustomerWithAlias.php @@ -4,12 +4,12 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class Customer. */ -final class CustomerWithAlias extends ActiveRecord +final class CustomerWithAlias extends ActiveRecordModel { public const STATUS_ACTIVE = 1; public const STATUS_INACTIVE = 2; @@ -25,7 +25,7 @@ final class CustomerWithAlias extends ActiveRecord public bool|string|null $bool_status = null; public int|null $profile_id = null; - public function getTableName(): string + public function tableName(): string { return 'customer'; } diff --git a/tests/Stubs/ActiveRecord/CustomerWithFactory.php b/tests/Stubs/ActiveRecord/CustomerWithFactory.php index 1c2b46c86..033c72f65 100644 --- a/tests/Stubs/ActiveRecord/CustomerWithFactory.php +++ b/tests/Stubs/ActiveRecord/CustomerWithFactory.php @@ -21,7 +21,7 @@ public function __construct(Factory $factory, private Aliases $aliases) public function relationQuery(string $name): ActiveQueryInterface { return match ($name) { - 'ordersWithFactory' => $this->hasMany(OrderWithFactory::class, ['customer_id' => 'id']), + 'ordersWithFactory' => $this->activeRecord()->hasMany(OrderWithFactory::class, ['customer_id' => 'id']), default => parent::relationQuery($name), }; } @@ -29,6 +29,6 @@ public function relationQuery(string $name): ActiveQueryInterface /** @return OrderWithFactory[] */ public function getOrdersWithFactory(): array { - return $this->relation('ordersWithFactory'); + return $this->activeRecord()->relation('ordersWithFactory'); } } diff --git a/tests/Stubs/ActiveRecord/DefaultPk.php b/tests/Stubs/ActiveRecord/DefaultPk.php index 7565a1f29..20ac6263c 100644 --- a/tests/Stubs/ActiveRecord/DefaultPk.php +++ b/tests/Stubs/ActiveRecord/DefaultPk.php @@ -4,14 +4,14 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; -final class DefaultPk extends ActiveRecord +final class DefaultPk extends ActiveRecordModel { public int $id; public string $type; - public function getTableName(): string + public function tableName(): string { return 'default_pk'; } diff --git a/tests/Stubs/ActiveRecord/Department.php b/tests/Stubs/ActiveRecord/Department.php index 4de951604..ce0023ec8 100644 --- a/tests/Stubs/ActiveRecord/Department.php +++ b/tests/Stubs/ActiveRecord/Department.php @@ -6,18 +6,18 @@ use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; use Yiisoft\ActiveRecord\ActiveRecordInterface; /** * Class Department */ -final class Department extends ActiveRecord +final class Department extends ActiveRecordModel { protected int $id; protected string $title; - public function getTableName(): string + public function tableName(): string { return 'department'; } @@ -32,12 +32,12 @@ public function relationQuery(string $name): ActiveQueryInterface public function getEmployees(): ActiveRecordInterface { - return $this->relation('employees'); + return $this->activeRecord()->relation('employees'); } public function getEmployeesQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Employee::class, [ 'department_id' => 'id', diff --git a/tests/Stubs/ActiveRecord/Document.php b/tests/Stubs/ActiveRecord/Document.php index b1faad047..68bc2145d 100644 --- a/tests/Stubs/ActiveRecord/Document.php +++ b/tests/Stubs/ActiveRecord/Document.php @@ -4,10 +4,10 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; use Yiisoft\ActiveRecord\OptimisticLockInterface; -final class Document extends ActiveRecord implements OptimisticLockInterface +final class Document extends ActiveRecordModel implements OptimisticLockInterface { public int $id; public string $title; diff --git a/tests/Stubs/ActiveRecord/Dog.php b/tests/Stubs/ActiveRecord/Dog.php index ffd7aa0bf..ecc16b753 100644 --- a/tests/Stubs/ActiveRecord/Dog.php +++ b/tests/Stubs/ActiveRecord/Dog.php @@ -9,10 +9,8 @@ */ final class Dog extends Animal { - public function populateRecord($row): void + public function initialize(): void { - parent::populateRecord($row); - $this->setDoes('bark'); } } diff --git a/tests/Stubs/ActiveRecord/Dossier.php b/tests/Stubs/ActiveRecord/Dossier.php index edd8099f3..94df1cc56 100644 --- a/tests/Stubs/ActiveRecord/Dossier.php +++ b/tests/Stubs/ActiveRecord/Dossier.php @@ -6,19 +6,19 @@ use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class Dossier */ -final class Dossier extends ActiveRecord +final class Dossier extends ActiveRecordModel { protected int $id; protected int $department_id; protected int $employee_id; protected string $summary; - public function getTableName(): string + public function tableName(): string { return 'dossier'; } @@ -50,12 +50,12 @@ public function setId(int $id): void public function setDepartmentId(int $departmentId): void { - $this->set('department_id', $departmentId); + $this->activeRecord()->set('department_id', $departmentId); } public function setEmployeeId(int $employeeId): void { - $this->set('employee_id', $employeeId); + $this->activeRecord()->set('employee_id', $employeeId); } public function setSummary(string $summary): void @@ -73,12 +73,12 @@ public function relationQuery(string $name): ActiveQueryInterface public function getEmployee(): Employee|null { - return $this->relation('employee'); + return $this->activeRecord()->relation('employee'); } public function getEmployeeQuery(): ActiveQuery { - return $this->hasOne( + return $this->activeRecord()->hasOne( Employee::class, [ 'department_id' => 'department_id', diff --git a/tests/Stubs/ActiveRecord/Employee.php b/tests/Stubs/ActiveRecord/Employee.php index 5bd94b631..59fcc417f 100644 --- a/tests/Stubs/ActiveRecord/Employee.php +++ b/tests/Stubs/ActiveRecord/Employee.php @@ -6,19 +6,19 @@ use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class Employee */ -final class Employee extends ActiveRecord +final class Employee extends ActiveRecordModel { protected int $id; protected int $department_id; protected string $first_name; protected string $last_name; - public function getTableName(): string + public function tableName(): string { return 'employee'; } @@ -39,13 +39,13 @@ public function getFullName(): string public function getDepartment(): Department { - return $this->relation('department'); + return $this->activeRecord()->relation('department'); } public function getDepartmentQuery(): ActiveQuery { return $this - ->hasOne(Department::class, [ + ->activeRecord()->hasOne(Department::class, [ 'id' => 'department_id', ]) ->inverseOf('employees') @@ -54,12 +54,12 @@ public function getDepartmentQuery(): ActiveQuery public function getDossier(): Dossier { - return $this->relation('dossier'); + return $this->activeRecord()->relation('dossier'); } public function getDossierQuery(): ActiveQuery { - return $this->hasOne( + return $this->activeRecord()->hasOne( Dossier::class, [ 'department_id' => 'department_id', diff --git a/tests/Stubs/ActiveRecord/Item.php b/tests/Stubs/ActiveRecord/Item.php index fb2001bae..bc0c786f5 100644 --- a/tests/Stubs/ActiveRecord/Item.php +++ b/tests/Stubs/ActiveRecord/Item.php @@ -6,18 +6,18 @@ use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class Item. */ -class Item extends ActiveRecord +class Item extends ActiveRecordModel { protected int $id; protected string $name; protected int $category_id; - public function getTableName(): string + public function tableName(): string { return 'item'; } @@ -26,7 +26,7 @@ public function relationQuery(string $name): ActiveQueryInterface { return match ($name) { 'category' => $this->getCategoryQuery(), - 'promotionsViaJson' => $this->hasMany(Promotion::class, ['json_item_ids' => 'id']), + 'promotionsViaJson' => $this->activeRecord()->hasMany(Promotion::class, ['json_item_ids' => 'id']), default => parent::relationQuery($name), }; } @@ -48,17 +48,17 @@ public function getCategoryId(): int public function getCategory(): Category { - return $this->relation('category'); + return $this->activeRecord()->relation('category'); } public function getCategoryQuery(): ActiveQuery { - return $this->hasOne(Category::class, ['id' => 'category_id']); + return $this->activeRecord()->hasOne(Category::class, ['id' => 'category_id']); } /** @return Promotion[] */ public function getPromotionsViaJson(): array { - return $this->relation('promotionsViaJson'); + return $this->activeRecord()->relation('promotionsViaJson'); } } diff --git a/tests/Stubs/ActiveRecord/NoExist.php b/tests/Stubs/ActiveRecord/NoExist.php index 4f9d1c248..87b35a6f6 100644 --- a/tests/Stubs/ActiveRecord/NoExist.php +++ b/tests/Stubs/ActiveRecord/NoExist.php @@ -4,11 +4,11 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; -final class NoExist extends ActiveRecord +final class NoExist extends ActiveRecordModel { - public function getTableName(): string + public function tableName(): string { return 'NoExist'; } diff --git a/tests/Stubs/ActiveRecord/NullValues.php b/tests/Stubs/ActiveRecord/NullValues.php index b33c9ca7b..ba6e4a531 100644 --- a/tests/Stubs/ActiveRecord/NullValues.php +++ b/tests/Stubs/ActiveRecord/NullValues.php @@ -4,7 +4,7 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class NullValues. @@ -16,9 +16,9 @@ * @property string $stringcol */ #[\AllowDynamicProperties] -final class NullValues extends ActiveRecord +final class NullValues extends ActiveRecordModel { - public function getTableName(): string + public function tableName(): string { return 'null_values'; } diff --git a/tests/Stubs/ActiveRecord/Order.php b/tests/Stubs/ActiveRecord/Order.php index 1d8b1e119..2b962b067 100644 --- a/tests/Stubs/ActiveRecord/Order.php +++ b/tests/Stubs/ActiveRecord/Order.php @@ -6,13 +6,13 @@ use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; use Yiisoft\ActiveRecord\Trait\CustomTableNameTrait; /** * Class Order. */ -class Order extends ActiveRecord +class Order extends ActiveRecordModel { use CustomTableNameTrait; @@ -25,7 +25,7 @@ class Order extends ActiveRecord protected string|int|null $virtualCustomerId = null; - public function getTableName(): string + public function tableName(): string { return $this->tableName ??= self::TABLE_NAME; } @@ -52,12 +52,12 @@ public function getTotal(): float public function setId(int|null $id): void { - $this->set('id', $id); + $this->activeRecord()->set('id', $id); } public function setCustomerId(int $customerId): void { - $this->set('customer_id', $customerId); + $this->activeRecord()->set('customer_id', $customerId); } public function setCreatedAt(int $createdAt): void @@ -112,42 +112,42 @@ public function setVirtualCustomerId(string|int|null $virtualCustomerId = null): public function getVirtualCustomer(): Customer|null { - return $this->relation('virtualCustomer'); + return $this->activeRecord()->relation('virtualCustomer'); } public function getVirtualCustomerQuery(): ActiveQuery { - return $this->hasOne(Customer::class, ['id' => 'virtualCustomerId']); + return $this->activeRecord()->hasOne(Customer::class, ['id' => 'virtualCustomerId']); } public function getCustomer(): Customer|null { - return $this->relation('customer'); + return $this->activeRecord()->relation('customer'); } public function getCustomerQuery(): ActiveQuery { - return $this->hasOne(Customer::class, ['id' => 'customer_id']); + return $this->activeRecord()->hasOne(Customer::class, ['id' => 'customer_id']); } public function getCustomerJoinedWithProfile(): Customer|null { - return $this->relation('customerJoinedWithProfile'); + return $this->activeRecord()->relation('customerJoinedWithProfile'); } public function getCustomerJoinedWithProfileQuery(): ActiveQuery { - return $this->hasOne(Customer::class, ['id' => 'customer_id'])->joinWith('profile'); + return $this->activeRecord()->hasOne(Customer::class, ['id' => 'customer_id'])->joinWith('profile'); } public function getCustomerJoinedWithProfileIndexOrdered(): array { - return $this->relation('customerJoinedWithProfileIndexOrdered'); + return $this->activeRecord()->relation('customerJoinedWithProfileIndexOrdered'); } public function getCustomerJoinedWithProfileIndexOrderedQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Customer::class, ['id' => 'customer_id'] )->joinWith('profile')->orderBy(['profile.description' => SORT_ASC])->indexBy('name'); @@ -155,42 +155,42 @@ public function getCustomerJoinedWithProfileIndexOrderedQuery(): ActiveQuery public function getCustomer2(): Customer|null { - return $this->relation('customer2'); + return $this->activeRecord()->relation('customer2'); } public function getCustomer2Query(): ActiveQuery { - return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders2'); + return $this->activeRecord()->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders2'); } public function getOrderItems(): array { - return $this->relation('orderItems'); + return $this->activeRecord()->relation('orderItems'); } public function getOrderItemsQuery(): ActiveQuery { - return $this->hasMany(OrderItem::class, ['order_id' => 'id']); + return $this->activeRecord()->hasMany(OrderItem::class, ['order_id' => 'id']); } public function getOrderItems2(): array { - return $this->relation('orderItems2'); + return $this->activeRecord()->relation('orderItems2'); } public function getOrderItems2Query(): ActiveQuery { - return $this->hasMany(OrderItem::class, ['order_id' => 'id'])->indexBy('item_id'); + return $this->activeRecord()->hasMany(OrderItem::class, ['order_id' => 'id'])->indexBy('item_id'); } public function getOrderItems3(): array { - return $this->relation('orderItems3'); + return $this->activeRecord()->relation('orderItems3'); } public function getOrderItems3Query(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( OrderItem::class, ['order_id' => 'id'] )->indexBy(fn ($row) => $row['order_id'] . '_' . $row['item_id']); @@ -198,44 +198,44 @@ public function getOrderItems3Query(): ActiveQuery public function getOrderItemsWithNullFK(): array { - return $this->relation('orderItemsWithNullFK'); + return $this->activeRecord()->relation('orderItemsWithNullFK'); } public function getOrderItemsWithNullFKQuery(): ActiveQuery { - return $this->hasMany(OrderItemWithNullFK::class, ['order_id' => 'id']); + return $this->activeRecord()->hasMany(OrderItemWithNullFK::class, ['order_id' => 'id']); } public function getItems(): array { - return $this->relation('items'); + return $this->activeRecord()->relation('items'); } public function getItemsQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { // additional query configuration })->orderBy('item.id'); } public function getItemsIndexed(): array { - return $this->relation('itemsIndexed'); + return $this->activeRecord()->relation('itemsIndexed'); } public function getItemsIndexedQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems')->indexBy('id'); + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems')->indexBy('id'); } public function getItemsWithNullFK(): array { - return $this->relation('itemsWithNullFK'); + return $this->activeRecord()->relation('itemsWithNullFK'); } public function getItemsWithNullFKQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->viaTable('order_item_with_null_fk', ['order_id' => 'id']); @@ -243,46 +243,46 @@ public function getItemsWithNullFKQuery(): ActiveQuery public function getItemsInOrder1(): array { - return $this->relation('itemsInOrder1'); + return $this->activeRecord()->relation('itemsInOrder1'); } public function getItemsInOrder1Query(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { $q->orderBy(['subtotal' => SORT_ASC]); })->orderBy('name'); } public function getItemsInOrder2(): array { - return $this->relation('itemsInOrder2'); + return $this->activeRecord()->relation('itemsInOrder2'); } public function getItemsInOrder2Query(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { $q->orderBy(['subtotal' => SORT_DESC]); })->orderBy('name'); } public function getBooks(): array { - return $this->relation('books'); + return $this->activeRecord()->relation('books'); } public function getBooksQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems')->where(['category_id' => 1]); + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems')->where(['category_id' => 1]); } public function getBooksWithNullFK(): array { - return $this->relation('booksWithNullFK'); + return $this->activeRecord()->relation('booksWithNullFK'); } public function getBooksWithNullFKQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->via('orderItemsWithNullFK')->where(['category_id' => 1]); @@ -290,12 +290,12 @@ public function getBooksWithNullFKQuery(): ActiveQuery public function getBooksViaTable(): array { - return $this->relation('booksViaTable'); + return $this->activeRecord()->relation('booksViaTable'); } public function getBooksViaTableQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->viaTable('order_item', ['order_id' => 'id'])->where(['category_id' => 1]); @@ -303,12 +303,12 @@ public function getBooksViaTableQuery(): ActiveQuery public function getBooksWithNullFKViaTable(): array { - return $this->relation('booksWithNullFKViaTable'); + return $this->activeRecord()->relation('booksWithNullFKViaTable'); } public function getBooksWithNullFKViaTableQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->viaTable('order_item_with_null_fk', ['order_id' => 'id'])->where(['category_id' => 1]); @@ -316,12 +316,12 @@ public function getBooksWithNullFKViaTableQuery(): ActiveQuery public function getBooks2(): array { - return $this->relation('books2'); + return $this->activeRecord()->relation('books2'); } public function getBooks2Query(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->onCondition(['category_id' => 1])->viaTable('order_item', ['order_id' => 'id']); @@ -329,12 +329,12 @@ public function getBooks2Query(): ActiveQuery public function getBooksExplicit(): array { - return $this->relation('booksExplicit'); + return $this->activeRecord()->relation('booksExplicit'); } public function getBooksExplicitQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->onCondition(['category_id' => 1])->viaTable('order_item', ['order_id' => 'id']); @@ -342,12 +342,12 @@ public function getBooksExplicitQuery(): ActiveQuery public function getBooksExplicitA(): array { - return $this->relation('booksExplicitA'); + return $this->activeRecord()->relation('booksExplicitA'); } public function getBooksExplicitAQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->alias('bo')->onCondition(['bo.category_id' => 1])->viaTable('order_item', ['order_id' => 'id']); @@ -355,12 +355,12 @@ public function getBooksExplicitAQuery(): ActiveQuery public function getBookItems(): array { - return $this->relation('bookItems'); + return $this->activeRecord()->relation('bookItems'); } public function getBookItemsQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->alias('books')->onCondition(['books.category_id' => 1])->viaTable('order_item', ['order_id' => 'id']); @@ -368,12 +368,12 @@ public function getBookItemsQuery(): ActiveQuery public function getMovieItems(): array { - return $this->relation('movieItems'); + return $this->activeRecord()->relation('movieItems'); } public function getMovieItemsQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->alias('movies')->onCondition(['movies.category_id' => 2])->viaTable('order_item', ['order_id' => 'id']); @@ -381,55 +381,55 @@ public function getMovieItemsQuery(): ActiveQuery public function getLimitedItems(): array { - return $this->relation('limitedItems'); + return $this->activeRecord()->relation('limitedItems'); } public function getLimitedItemsQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->onCondition(['item.id' => [3, 5]])->via('orderItems'); + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->onCondition(['item.id' => [3, 5]])->via('orderItems'); } public function getExpensiveItemsUsingViaWithCallable(): array { - return $this->relation('expensiveItemsUsingViaWithCallable'); + return $this->activeRecord()->relation('expensiveItemsUsingViaWithCallable'); } public function getExpensiveItemsUsingViaWithCallableQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', function (ActiveQuery $q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', function (ActiveQuery $q) { $q->where(['>=', 'subtotal', 10]); }); } public function getCheapItemsUsingViaWithCallable(): array { - return $this->relation('cheapItemsUsingViaWithCallable'); + return $this->activeRecord()->relation('cheapItemsUsingViaWithCallable'); } public function getCheapItemsUsingViaWithCallableQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', function (ActiveQuery $q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', function (ActiveQuery $q) { $q->where(['<', 'subtotal', 10]); }); } public function getOrderItemsFor8(): array { - return $this->relation('orderItemsFor8'); + return $this->activeRecord()->relation('orderItemsFor8'); } public function getOrderItemsFor8Query(): ActiveQuery { - return $this->hasMany(OrderItemWithNullFK::class, ['order_id' => 'id'])->andOnCondition(['subtotal' => 8.0]); + return $this->activeRecord()->hasMany(OrderItemWithNullFK::class, ['order_id' => 'id'])->andOnCondition(['subtotal' => 8.0]); } public function getItemsFor8(): array { - return $this->relation('itemsFor8'); + return $this->activeRecord()->relation('itemsFor8'); } public function getItemsFor8Query(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItemsFor8'); + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItemsFor8'); } } diff --git a/tests/Stubs/ActiveRecord/OrderItem.php b/tests/Stubs/ActiveRecord/OrderItem.php index 471a730ab..ae6d7028e 100644 --- a/tests/Stubs/ActiveRecord/OrderItem.php +++ b/tests/Stubs/ActiveRecord/OrderItem.php @@ -6,13 +6,13 @@ use Yiisoft\ActiveRecord\ActiveQuery; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; use Yiisoft\ActiveRecord\Trait\CustomTableNameTrait; /** * Class OrderItem. */ -final class OrderItem extends ActiveRecord +final class OrderItem extends ActiveRecordModel { use CustomTableNameTrait; @@ -21,7 +21,7 @@ final class OrderItem extends ActiveRecord protected int $quantity; protected float $subtotal; - public function getTableName(): string + public function tableName(): string { return $this->tableName ??= 'order_item'; } @@ -48,12 +48,12 @@ public function getSubtotal(): float public function setOrderId(int $orderId): void { - $this->set('order_id', $orderId); + $this->activeRecord()->set('order_id', $orderId); } public function setItemId(int $itemId): void { - $this->set('item_id', $itemId); + $this->activeRecord()->set('item_id', $itemId); } public function setQuantity(int $quantity): void @@ -80,48 +80,48 @@ public function relationQuery(string $name): ActiveQueryInterface public function getOrder(): Order|null { - return $this->relation('order'); + return $this->activeRecord()->relation('order'); } public function getOrderQuery(): ActiveQuery { - return $this->hasOne(Order::class, ['id' => 'order_id']); + return $this->activeRecord()->hasOne(Order::class, ['id' => 'order_id']); } public function getItem(): Item|null { - return $this->relation('item'); + return $this->activeRecord()->relation('item'); } public function getItemQuery(): ActiveQuery { - return $this->hasOne(Item::class, ['id' => 'item_id']); + return $this->activeRecord()->hasOne(Item::class, ['id' => 'item_id']); } public function getOrderItemCompositeWithJoin(): self|null { - return $this->relation('orderItemCompositeWithJoin'); + return $this->activeRecord()->relation('orderItemCompositeWithJoin'); } public function getOrderItemCompositeWithJoinQuery(): ActiveQuery { /** relations used by testFindCompositeWithJoin() */ - return $this->hasOne(self::class, ['item_id' => 'item_id', 'order_id' => 'order_id' ])->joinWith('item'); + return $this->activeRecord()->hasOne(self::class, ['item_id' => 'item_id', 'order_id' => 'order_id' ])->joinWith('item'); } public function getOrderItemCompositeNoJoin(): self|null { - return $this->relation('orderItemCompositeNoJoin'); + return $this->activeRecord()->relation('orderItemCompositeNoJoin'); } public function getOrderItemCompositeNoJoinQuery(): ActiveQuery { - return $this->hasOne(self::class, ['item_id' => 'item_id', 'order_id' => 'order_id' ]); + return $this->activeRecord()->hasOne(self::class, ['item_id' => 'item_id', 'order_id' => 'order_id' ]); } public function getCustom(): Order|null { - return $this->relation('custom'); + return $this->activeRecord()->relation('custom'); } public function getCustomQuery(): ActiveQuery diff --git a/tests/Stubs/ActiveRecord/OrderItemWithNullFK.php b/tests/Stubs/ActiveRecord/OrderItemWithNullFK.php index 8dd104b33..83dcce7af 100644 --- a/tests/Stubs/ActiveRecord/OrderItemWithNullFK.php +++ b/tests/Stubs/ActiveRecord/OrderItemWithNullFK.php @@ -4,19 +4,19 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class OrderItem. */ -final class OrderItemWithNullFK extends ActiveRecord +final class OrderItemWithNullFK extends ActiveRecordModel { protected int|null $order_id = null; protected int|null $item_id = null; protected int $quantity; protected float $subtotal; - public function getTableName(): string + public function tableName(): string { return 'order_item_with_null_fk'; } diff --git a/tests/Stubs/ActiveRecord/OrderWithFactory.php b/tests/Stubs/ActiveRecord/OrderWithFactory.php index d0a8b9282..49aa5981e 100644 --- a/tests/Stubs/ActiveRecord/OrderWithFactory.php +++ b/tests/Stubs/ActiveRecord/OrderWithFactory.php @@ -14,12 +14,12 @@ final class OrderWithFactory extends Order public function relationQuery(string $name): ActiveQueryInterface { return match ($name) { - 'customerWithFactory' => $this->hasOne(CustomerWithFactory::class, ['id' => 'customer_id']), - 'customerWithFactoryClosure' => $this->hasOne( + 'customerWithFactory' => $this->activeRecord()->hasOne(CustomerWithFactory::class, ['id' => 'customer_id']), + 'customerWithFactoryClosure' => $this->activeRecord()->hasOne( fn () => $this->factory->create(CustomerWithFactory::class), ['id' => 'customer_id'] ), - 'customerWithFactoryInstance' => $this->hasOne( + 'customerWithFactoryInstance' => $this->activeRecord()->hasOne( $this->factory->create(CustomerWithFactory::class), ['id' => 'customer_id'] ), @@ -29,16 +29,16 @@ public function relationQuery(string $name): ActiveQueryInterface public function getCustomerWithFactory(): CustomerWithFactory|null { - return $this->relation('customerWithFactory'); + return $this->activeRecord()->relation('customerWithFactory'); } public function getCustomerWithFactoryClosure(): CustomerWithFactory|null { - return $this->relation('customerWithFactoryClosure'); + return $this->activeRecord()->relation('customerWithFactoryClosure'); } public function getCustomerWithFactoryInstance(): CustomerWithFactory|null { - return $this->relation('customerWithFactoryInstance'); + return $this->activeRecord()->relation('customerWithFactoryInstance'); } } diff --git a/tests/Stubs/ActiveRecord/OrderWithNullFK.php b/tests/Stubs/ActiveRecord/OrderWithNullFK.php index eea6b5495..6b7402c1c 100644 --- a/tests/Stubs/ActiveRecord/OrderWithNullFK.php +++ b/tests/Stubs/ActiveRecord/OrderWithNullFK.php @@ -4,19 +4,19 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class Order. */ -final class OrderWithNullFK extends ActiveRecord +final class OrderWithNullFK extends ActiveRecordModel { protected int $id; protected int|null $customer_id = null; protected int $created_at; protected float $total; - public function getTableName(): string + public function tableName(): string { return 'order_with_null_fk'; } diff --git a/tests/Stubs/ActiveRecord/Profile.php b/tests/Stubs/ActiveRecord/Profile.php index 251fab816..761bc7a5b 100644 --- a/tests/Stubs/ActiveRecord/Profile.php +++ b/tests/Stubs/ActiveRecord/Profile.php @@ -4,19 +4,19 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class Profile. */ -final class Profile extends ActiveRecord +final class Profile extends ActiveRecordModel { public const TABLE_NAME = 'profile'; protected int $id; protected string $description; - public function getTableName(): string + public function tableName(): string { return self::TABLE_NAME; } diff --git a/tests/Stubs/ActiveRecord/ProfileWithConstructor.php b/tests/Stubs/ActiveRecord/ProfileWithConstructor.php index 2b52f57d3..5543fbc69 100644 --- a/tests/Stubs/ActiveRecord/ProfileWithConstructor.php +++ b/tests/Stubs/ActiveRecord/ProfileWithConstructor.php @@ -4,14 +4,14 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; use Yiisoft\Aliases\Aliases; use Yiisoft\Db\Connection\ConnectionInterface; /** * Class Profile. */ -final class ProfileWithConstructor extends ActiveRecord +final class ProfileWithConstructor extends ActiveRecordModel { protected int $id; protected string $description; @@ -21,7 +21,7 @@ public function __construct(ConnectionInterface $db, private Aliases $aliases) parent::__construct($db); } - public function getTableName(): string + public function tableName(): string { return 'profile'; } diff --git a/tests/Stubs/ActiveRecord/Promotion.php b/tests/Stubs/ActiveRecord/Promotion.php index 86a5654e5..68c4c6139 100644 --- a/tests/Stubs/ActiveRecord/Promotion.php +++ b/tests/Stubs/ActiveRecord/Promotion.php @@ -5,9 +5,9 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; use Yiisoft\ActiveRecord\ActiveQueryInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; -class Promotion extends ActiveRecord +class Promotion extends ActiveRecordModel { public int $id; /** @var int[] $array_item_ids */ @@ -16,7 +16,7 @@ class Promotion extends ActiveRecord public array $json_item_ids; public string $title; - public function getTableName(): string + public function tableName(): string { return '{{%promotion}}'; } @@ -24,7 +24,7 @@ public function getTableName(): string public function relationQuery(string $name): ActiveQueryInterface { return match ($name) { - 'itemsViaJson' => $this->hasMany(Item::class, ['id' => 'json_item_ids']) + 'itemsViaJson' => $this->activeRecord()->hasMany(Item::class, ['id' => 'json_item_ids']) ->inverseOf('promotionsViaJson'), default => parent::relationQuery($name), }; @@ -33,6 +33,6 @@ public function relationQuery(string $name): ActiveQueryInterface /** @return Item[] */ public function getItemsViaJson(): array { - return $this->relation('itemsViaJson'); + return $this->activeRecord()->relation('itemsViaJson'); } } diff --git a/tests/Stubs/ActiveRecord/TestTrigger.php b/tests/Stubs/ActiveRecord/TestTrigger.php index caee9c577..b263ab63b 100644 --- a/tests/Stubs/ActiveRecord/TestTrigger.php +++ b/tests/Stubs/ActiveRecord/TestTrigger.php @@ -4,17 +4,17 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class TestTrigger. */ -final class TestTrigger extends ActiveRecord +final class TestTrigger extends ActiveRecordModel { public int $id; public string $stringcol; - public function getTableName(): string + public function tableName(): string { return 'test_trigger'; } diff --git a/tests/Stubs/ActiveRecord/TestTriggerAlert.php b/tests/Stubs/ActiveRecord/TestTriggerAlert.php index 96ffb6b34..30a3e36ea 100644 --- a/tests/Stubs/ActiveRecord/TestTriggerAlert.php +++ b/tests/Stubs/ActiveRecord/TestTriggerAlert.php @@ -4,17 +4,17 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; /** * Class TestTriggerAlert. */ -final class TestTriggerAlert extends ActiveRecord +final class TestTriggerAlert extends ActiveRecordModel { public int $id; public string $stringcol; - public function getTableName(): string + public function tableName(): string { return 'test_trigger_alert'; } diff --git a/tests/Stubs/ActiveRecord/Type.php b/tests/Stubs/ActiveRecord/Type.php index 421df9204..b387428f1 100644 --- a/tests/Stubs/ActiveRecord/Type.php +++ b/tests/Stubs/ActiveRecord/Type.php @@ -4,13 +4,13 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; use Yiisoft\Db\Expression\Expression; /** * Model representing type table. */ -class Type extends ActiveRecord +class Type extends ActiveRecordModel { public int $int_col; public int|null $int_col2 = 1; @@ -30,7 +30,7 @@ class Type extends ActiveRecord public int|string $bit_col = 0b1000_0010; public array|null $json_col = null; - public function getTableName(): string + public function tableName(): string { return 'type'; } diff --git a/tests/Stubs/ActiveRecord/UserAR.php b/tests/Stubs/ActiveRecord/UserAR.php index 9944cab58..ae77e2c13 100644 --- a/tests/Stubs/ActiveRecord/UserAR.php +++ b/tests/Stubs/ActiveRecord/UserAR.php @@ -4,9 +4,9 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; -final class UserAR extends ActiveRecord +final class UserAR extends ActiveRecordModel { public const STATUS_DELETED = 0; public const STATUS_ACTIVE = 10; @@ -24,7 +24,7 @@ final class UserAR extends ActiveRecord public int $updated_at; public bool $is_deleted = false; - public function getTableName(): string + public function tableName(): string { return '{{%bool_user}}'; } diff --git a/tests/Stubs/ArrayableActiveRecord.php b/tests/Stubs/ArrayableActiveRecord.php index 6f013d605..949c0a4ef 100644 --- a/tests/Stubs/ArrayableActiveRecord.php +++ b/tests/Stubs/ArrayableActiveRecord.php @@ -4,7 +4,7 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; use Yiisoft\ActiveRecord\Trait\ArrayableTrait; use Yiisoft\Arrays\ArrayableInterface; @@ -13,7 +13,7 @@ * * @see ArrayableInterface to convert the object into an array; */ -class ArrayableActiveRecord extends ActiveRecord implements ArrayableInterface +class ArrayableActiveRecord extends ActiveRecordModel implements ArrayableInterface { use ArrayableTrait; } diff --git a/tests/Stubs/MagicActiveRecord.php b/tests/Stubs/MagicActiveRecord.php index 90d79541d..a8a28f0c4 100644 --- a/tests/Stubs/MagicActiveRecord.php +++ b/tests/Stubs/MagicActiveRecord.php @@ -5,7 +5,7 @@ namespace Yiisoft\ActiveRecord\Tests\Stubs; use Yiisoft\ActiveRecord\ActiveRecordInterface; -use Yiisoft\ActiveRecord\ActiveRecord; +use Yiisoft\ActiveRecord\ActiveRecordModel; use Yiisoft\ActiveRecord\Trait\MagicPropertiesTrait; use Yiisoft\ActiveRecord\Trait\MagicRelationsTrait; @@ -15,7 +15,7 @@ * @see MagicPropertiesTrait to access column values and relations via PHP magic methods as properties; * @see MagicRelationsTrait to access relation queries. */ -class MagicActiveRecord extends ActiveRecord +class MagicActiveRecord extends ActiveRecordModel { use MagicPropertiesTrait; use MagicRelationsTrait; diff --git a/tests/Stubs/MagicActiveRecord/Alpha.php b/tests/Stubs/MagicActiveRecord/Alpha.php index 1392800c3..20289f003 100644 --- a/tests/Stubs/MagicActiveRecord/Alpha.php +++ b/tests/Stubs/MagicActiveRecord/Alpha.php @@ -15,13 +15,13 @@ final class Alpha extends MagicActiveRecord { public const TABLE_NAME = 'alpha'; - public function getTableName(): string + public function tableName(): string { return self::TABLE_NAME; } public function getBetasQuery(): ActiveQuery { - return $this->hasMany(Beta::class, ['alpha_string_identifier' => 'string_identifier']); + return $this->activeRecord()->hasMany(Beta::class, ['alpha_string_identifier' => 'string_identifier']); } } diff --git a/tests/Stubs/MagicActiveRecord/Animal.php b/tests/Stubs/MagicActiveRecord/Animal.php index c6ad39fbc..fb6470164 100644 --- a/tests/Stubs/MagicActiveRecord/Animal.php +++ b/tests/Stubs/MagicActiveRecord/Animal.php @@ -16,7 +16,7 @@ class Animal extends MagicActiveRecord { private string $does; - public function getTableName(): string + public function tableName(): string { return 'animal'; } diff --git a/tests/Stubs/MagicActiveRecord/Beta.php b/tests/Stubs/MagicActiveRecord/Beta.php index dcccdf627..4b54555fa 100644 --- a/tests/Stubs/MagicActiveRecord/Beta.php +++ b/tests/Stubs/MagicActiveRecord/Beta.php @@ -14,13 +14,13 @@ */ final class Beta extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'beta'; } public function getAlphaQuery(): ActiveQuery { - return $this->hasOne(Alpha::class, ['string_identifier' => 'alpha_string_identifier']); + return $this->activeRecord()->hasOne(Alpha::class, ['string_identifier' => 'alpha_string_identifier']); } } diff --git a/tests/Stubs/MagicActiveRecord/BoolAR.php b/tests/Stubs/MagicActiveRecord/BoolAR.php index dfc685b26..f911d2092 100644 --- a/tests/Stubs/MagicActiveRecord/BoolAR.php +++ b/tests/Stubs/MagicActiveRecord/BoolAR.php @@ -8,7 +8,7 @@ final class BoolAR extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'bool_values'; } diff --git a/tests/Stubs/MagicActiveRecord/Cat.php b/tests/Stubs/MagicActiveRecord/Cat.php index dd5b680c8..236121a4e 100644 --- a/tests/Stubs/MagicActiveRecord/Cat.php +++ b/tests/Stubs/MagicActiveRecord/Cat.php @@ -8,10 +8,8 @@ final class Cat extends Animal { - public function populateRecord($row): void + public function initialize(): void { - parent::populateRecord($row); - $this->setDoes('meow'); } diff --git a/tests/Stubs/MagicActiveRecord/Category.php b/tests/Stubs/MagicActiveRecord/Category.php index d8cc2fc5a..cdc0c80bf 100644 --- a/tests/Stubs/MagicActiveRecord/Category.php +++ b/tests/Stubs/MagicActiveRecord/Category.php @@ -15,28 +15,28 @@ */ final class Category extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'category'; } public function getLimitedItemsQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['category_id' => 'id'])->onCondition(['item.id' => [1, 2, 3]]); + return $this->activeRecord()->hasMany(Item::class, ['category_id' => 'id'])->onCondition(['item.id' => [1, 2, 3]]); } public function getItemsQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['category_id' => 'id']); + return $this->activeRecord()->hasMany(Item::class, ['category_id' => 'id']); } public function getOrderItemsQuery(): ActiveQuery { - return $this->hasMany(OrderItem::class, ['item_id' => 'id'])->via('items'); + return $this->activeRecord()->hasMany(OrderItem::class, ['item_id' => 'id'])->via('items'); } public function getOrdersQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['id' => 'order_id'])->via('orderItems'); + return $this->activeRecord()->hasMany(Order::class, ['id' => 'order_id'])->via('orderItems'); } } diff --git a/tests/Stubs/MagicActiveRecord/Customer.php b/tests/Stubs/MagicActiveRecord/Customer.php index 1353676e0..3d53a7e08 100644 --- a/tests/Stubs/MagicActiveRecord/Customer.php +++ b/tests/Stubs/MagicActiveRecord/Customer.php @@ -31,34 +31,34 @@ class Customer extends MagicActiveRecord */ public $sumTotal; - public function getTableName(): string + public function tableName(): string { return 'customer'; } public function getProfileQuery(): ActiveQuery { - return $this->hasOne(Profile::class, ['id' => 'profile_id']); + return $this->activeRecord()->activeRecord()->hasOne(Profile::class, ['id' => 'profile_id']); } public function getOrdersPlainQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id']); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id']); } public function getOrdersQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('[[id]]'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('[[id]]'); } public function getOrdersNoOrderQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id']); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id']); } public function getExpensiveOrdersQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->andWhere('[[total]] > 50')->orderBy('id'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->andWhere('[[total]] > 50')->orderBy('id'); } public function getItemQuery(): void @@ -67,12 +67,12 @@ public function getItemQuery(): void public function getOrdersWithItemsQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->with('orderItems'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->with('orderItems'); } public function getExpensiveOrdersWithNullFKQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( OrderWithNullFK::class, ['customer_id' => 'id'] )->andWhere('[[total]] > 50')->orderBy('id'); @@ -80,18 +80,18 @@ public function getExpensiveOrdersWithNullFKQuery(): ActiveQuery public function getOrdersWithNullFKQuery(): ActiveQuery { - return $this->hasMany(OrderWithNullFK::class, ['customer_id' => 'id'])->orderBy('id'); + return $this->activeRecord()->hasMany(OrderWithNullFK::class, ['customer_id' => 'id'])->orderBy('id'); } public function getOrders2Query(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer2')->orderBy('id'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer2')->orderBy('id'); } /** deeply nested table relation */ public function getOrderItemsQuery(): ActiveQuery { - $rel = $this->hasMany(Item::class, ['id' => 'item_id']); + $rel = $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id']); return $rel->viaTable('order_item', ['order_id' => 'id'], function ($q) { /* @var $q ActiveQuery */ @@ -105,13 +105,13 @@ public function setOrdersReadOnly(): void public function getOrderItems2Query(): ActiveQuery { - return $this->hasMany(OrderItem::class, ['order_id' => 'id']) + return $this->activeRecord()->hasMany(OrderItem::class, ['order_id' => 'id']) ->via('ordersNoOrder'); } public function getItems2Query(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id']) + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id']) ->via('orderItems2'); } } diff --git a/tests/Stubs/MagicActiveRecord/CustomerWithAlias.php b/tests/Stubs/MagicActiveRecord/CustomerWithAlias.php index ed21bb297..c2f76c81c 100644 --- a/tests/Stubs/MagicActiveRecord/CustomerWithAlias.php +++ b/tests/Stubs/MagicActiveRecord/CustomerWithAlias.php @@ -25,7 +25,7 @@ final class CustomerWithAlias extends MagicActiveRecord public int $status2; public float $sumTotal; - public function getTableName(): string + public function tableName(): string { return 'customer'; } diff --git a/tests/Stubs/MagicActiveRecord/CustomerWithProperties.php b/tests/Stubs/MagicActiveRecord/CustomerWithProperties.php index 37f7a8af0..84c9c8eb5 100644 --- a/tests/Stubs/MagicActiveRecord/CustomerWithProperties.php +++ b/tests/Stubs/MagicActiveRecord/CustomerWithProperties.php @@ -17,7 +17,7 @@ class CustomerWithProperties extends MagicActiveRecord protected string|null $name = null; public string|null $address = null; - public function getTableName(): string + public function tableName(): string { return 'customer'; } @@ -44,17 +44,17 @@ public function getAddress(): string|null public function getStatus(): int|null { - return $this->get('status'); + return $this->activeRecord()->get('status'); } public function getProfileQuery(): ActiveQuery { - return $this->hasOne(Profile::class, ['id' => 'profile_id']); + return $this->activeRecord()->hasOne(Profile::class, ['id' => 'profile_id']); } public function getOrdersQuery(): ActiveQuery { - return $this->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('[[id]]'); + return $this->activeRecord()->hasMany(Order::class, ['customer_id' => 'id'])->orderBy('[[id]]'); } public function setEmail(string $email): void @@ -74,6 +74,6 @@ public function setAddress(string|null $address): void public function setStatus(int|null $status): void { - $this->set('status', $status); + $this->activeRecord()->set('status', $status); } } diff --git a/tests/Stubs/MagicActiveRecord/DefaultPk.php b/tests/Stubs/MagicActiveRecord/DefaultPk.php index 57d5d1061..18ca2804d 100644 --- a/tests/Stubs/MagicActiveRecord/DefaultPk.php +++ b/tests/Stubs/MagicActiveRecord/DefaultPk.php @@ -8,7 +8,7 @@ final class DefaultPk extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'default_pk'; } diff --git a/tests/Stubs/MagicActiveRecord/Department.php b/tests/Stubs/MagicActiveRecord/Department.php index c31b142bc..8d3d79e35 100644 --- a/tests/Stubs/MagicActiveRecord/Department.php +++ b/tests/Stubs/MagicActiveRecord/Department.php @@ -16,14 +16,14 @@ */ final class Department extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'department'; } public function getEmployeesQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Employee::class, [ 'department_id' => 'id', diff --git a/tests/Stubs/MagicActiveRecord/Dog.php b/tests/Stubs/MagicActiveRecord/Dog.php index ea3213706..f3f2a31c6 100644 --- a/tests/Stubs/MagicActiveRecord/Dog.php +++ b/tests/Stubs/MagicActiveRecord/Dog.php @@ -9,10 +9,8 @@ */ final class Dog extends Animal { - public function populateRecord($row): void + public function initialize(): void { - parent::populateRecord($row); - $this->setDoes('bark'); } } diff --git a/tests/Stubs/MagicActiveRecord/Dossier.php b/tests/Stubs/MagicActiveRecord/Dossier.php index ba52aebdc..bcdfc1c01 100644 --- a/tests/Stubs/MagicActiveRecord/Dossier.php +++ b/tests/Stubs/MagicActiveRecord/Dossier.php @@ -18,14 +18,14 @@ */ final class Dossier extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'dossier'; } public function getEmployeeQuery(): ActiveQuery { - return $this->hasOne( + return $this->activeRecord()->hasOne( Employee::class, [ 'department_id' => 'department_id', diff --git a/tests/Stubs/MagicActiveRecord/Employee.php b/tests/Stubs/MagicActiveRecord/Employee.php index 9410b6a8c..375dcb4a3 100644 --- a/tests/Stubs/MagicActiveRecord/Employee.php +++ b/tests/Stubs/MagicActiveRecord/Employee.php @@ -20,7 +20,7 @@ */ final class Employee extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'employee'; } @@ -33,7 +33,7 @@ public function getFullName(): string public function getDepartmentQuery(): ActiveQuery { return $this - ->hasOne(Department::class, [ + ->activeRecord()->hasOne(Department::class, [ 'id' => 'department_id', ]) ->inverseOf('employees') @@ -42,7 +42,7 @@ public function getDepartmentQuery(): ActiveQuery public function getDossierQuery(): ActiveQuery { - return $this->hasOne( + return $this->activeRecord()->hasOne( Dossier::class, [ 'department_id' => 'department_id', diff --git a/tests/Stubs/MagicActiveRecord/Item.php b/tests/Stubs/MagicActiveRecord/Item.php index 9ca235d99..0fa4c8503 100644 --- a/tests/Stubs/MagicActiveRecord/Item.php +++ b/tests/Stubs/MagicActiveRecord/Item.php @@ -16,13 +16,13 @@ */ final class Item extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'item'; } public function getCategoryQuery(): ActiveQuery { - return $this->hasOne(Category::class, ['id' => 'category_id']); + return $this->activeRecord()->hasOne(Category::class, ['id' => 'category_id']); } } diff --git a/tests/Stubs/MagicActiveRecord/NoExist.php b/tests/Stubs/MagicActiveRecord/NoExist.php index 8af4b385b..2d92df101 100644 --- a/tests/Stubs/MagicActiveRecord/NoExist.php +++ b/tests/Stubs/MagicActiveRecord/NoExist.php @@ -8,7 +8,7 @@ final class NoExist extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'NoExist'; } diff --git a/tests/Stubs/MagicActiveRecord/NullValues.php b/tests/Stubs/MagicActiveRecord/NullValues.php index 637b668ad..95a42f213 100644 --- a/tests/Stubs/MagicActiveRecord/NullValues.php +++ b/tests/Stubs/MagicActiveRecord/NullValues.php @@ -17,7 +17,7 @@ */ final class NullValues extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'null_values'; } diff --git a/tests/Stubs/MagicActiveRecord/Order.php b/tests/Stubs/MagicActiveRecord/Order.php index 00276d823..fb163a194 100644 --- a/tests/Stubs/MagicActiveRecord/Order.php +++ b/tests/Stubs/MagicActiveRecord/Order.php @@ -23,19 +23,19 @@ class Order extends MagicActiveRecord private string|int|null $virtualCustomerId = null; - public function getTableName(): string + public function tableName(): string { return self::TABLE_NAME; } public function getCreated_at(): DateTimeImmutable { - return DateTimeImmutable::createFromFormat('U', (string) $this->get('created_at')); + return DateTimeImmutable::createFromFormat('U', (string) $this->activeRecord()->get('created_at')); } public function setCreated_at(DateTimeInterface|int $createdAt): void { - $this->set('created_at', $createdAt instanceof DateTimeInterface + $this->activeRecord()->set('created_at', $createdAt instanceof DateTimeInterface ? $createdAt->getTimestamp() : $createdAt); } @@ -47,22 +47,22 @@ public function setVirtualCustomerId(string|int|null $virtualCustomerId = null): public function getVirtualCustomerQuery() { - return $this->hasOne(Customer::class, ['id' => 'virtualCustomerId']); + return $this->activeRecord()->hasOne(Customer::class, ['id' => 'virtualCustomerId']); } public function getCustomerQuery(): ActiveQuery { - return $this->hasOne(Customer::class, ['id' => 'customer_id']); + return $this->activeRecord()->hasOne(Customer::class, ['id' => 'customer_id']); } public function getCustomerJoinedWithProfileQuery(): ActiveQuery { - return $this->hasOne(Customer::class, ['id' => 'customer_id'])->joinWith('profile'); + return $this->activeRecord()->hasOne(Customer::class, ['id' => 'customer_id'])->joinWith('profile'); } public function getCustomerJoinedWithProfileIndexOrderedQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Customer::class, ['id' => 'customer_id'] )->joinWith('profile')->orderBy(['profile.description' => SORT_ASC])->indexBy('name'); @@ -70,22 +70,22 @@ public function getCustomerJoinedWithProfileIndexOrderedQuery(): ActiveQuery public function getCustomer2Query(): ActiveQuery { - return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders2'); + return $this->activeRecord()->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders2'); } public function getOrderItemsQuery(): ActiveQuery { - return $this->hasMany(OrderItem::class, ['order_id' => 'id']); + return $this->activeRecord()->hasMany(OrderItem::class, ['order_id' => 'id']); } public function getOrderItems2Query(): ActiveQuery { - return $this->hasMany(OrderItem::class, ['order_id' => 'id'])->indexBy('item_id'); + return $this->activeRecord()->hasMany(OrderItem::class, ['order_id' => 'id'])->indexBy('item_id'); } public function getOrderItems3Query(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( OrderItem::class, ['order_id' => 'id'] )->indexBy(fn ($row) => $row['order_id'] . '_' . $row['item_id']); @@ -93,24 +93,24 @@ public function getOrderItems3Query(): ActiveQuery public function getOrderItemsWithNullFKQuery(): ActiveQuery { - return $this->hasMany(OrderItemWithNullFK::class, ['order_id' => 'id']); + return $this->activeRecord()->hasMany(OrderItemWithNullFK::class, ['order_id' => 'id']); } public function getItemsQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { // additional query configuration })->orderBy('item.id'); } public function getItemsIndexedQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems')->indexBy('id'); + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems')->indexBy('id'); } public function getItemsWithNullFKQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->viaTable('order_item_with_null_fk', ['order_id' => 'id']); @@ -118,26 +118,26 @@ public function getItemsWithNullFKQuery(): ActiveQuery public function getItemsInOrder1Query(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { $q->orderBy(['subtotal' => SORT_ASC]); })->orderBy('name'); } public function getItemsInOrder2Query(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', static function ($q) { $q->orderBy(['subtotal' => SORT_DESC]); })->orderBy('name'); } public function getBooksQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems')->where(['category_id' => 1]); + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems')->where(['category_id' => 1]); } public function getBooksWithNullFKQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->via('orderItemsWithNullFK')->where(['category_id' => 1]); @@ -145,7 +145,7 @@ public function getBooksWithNullFKQuery(): ActiveQuery public function getBooksViaTableQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->viaTable('order_item', ['order_id' => 'id'])->where(['category_id' => 1]); @@ -153,7 +153,7 @@ public function getBooksViaTableQuery(): ActiveQuery public function getBooksWithNullFKViaTableQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->viaTable('order_item_with_null_fk', ['order_id' => 'id'])->where(['category_id' => 1]); @@ -161,7 +161,7 @@ public function getBooksWithNullFKViaTableQuery(): ActiveQuery public function getBooks2Query(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->onCondition(['category_id' => 1])->viaTable('order_item', ['order_id' => 'id']); @@ -169,7 +169,7 @@ public function getBooks2Query(): ActiveQuery public function getBooksExplicitQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->onCondition(['category_id' => 1])->viaTable('order_item', ['order_id' => 'id']); @@ -177,7 +177,7 @@ public function getBooksExplicitQuery(): ActiveQuery public function getBooksExplicitAQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->alias('bo')->onCondition(['bo.category_id' => 1])->viaTable('order_item', ['order_id' => 'id']); @@ -185,7 +185,7 @@ public function getBooksExplicitAQuery(): ActiveQuery public function getBookItemsQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->alias('books')->onCondition(['books.category_id' => 1])->viaTable('order_item', ['order_id' => 'id']); @@ -193,7 +193,7 @@ public function getBookItemsQuery(): ActiveQuery public function getMovieItemsQuery(): ActiveQuery { - return $this->hasMany( + return $this->activeRecord()->hasMany( Item::class, ['id' => 'item_id'] )->alias('movies')->onCondition(['movies.category_id' => 2])->viaTable('order_item', ['order_id' => 'id']); @@ -201,30 +201,30 @@ public function getMovieItemsQuery(): ActiveQuery public function getLimitedItemsQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->onCondition(['item.id' => [3, 5]])->via('orderItems'); + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->onCondition(['item.id' => [3, 5]])->via('orderItems'); } public function getExpensiveItemsUsingViaWithCallableQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', function (ActiveQuery $q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', function (ActiveQuery $q) { $q->where(['>=', 'subtotal', 10]); }); } public function getCheapItemsUsingViaWithCallableQuery(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', function (ActiveQuery $q) { + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItems', function (ActiveQuery $q) { $q->where(['<', 'subtotal', 10]); }); } public function getOrderItemsFor8Query(): ActiveQuery { - return $this->hasMany(OrderItemWithNullFK::class, ['order_id' => 'id'])->andOnCondition(['subtotal' => 8.0]); + return $this->activeRecord()->hasMany(OrderItemWithNullFK::class, ['order_id' => 'id'])->andOnCondition(['subtotal' => 8.0]); } public function getItemsFor8Query(): ActiveQuery { - return $this->hasMany(Item::class, ['id' => 'item_id'])->via('orderItemsFor8'); + return $this->activeRecord()->hasMany(Item::class, ['id' => 'item_id'])->via('orderItemsFor8'); } } diff --git a/tests/Stubs/MagicActiveRecord/OrderItem.php b/tests/Stubs/MagicActiveRecord/OrderItem.php index ddcbad6df..8daa56099 100644 --- a/tests/Stubs/MagicActiveRecord/OrderItem.php +++ b/tests/Stubs/MagicActiveRecord/OrderItem.php @@ -17,7 +17,7 @@ */ final class OrderItem extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'order_item'; } @@ -26,34 +26,34 @@ public function fields(): array { $fields = parent::fields(); - $fields['order_id'] = $this->get('order_id'); - $fields['item_id'] = $this->get('item_id'); - $fields['price'] = $this->get('subtotal') / $this->get('quantity'); - $fields['quantity'] = $this->get('quantity'); - $fields['subtotal'] = $this->get('subtotal'); + $fields['order_id'] = $this->activeRecord()->get('order_id'); + $fields['item_id'] = $this->activeRecord()->get('item_id'); + $fields['price'] = $this->activeRecord()->get('subtotal') / $this->activeRecord()->get('quantity'); + $fields['quantity'] = $this->activeRecord()->get('quantity'); + $fields['subtotal'] = $this->activeRecord()->get('subtotal'); return $fields; } public function getOrderQuery(): ActiveQuery { - return $this->hasOne(Order::class, ['id' => 'order_id']); + return $this->activeRecord()->hasOne(Order::class, ['id' => 'order_id']); } public function getItemQuery(): ActiveQuery { - return $this->hasOne(Item::class, ['id' => 'item_id']); + return $this->activeRecord()->hasOne(Item::class, ['id' => 'item_id']); } public function getOrderItemCompositeWithJoinQuery(): ActiveQuery { /** relations used by testFindCompositeWithJoin() */ - return $this->hasOne(self::class, ['item_id' => 'item_id', 'order_id' => 'order_id' ])->joinWith('item'); + return $this->activeRecord()->hasOne(self::class, ['item_id' => 'item_id', 'order_id' => 'order_id' ])->joinWith('item'); } public function getOrderItemCompositeNoJoinQuery(): ActiveQuery { - return $this->hasOne(self::class, ['item_id' => 'item_id', 'order_id' => 'order_id' ]); + return $this->activeRecord()->hasOne(self::class, ['item_id' => 'item_id', 'order_id' => 'order_id' ]); } public function getCustomQuery(): ActiveQuery diff --git a/tests/Stubs/MagicActiveRecord/OrderItemWithNullFK.php b/tests/Stubs/MagicActiveRecord/OrderItemWithNullFK.php index 9247dc417..2312f8619 100644 --- a/tests/Stubs/MagicActiveRecord/OrderItemWithNullFK.php +++ b/tests/Stubs/MagicActiveRecord/OrderItemWithNullFK.php @@ -16,7 +16,7 @@ */ final class OrderItemWithNullFK extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'order_item_with_null_fk'; } diff --git a/tests/Stubs/MagicActiveRecord/OrderWithNullFK.php b/tests/Stubs/MagicActiveRecord/OrderWithNullFK.php index 871c3f4ff..0420c82bd 100644 --- a/tests/Stubs/MagicActiveRecord/OrderWithNullFK.php +++ b/tests/Stubs/MagicActiveRecord/OrderWithNullFK.php @@ -16,7 +16,7 @@ */ final class OrderWithNullFK extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'order_with_null_fk'; } diff --git a/tests/Stubs/MagicActiveRecord/Profile.php b/tests/Stubs/MagicActiveRecord/Profile.php index 16e3f4c16..5183a1506 100644 --- a/tests/Stubs/MagicActiveRecord/Profile.php +++ b/tests/Stubs/MagicActiveRecord/Profile.php @@ -16,7 +16,7 @@ final class Profile extends MagicActiveRecord { public const TABLE_NAME = 'profile'; - public function getTableName(): string + public function tableName(): string { return self::TABLE_NAME; } diff --git a/tests/Stubs/MagicActiveRecord/ProfileWithConstructor.php b/tests/Stubs/MagicActiveRecord/ProfileWithConstructor.php index 09376212f..e802bd010 100644 --- a/tests/Stubs/MagicActiveRecord/ProfileWithConstructor.php +++ b/tests/Stubs/MagicActiveRecord/ProfileWithConstructor.php @@ -21,7 +21,7 @@ public function __construct(ConnectionInterface $db, private Aliases $aliases) parent::__construct($db); } - public function getTableName(): string + public function tableName(): string { return 'profile'; } diff --git a/tests/Stubs/MagicActiveRecord/TestTrigger.php b/tests/Stubs/MagicActiveRecord/TestTrigger.php index 584c495e4..0f7789be5 100644 --- a/tests/Stubs/MagicActiveRecord/TestTrigger.php +++ b/tests/Stubs/MagicActiveRecord/TestTrigger.php @@ -14,7 +14,7 @@ */ final class TestTrigger extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'test_trigger'; } diff --git a/tests/Stubs/MagicActiveRecord/TestTriggerAlert.php b/tests/Stubs/MagicActiveRecord/TestTriggerAlert.php index 3d5b4234b..207c6bfd7 100644 --- a/tests/Stubs/MagicActiveRecord/TestTriggerAlert.php +++ b/tests/Stubs/MagicActiveRecord/TestTriggerAlert.php @@ -14,7 +14,7 @@ */ final class TestTriggerAlert extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'test_trigger_alert'; } diff --git a/tests/Stubs/MagicActiveRecord/Type.php b/tests/Stubs/MagicActiveRecord/Type.php index 35f8674a8..b3d46fe1f 100644 --- a/tests/Stubs/MagicActiveRecord/Type.php +++ b/tests/Stubs/MagicActiveRecord/Type.php @@ -26,7 +26,7 @@ */ final class Type extends MagicActiveRecord { - public function getTableName(): string + public function tableName(): string { return 'type'; } diff --git a/tests/Stubs/MagicActiveRecord/UserAR.php b/tests/Stubs/MagicActiveRecord/UserAR.php index 75a047b71..e5527e269 100644 --- a/tests/Stubs/MagicActiveRecord/UserAR.php +++ b/tests/Stubs/MagicActiveRecord/UserAR.php @@ -12,7 +12,7 @@ final class UserAR extends MagicActiveRecord public const STATUS_ACTIVE = 10; public const ROLE_USER = 10; - public function getTableName(): string + public function tableName(): string { return '{{%bool_user}}'; } diff --git a/tests/Support/ModelFactory.php b/tests/Support/ModelFactory.php index 5e105d8ec..358b942bf 100644 --- a/tests/Support/ModelFactory.php +++ b/tests/Support/ModelFactory.php @@ -4,6 +4,8 @@ namespace Yiisoft\ActiveRecord\Tests\Support; +use Yiisoft\ActiveRecord\ActiveRecordModel; + class ModelFactory { public static function create(array $rows): array @@ -13,8 +15,10 @@ public static function create(array $rows): array foreach ($rows as $row) { $class = $row['type']; + /** @var ActiveRecordModel $model */ $model = new $class(); - $model->populateRecord($row); + $model->activeRecord()->populateRecord($row); + $model->initialize(); $models[] = $model; }