Skip to content

Commit

Permalink
refactor: improve cursor parser
Browse files Browse the repository at this point in the history
  • Loading branch information
lindyhopchris committed Aug 7, 2024
1 parent fcd5add commit adda8b8
Showing 1 changed file with 29 additions and 19 deletions.
48 changes: 29 additions & 19 deletions src/Pagination/Cursor/CursorParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,13 @@ public function encode(LaravelCursor $cursor): string
{
$key = $cursor->parameter($this->keyName);

if (!$key) {
return $cursor->encode();
if ($key) {
$parameters = $this->withoutPrivate($cursor->toArray());
$parameters[$this->keyName] = $this->idParser->encode($key);
$cursor = new LaravelCursor($parameters, $cursor->pointsToNextItems());
}

$encodedId = $this->idParser->encode($key);
$parameters = $cursor->toArray();
unset($parameters['_pointsToNextItems']);
$parameters[$this->keyName] = $encodedId;

$newCursor = new LaravelCursor($parameters, $cursor->pointsToNextItems());
return $newCursor->encode();
return $cursor->encode();
}

/**
Expand All @@ -53,25 +49,39 @@ public function encode(LaravelCursor $cursor): string
*/
public function decode(Cursor $cursor): ?LaravelCursor
{
$encodedCursor = $cursor->isBefore() ? $cursor->getBefore() : $cursor->getAfter();
if (!is_string($encodedCursor)) {
return null;
}

$parameters = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $encodedCursor)), true);
$decoded = LaravelCursor::fromEncoded(
$cursor->isBefore() ? $cursor->getBefore() : $cursor->getAfter(),
);

if (json_last_error() !== JSON_ERROR_NONE) {
if ($decoded === null) {
return null;
}

$pointsToNextItems = $parameters['_pointsToNextItems'];
unset($parameters['_pointsToNextItems']);
$parameters = $this->withoutPrivate($decoded->toArray());

if (isset($parameters[$this->keyName])) {
$parameters[$this->keyName] = $this->idParser->decode(
$parameters[$this->keyName],
);
}

return new LaravelCursor($parameters, $pointsToNextItems);
return new LaravelCursor($parameters, $decoded->pointsToNextItems());
}

/**
* @param array<string, mixed> $values
* @return array<string, mixed>
*/
private function withoutPrivate(array $values): array
{
$result = [];

foreach ($values as $key => $value) {
if (!str_starts_with($key, '_')) {
$result[$key] = $value;
}
}

return $result;
}
}

0 comments on commit adda8b8

Please sign in to comment.