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

135 lines
1.9 KiB
PHP
Raw Normal View History

2020-08-31 12:38:32 +08:00
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/9 0009
* Time: 9:44
*/
namespace Database\Base;
2020-09-08 01:13:09 +08:00
use ArrayIterator;
use Exception;
2020-08-31 12:38:32 +08:00
use Snowflake\Abstracts\Component;
use Database\ActiveRecord;
2020-09-08 01:13:09 +08:00
use Traversable;
2020-08-31 12:38:32 +08:00
/**
* Class AbstractCollection
* @package Database\Base
*/
abstract class AbstractCollection extends Component implements \IteratorAggregate, \ArrayAccess
{
/**
* @var ActiveRecord[]
*/
protected $_item = [];
/** @var ActiveRecord */
protected $model;
2020-09-08 01:09:24 +08:00
protected $query;
2020-08-31 12:38:32 +08:00
/**
* Collection constructor.
*
2020-09-08 01:09:24 +08:00
* @param $query
2020-08-31 12:38:32 +08:00
* @param array $array
*/
2020-09-08 01:09:24 +08:00
public function __construct($query, array $array = [])
2020-08-31 12:38:32 +08:00
{
$this->_item = $array;
2020-09-08 01:09:24 +08:00
$this->query = $query;
2020-08-31 12:38:32 +08:00
parent::__construct([]);
}
/**
* @return int
*/
public function getLength()
{
return count($this->_item);
}
/**
* @param $item
*/
public function setItems($item)
{
$this->_item = $item;
}
/**
* @param $model
*/
public function setModel($model)
{
$this->model = $model;
}
/**
* @param $item
*/
public function addItem($item)
{
array_push($this->_item, $item);
}
/**
2020-09-08 01:13:09 +08:00
* @return ArrayIterator|Traversable
* @throws Exception
2020-08-31 12:38:32 +08:00
*/
public function getIterator()
{
2020-09-08 00:49:15 +08:00
return new CollectionIterator($this->model, $this->_item);
2020-08-31 12:38:32 +08:00
}
/**
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return !empty($this->_item) && isset($this->_item[$offset]);
}
/**
* @param mixed $offset
* @return mixed|null|ActiveRecord
*/
public function offsetGet($offset)
{
if (!$this->offsetExists($offset)) {
return NULL;
}
/** @var ActiveRecord $model */
return $this->_item[$offset];
}
/**
* @param mixed $offset
* @param mixed $value
*/
public function offsetSet($offset, $value)
{
$this->_item[$offset] = $value;
}
/**
* @param mixed $offset
*/
public function offsetUnset($offset)
{
if ($this->offsetExists($offset)) {
unset($this->_item[$offset]);
}
}
}