src/Entity/EntityStore.php
<?php
namespace Bookboon\Api\Entity;
use Bookboon\Api\Exception\UsageException;
use Countable;
use Iterator;
use JsonSerializable;
/**
* Class EntityStore
* @package Bookboon\Api\Entity
* @template T extends Entity
*/
class EntityStore implements Iterator, Countable, JsonSerializable
{
/**
* @var array<T>
*/
protected $contents;
/**
* @var int
*/
private $index = 0;
/**
* EntityStore constructor.
* @param array<T> $contents
* @psalm-param class-string<T> $classString
*/
public function __construct(array $contents = [], string $className = Entity::class)
{
$this->contents = $contents;
}
/**
* @return array<Entity>
* @psalm-return array<T>
*/
public function get() : array
{
return $this->contents;
}
/**
* @return Entity
* @psalm-return T
* @throws UsageException
*/
public function getSingle() : Entity
{
if (count($this->contents) === 1) {
return $this->contents[0];
}
throw new UsageException("Multiple responses exists");
}
/**
* Return the current element
* @link https://php.net/manual/en/iterator.current.php
* @return Entity
* @psalm-return T
* @since 5.0.0
*/
public function current()
{
return $this->contents[$this->index];
}
/**
* Move forward to next element
* @link https://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function next()
{
$this->index++;
}
/**
* Return the key of the current element
* @link https://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
* @since 5.0.0
*/
public function key()
{
return $this->index;
}
/**
* Checks if current position is valid
* @link https://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
* @since 5.0.0
*/
public function valid()
{
return isset($this->contents[$this->key()]);
}
/**
* Rewind the Iterator to the first element
* @link https://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
* @since 5.0.0
*/
public function rewind()
{
$this->index = 0;
}
/**
* Count elements of an object
* @link https://php.net/manual/en/countable.count.php
* @return int The custom count as an integer.
* </p>
* <p>
* The return value is cast to an integer.
* @since 5.1.0
*/
public function count()
{
return count($this->contents);
}
/**
* Specify data which should be serialized to JSON
* @link https://php.net/manual/en/jsonserializable.jsonserialize.php
* @return mixed data which can be serialized by <b>json_encode</b>,
* which is a value of any type other than a resource.
* @since 5.4.0
*/
public function jsonSerialize()
{
return $this->contents;
}
}