107 lines
2.8 KiB
PHP
107 lines
2.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Uwil\ArcadiaApiPhpClient\Lib\Pagination;
|
|
|
|
use Uwil\ArcadiaApiPhpClient\Lib\Equatable;
|
|
|
|
/**
|
|
* Immutable value object representing a pagination range.
|
|
*/
|
|
final class Pagination implements Equatable
|
|
{
|
|
/** ERR_TOO_MANY_RECORDS fixed to 10k */
|
|
public const int MAX_PAGE_SIZE = PageSize::MAX_PAGE_SIZE;
|
|
|
|
public function __construct(
|
|
private readonly int $from,
|
|
private readonly int $to,
|
|
) {
|
|
if ($from < 0) {
|
|
throw new \InvalidArgumentException('From index must be non-negative');
|
|
}
|
|
if ($to < 0) {
|
|
throw new \InvalidArgumentException('To index must be non-negative');
|
|
}
|
|
if ($to <= $from) {
|
|
throw new \InvalidArgumentException('To index must be greater than from index');
|
|
}
|
|
if (($to - $from + 1) > self::MAX_PAGE_SIZE) {
|
|
throw new \InvalidArgumentException('Page size must be less than or equal to ' . self::MAX_PAGE_SIZE);
|
|
}
|
|
}
|
|
|
|
public function from(): int
|
|
{
|
|
return $this->from;
|
|
}
|
|
|
|
public function to(): int
|
|
{
|
|
return $this->to;
|
|
}
|
|
|
|
public function pageSize(): int
|
|
{
|
|
return $this->to - $this->from + 1;
|
|
}
|
|
|
|
public function pageNumber(): int
|
|
{
|
|
return (int) ($this->from / $this->pageSize()) + 1;
|
|
}
|
|
|
|
public function pageSizeVo(): PageSize
|
|
{
|
|
return new PageSize($this->pageSize());
|
|
}
|
|
|
|
public function pageNumberVo(): PageNumber
|
|
{
|
|
return new PageNumber($this->pageNumber());
|
|
}
|
|
|
|
public function equals(mixed $other): bool
|
|
{
|
|
return $other instanceof self && $this->from === $other->from && $this->to === $other->to;
|
|
}
|
|
|
|
public static function ofIndexes(int $from, int $to): self
|
|
{
|
|
return new self($from, $to);
|
|
}
|
|
|
|
public static function ofPage(PageNumber $pageNumber, PageSize $pageSize = new PageSize()): self
|
|
{
|
|
$fromIndex = ($pageNumber->value - 1) * $pageSize->value;
|
|
$toIndex = max($pageNumber->value * $pageSize->value - 1, 1);
|
|
|
|
return new self($fromIndex, $toIndex);
|
|
}
|
|
|
|
public static function ofOffsetAndLimit(int $offset, int $limit): self
|
|
{
|
|
if ($offset < 0) {
|
|
throw new \InvalidArgumentException('Offset must be non-negative');
|
|
}
|
|
if ($limit <= 0) {
|
|
throw new \InvalidArgumentException('Limit must be positive and non-zero');
|
|
}
|
|
|
|
$fromIndex = $offset;
|
|
$toIndex = max($offset + $limit - 1, 1);
|
|
|
|
return new self($fromIndex, $toIndex);
|
|
}
|
|
|
|
public static function firstPage(PageSize $pageSize = new PageSize()): self
|
|
{
|
|
return self::ofPage(new PageNumber(1), $pageSize);
|
|
}
|
|
|
|
public function __toString(): string
|
|
{
|
|
return sprintf('Pagination{from=%d, to=%d}', $this->from, $this->to);
|
|
}
|
|
}
|