Files
kiri-core/Database/Base/CollectionIterator.php
T

73 lines
1.2 KiB
PHP
Raw Normal View History

2020-09-08 00:49:15 +08:00
<?php
2020-10-29 18:17:25 +08:00
declare(strict_types=1);
2020-09-08 00:49:15 +08:00
namespace Database\Base;
2020-09-08 01:21:07 +08:00
use Database\ActiveQuery;
2020-09-08 00:49:15 +08:00
use Database\ActiveRecord;
2020-09-08 01:13:09 +08:00
use ReflectionException;
2020-09-08 00:57:42 +08:00
use Snowflake\Exception\NotFindClassException;
use Snowflake\Snowflake;
2020-09-08 00:49:15 +08:00
/**
* Class CollectionIterator
* @package Database\Base
*/
class CollectionIterator extends \ArrayIterator
{
2020-10-29 18:17:25 +08:00
private ActiveRecord $model;
2020-09-08 00:49:15 +08:00
2020-09-08 01:21:07 +08:00
/** @var ActiveQuery */
2020-10-29 18:17:25 +08:00
private ActiveQuery $query;
2020-09-08 01:21:07 +08:00
2020-09-08 00:57:42 +08:00
/**
* CollectionIterator constructor.
* @param $model
2020-09-08 01:21:07 +08:00
* @param $query
2020-09-08 00:57:42 +08:00
* @param array $array
* @param int $flags
* @throws NotFindClassException
2020-09-08 01:21:07 +08:00
* @throws ReflectionException
2020-09-08 00:57:42 +08:00
*/
2020-09-08 01:21:07 +08:00
public function __construct($model, $query, $array = array(), $flags = 0)
2020-09-08 00:49:15 +08:00
{
$this->model = $model;
2020-09-08 00:57:42 +08:00
if (is_string($model)) {
$this->model = Snowflake::createObject($model);
}
2020-09-08 01:21:07 +08:00
$this->query = $query;
2020-09-08 00:49:15 +08:00
parent::__construct($array, $flags);
}
2020-09-08 01:13:09 +08:00
/**
* @param $current
* @return ActiveRecord
*/
protected function newModel($current)
{
return (clone $this->model)->setAttributes($current);
2020-09-08 01:21:07 +08:00
2020-09-08 01:13:09 +08:00
}
2020-09-08 00:49:15 +08:00
/**
* @return ActiveRecord|mixed
*/
public function current()
{
2020-09-08 01:13:09 +08:00
$current = parent::current();
2020-09-08 01:21:07 +08:00
if (!($current instanceof ActiveRecord)) {
$current = $this->newModel($current);
2020-09-08 01:13:09 +08:00
}
2020-09-08 01:21:07 +08:00
return $this->query->getWith($current);
2020-09-08 00:49:15 +08:00
}
}