<?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\Infrastructure\Search;
use Elements\Demi\Deskline\Exception;
use Elements\Demi\Deskline\Service\Search;
use Iterator;
use Pimcore\Model\Paginator\PaginateListingInterface;
class Listing implements Iterator, PaginateListingInterface
{
protected ?Parameter $parameter = null;
protected mixed $randomSeed = null;
protected ?string $locale = null;
protected array $objects = [];
protected int $count = 0;
public function __construct(protected Search $adapter, protected int $page = 1, protected int $pageSize = 10)
{
}
public function getParameter(): Parameter
{
if (empty($this->parameter)) {
throw new Exception('parameter missing');
}
return $this->parameter;
}
public function setParameter(Parameter $parameter): void
{
if (!$parameter->getCustomOrderKey() && !$parameter->getOrderConst()) {
$parameter->setOrderConst(Parameter::ORDER_BY_NAME_ASC);
}
$this->parameter = $parameter;
}
public function count(): int
{
if (!$this->objects) {
$this->load();
}
return $this->count;
}
/**
* @inheritDoc
*/
public function getItems($page, $itemCountPerPage): array
{
if (! $this->objects) {
$this->page = $page;
$this->pageSize = $itemCountPerPage;
$this->load();
}
return $this->objects;
}
/**
* @inheritdoc
*/
public function load(): void
{
$result = $this->adapter->searchInfrastructure($this->getParameter(), $this->page, $this->pageSize, $this->getParameter()->getOrderConst(), $this->randomSeed, $this->locale, $this->getParameter()->getCustomOrderKey(), $this->getParameter()->getCustomOrder());
$this->count = $result->getTotalAmount();
$this->objects = $result->getEntries();
}
public function setObjects(array $objects): void
{
$this->objects = $objects;
}
public function getObjects(): array
{
return $this->objects;
}
public function getPaginatorAdapter(): self
{
return $this;
}
/**
* @inheritdoc
*/
public function rewind()
{
if ($this->objects === null) {
$this->load();
}
reset($this->objects);
}
public function current(): mixed
{
if ($this->objects === null) {
$this->load();
}
return current($this->objects);
}
public function key(): string|int|null
{
if ($this->objects === null) {
$this->load();
}
return key($this->objects);
}
public function next(): mixed
{
if ($this->objects === null) {
$this->load();
}
return next($this->objects);
}
public function valid(): bool
{
return $this->current() !== false;
}
}