Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/Internal/SortToken.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace TinyBlocks\HttpQuery\Internal;

use TinyBlocks\HttpQuery\Direction;
use TinyBlocks\HttpQuery\Exceptions\SortExpressionIsInvalid;
use TinyBlocks\HttpQuery\Order;

final readonly class SortToken
{
private function __construct(private string $field, private Direction $direction)
{
}

public static function from(string $token, string $expression): SortToken
{
$descending = str_starts_with($token, '-');
$field = $descending ? substr($token, 1) : $token;
$direction = $descending ? Direction::DESCENDING : Direction::ASCENDING;

if (preg_match('/^\w[\w.-]*$/', $field) !== 1) {
throw SortExpressionIsInvalid::from(expression: $expression);
}

return new SortToken(field: $field, direction: $direction);
}

public function toOrder(): Order
{
return Order::from(field: $this->field, direction: $this->direction);
}
}
17 changes: 5 additions & 12 deletions src/Sort.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use TinyBlocks\Collection\Collection;
use TinyBlocks\HttpQuery\Exceptions\SortExpressionIsInvalid;
use TinyBlocks\HttpQuery\Internal\SortToken;

/**
* Ordered set of sort fields parsed from a JSON:API-style sort expression.
Expand Down Expand Up @@ -37,18 +38,10 @@ public static function fromExpression(string $expression): Sort
return new Sort(orders: []);
}

$orders = array_map(static function (string $token) use ($expression): Order {
$descending = str_starts_with($token, '-');
$field = $descending ? substr($token, 1) : $token;

if (preg_match('/^\w[\w.-]*$/', $field) !== 1) {
throw SortExpressionIsInvalid::from(expression: $expression);
}

$direction = $descending ? Direction::DESCENDING : Direction::ASCENDING;

return Order::from(field: $field, direction: $direction);
}, explode(',', $trimmed));
$orders = array_map(
static fn(string $token): Order => SortToken::from(token: $token, expression: $expression)->toOrder(),
explode(',', $trimmed)
);

return new Sort(orders: $orders);
}
Expand Down