<?php
/**
* Elements DeMI
*
* This source file is available under the elements DeMI license version 1
*
* @copyright Copyright (c) elements.at New Media Solutions GmbH (https://www.elements.at/)
* @license elements DeMI Lizenz Version 1 (https://www.elements.at/de/demi-lizenz)
*/
namespace Elements\Demi\AdditionalService\Search;
use Elements\Demi\AdditionalService\Search\Adapter\Local;
use Elements\Demi\Deskline\AdditionalService\Search\Adapter;
class Listing implements \Countable, \Iterator
{
protected ?ResultSet $resultSet = null;
protected ?AbstractAdapter $adapter = null;
protected ?Parameter $parameter = null;
protected int $count = 0;
protected ?array $objects = null;
public function __construct(AbstractAdapter $adapter)
{
$this->adapter = $adapter;
}
public function setAdapter(Local|Adapter|null $adapter): void
{
$this->adapter = $adapter;
}
public function getAdapter(): Local|Adapter|null
{
return $this->adapter;
}
public function getParameter(): Parameter
{
if (!$this->parameter) {
throw new \Exception('Parameter not set.');
}
return $this->parameter;
}
public function setParameter(Parameter $parameter): void
{
$this->parameter = $parameter;
$this->adapter->setParams($parameter);
}
public function load(): void
{
$result = $this->adapter->search();
$this->count = $result->count();
$this->resultSet = $result;
$this->objects = $result->getProducts();
}
public function count(): int
{
$this->checkLoaded();
return $this->count;
}
public function checkLoaded(): void
{
$this->adapter->setParams($this->getParameter());
if ($this->objects === null) {
$this->load();
}
}
public function getItems(?int $page, ?int $itemCountPerPage): ?array
{
$this->checkLoaded();
return $this->objects;
}
public function getPaginatorAdapter(): self
{
return $this;
}
public function rewind(): void
{
$this->checkLoaded();
reset($this->objects);
}
public function current(): mixed
{
$this->checkLoaded();
return current($this->objects);
}
public function key(): string|int|null
{
$this->checkLoaded();
return key($this->objects);
}
public function next(): mixed
{
$this->checkLoaded();
return next($this->objects);
}
public function valid(): bool
{
return $this->current() !== null;
}
public function flushObjects(): void
{
$this->objects = null;
}
}