<?php
namespace App\Model\Content\Media;
/**
*
*/
final class MediaCollection
implements
\ArrayAccess,
\Countable,
\Iterator,
\JsonSerializable
{
/**
* @var array|AbstractMedia[]
*/
protected array $elements;
/**
* @param array $elements
*/
public function __construct(array $elements = [])
{
$this->elements = array_map(
function ($element) {
return AbstractMedia::build($element);
},
$elements
);
}
/**
* @return AbstractMedia|null
*/
public function getFeature(): ?AbstractMedia
{
if ( ! $this->elements) {
return null;
}
foreach ($this->elements as $element) {
if ($element->isFeatured()) {
return $element;
}
}
return $this->elements[0];
}
/**
* @param int $max
* @return array|AbstractMedia[]
*/
public function getFeatures(int $max = PHP_INT_MAX): array
{
$max = max(1, $max);
if ( ! $this->elements) {
return [];
}
if (($first = $this->getFeature()) === $this->elements[0]) {
return array_slice($this->elements, 0, $max);
}
$features = [
$first,
];
foreach ($this->elements as $element) {
if (count($features) >= $max) {
break;
}
if ($element !== $first) {
$features[] = $element;
}
}
return $features;
}
/**
* @return array|AbstractMedia[]
*/
public function toArray(): array
{
return $this->elements;
}
/**
* @return array
*/
public function jsonSerialize(): array
{
return array_map(
function (AbstractMedia $element) {
return $element->jsonSerialize();
},
array_values($this->elements)
);
}
/**
* {@inheritDoc}
*/
public function offsetExists($offset): bool
{
return array_key_exists($offset, $this->elements);
}
/**
* {@inheritDoc}
*/
public function offsetGet($offset)
{
return $this->elements[$offset];
}
/**
* {@inheritDoc}
*/
public function offsetSet($offset, $value)
{
$this->elements[$offset] = ( ! $value instanceof AbstractMedia)
? AbstractMedia::build($value)
: $value;
}
/**
* {@inheritDoc}
*/
public function offsetUnset($offset)
{
unset($this->elements[$offset]);
}
/**
* {@inheritDoc}
*/
public function count(): int
{
return count($this->elements);
}
/**
* {@inheritDoc}
*/
public function current(): AbstractMedia
{
return current($this->elements);
}
/**
* {@inheritDoc}
*/
public function next(): void
{
next($this->elements);
}
/**
* {@inheritDoc}
*/
public function key(): int
{
return key($this->elements);
}
/**
* {@inheritDoc}
*/
public function valid(): bool
{
return isset($this->elements[key($this->elements)]);
}
/**
* {@inheritDoc}
*/
public function rewind(): void
{
reset($this->elements);
}
/**
* @return AbstractMedia|null
*/
public function first(): ?AbstractMedia
{
if ($this->elements) {
return $this->elements[0];
}
return null;
}
/**
* @param AbstractMedia $media
* @return $this
*/
public function append(AbstractMedia $media): self
{
$this->elements[] = $media;
return $this;
}
}