2020-01-28 10:49:55 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
|
|
namespace Shlinkio\Shlink\Core\Model;
|
|
|
|
|
|
|
|
|
|
use Shlinkio\Shlink\Core\Exception\ValidationException;
|
|
|
|
|
|
2021-02-02 20:21:48 +01:00
|
|
|
use function array_pad;
|
2020-09-20 13:21:21 +02:00
|
|
|
use function explode;
|
2020-01-28 10:49:55 +01:00
|
|
|
|
|
|
|
|
final class ShortUrlsOrdering
|
|
|
|
|
{
|
|
|
|
|
public const ORDER_BY = 'orderBy';
|
|
|
|
|
private const DEFAULT_ORDER_DIRECTION = 'ASC';
|
|
|
|
|
|
|
|
|
|
private ?string $orderField = null;
|
|
|
|
|
private string $orderDirection = self::DEFAULT_ORDER_DIRECTION;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @throws ValidationException
|
|
|
|
|
*/
|
|
|
|
|
public static function fromRawData(array $query): self
|
|
|
|
|
{
|
|
|
|
|
$instance = new self();
|
|
|
|
|
$instance->validateAndInit($query);
|
|
|
|
|
|
|
|
|
|
return $instance;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @throws ValidationException
|
|
|
|
|
*/
|
|
|
|
|
private function validateAndInit(array $data): void
|
|
|
|
|
{
|
|
|
|
|
$orderBy = $data[self::ORDER_BY] ?? null;
|
|
|
|
|
if ($orderBy === null) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2021-12-14 22:21:53 +01:00
|
|
|
[$field, $dir] = array_pad(explode('-', $orderBy), 2, null);
|
|
|
|
|
$this->orderField = $field;
|
|
|
|
|
$this->orderDirection = $dir ?? self::DEFAULT_ORDER_DIRECTION;
|
2020-01-28 10:49:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function orderField(): ?string
|
|
|
|
|
{
|
|
|
|
|
return $this->orderField;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function orderDirection(): string
|
|
|
|
|
{
|
|
|
|
|
return $this->orderDirection;
|
|
|
|
|
}
|
2020-01-28 11:17:54 +01:00
|
|
|
|
|
|
|
|
public function hasOrderField(): bool
|
|
|
|
|
{
|
|
|
|
|
return $this->orderField !== null;
|
|
|
|
|
}
|
2020-01-28 10:49:55 +01:00
|
|
|
}
|