diff --git a/src/ActiveRecord.php b/src/ActiveRecord.php index 0c6e7fc1b..84b0fe861 100644 --- a/src/ActiveRecord.php +++ b/src/ActiveRecord.php @@ -4,7 +4,9 @@ namespace Yiisoft\ActiveRecord; +use IteratorAggregate; use Throwable; +use Yiisoft\ActiveRecord\Trait\ArrayIteratorTrait; use Yiisoft\Db\Exception\Exception; use Yiisoft\Db\Exception\InvalidArgumentException; use Yiisoft\Db\Exception\InvalidConfigException; @@ -80,9 +82,13 @@ * * @method ActiveQuery hasMany($class, array $link) {@see BaseActiveRecord::hasMany()} for more info. * @method ActiveQuery hasOne($class, array $link) {@see BaseActiveRecord::hasOne()} for more info. + * + * @template-implements IteratorAggregate */ -class ActiveRecord extends BaseActiveRecord +class ActiveRecord extends BaseActiveRecord implements IteratorAggregate { + use ArrayIteratorTrait; + /** * The insert operation. This is mainly used when overriding {@see transactions()} to specify which operations are * transactional. diff --git a/src/BaseActiveRecord.php b/src/BaseActiveRecord.php index 9807ad6d1..8c14384fa 100644 --- a/src/BaseActiveRecord.php +++ b/src/BaseActiveRecord.php @@ -6,7 +6,6 @@ use ArrayAccess; use Closure; -use IteratorAggregate; use ReflectionException; use Throwable; use Yiisoft\Arrays\ArrayableInterface; @@ -46,9 +45,8 @@ * See {@see ActiveRecord} for a concrete implementation. * * @template-implements ArrayAccess - * @template-implements IteratorAggregate */ -abstract class BaseActiveRecord implements ActiveRecordInterface, IteratorAggregate, ArrayAccess, ArrayableInterface +abstract class BaseActiveRecord implements ActiveRecordInterface, ArrayAccess, ArrayableInterface { use ArrayableTrait; use BaseActiveRecordTrait; diff --git a/src/BaseActiveRecordTrait.php b/src/BaseActiveRecordTrait.php index d5e4c02f8..f9b153b75 100644 --- a/src/BaseActiveRecordTrait.php +++ b/src/BaseActiveRecordTrait.php @@ -5,10 +5,8 @@ namespace Yiisoft\ActiveRecord; use ArrayAccess; -use ArrayIterator; use Error; use Exception; -use IteratorAggregate; use ReflectionException; use ReflectionMethod; use Throwable; @@ -210,20 +208,6 @@ public function __set(string $name, mixed $value): void throw new UnknownPropertyException('Setting unknown property: ' . static::class . '::' . $name); } - /** - * Returns an iterator for traversing the attributes in the ActiveRecord. - * - * This method is required by the interface {@see IteratorAggregate}. - * - * @return ArrayIterator an iterator for traversing the items in the list. - */ - public function getIterator(): ArrayIterator - { - $attributes = $this->getAttributes(); - - return new ArrayIterator($attributes); - } - /** * Returns whether there is an element at the specified offset. * diff --git a/src/Trait/ArrayIteratorTrait.php b/src/Trait/ArrayIteratorTrait.php new file mode 100644 index 000000000..04115d1cd --- /dev/null +++ b/src/Trait/ArrayIteratorTrait.php @@ -0,0 +1,31 @@ +getAttributes(); + + return new ArrayIterator($attributes); + } +}