Files
kiri-databases/src/Base/CollectionIterator.php
T

76 lines
1.1 KiB
PHP
Raw Normal View History

2021-08-11 15:03:28 +08:00
<?php
declare(strict_types=1);
namespace Database\Base;
use Database\ActiveQuery;
2021-09-28 18:54:07 +08:00
use Database\ModelInterface;
2021-08-11 15:03:28 +08:00
use Exception;
/**
* Class CollectionIterator
* @package Database\Base
*/
class CollectionIterator extends \ArrayIterator
{
2021-11-11 03:11:41 +08:00
private ModelInterface|string $model;
2021-08-11 15:03:28 +08:00
/** @var ActiveQuery */
private ActiveQuery $query;
2021-09-28 18:54:07 +08:00
private ?ModelInterface $_clone = null;
2021-08-11 15:03:28 +08:00
public function clean()
{
unset($this->query);
}
/**
* CollectionIterator constructor.
* @param $model
* @param $query
* @param array $array
* @param int $flags
* @throws Exception
*/
public function __construct($model, $query, array $array = [], int $flags = 0)
{
$this->model = $model;
$this->query = $query;
parent::__construct($array, $flags);
}
/**
* @param $current
2021-09-28 18:54:07 +08:00
* @return ModelInterface
2021-08-11 15:03:28 +08:00
* @throws Exception
*/
2021-09-28 18:54:07 +08:00
protected function newModel($current): ModelInterface
2021-08-11 15:03:28 +08:00
{
2021-11-11 03:45:09 +08:00
return $this->model->populates($current);
2021-08-11 15:03:28 +08:00
}
/**
* @throws Exception
*/
2021-09-28 18:54:07 +08:00
public function current(): ModelInterface
2021-08-11 15:03:28 +08:00
{
if (is_array($current = parent::current())) {
$current = $this->newModel($current);
}
2021-10-19 18:27:12 +08:00
return $current;
2021-08-11 15:03:28 +08:00
}
}