| 1 |
<?php |
| 2 |
|
| 3 |
namespace Illuminate\Pagination; |
| 4 |
|
| 5 |
use Illuminate\Contracts\Support\Arrayable; |
| 6 |
use Illuminate\Support\Collection; |
| 7 |
use UnexpectedValueException; |
| 8 |
|
| 9 |
|
| 10 |
class Cursor implements Arrayable |
| 11 |
{ |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
protected $parameters; |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
protected $pointsToNextItems; |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
public function __construct(array $parameters, $pointsToNextItems = true) |
| 33 |
{ |
| 34 |
$this->parameters = $parameters; |
| 35 |
$this->pointsToNextItems = $pointsToNextItems; |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
public function parameter(string $parameterName) |
| 47 |
{ |
| 48 |
if (! array_key_exists($parameterName, $this->parameters)) { |
| 49 |
throw new UnexpectedValueException("Unable to find parameter [{$parameterName}] in pagination item."); |
| 50 |
} |
| 51 |
|
| 52 |
return $this->parameters[$parameterName]; |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
public function parameters(array $parameterNames) |
| 62 |
{ |
| 63 |
return (new Collection($parameterNames)) |
| 64 |
->map(fn ($parameterName) => $this->parameter($parameterName)) |
| 65 |
->toArray(); |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
public function pointsToNextItems() |
| 74 |
{ |
| 75 |
return $this->pointsToNextItems; |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
public function pointsToPreviousItems() |
| 84 |
{ |
| 85 |
return ! $this->pointsToNextItems; |
| 86 |
} |
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
public function toArray() |
| 94 |
{ |
| 95 |
return array_merge($this->parameters, [ |
| 96 |
'_pointsToNextItems' => $this->pointsToNextItems, |
| 97 |
]); |
| 98 |
} |
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
public function encode() |
| 106 |
{ |
| 107 |
return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(json_encode($this->toArray()))); |
| 108 |
} |
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
public static function fromEncoded($encodedString) |
| 117 |
{ |
| 118 |
if (! is_string($encodedString)) { |
| 119 |
return null; |
| 120 |
} |
| 121 |
|
| 122 |
$parameters = json_decode(base64_decode(str_replace(['-', '_'], ['+', '/'], $encodedString)), true); |
| 123 |
|
| 124 |
if (json_last_error() !== JSON_ERROR_NONE) { |
| 125 |
return null; |
| 126 |
} |
| 127 |
|
| 128 |
$pointsToNextItems = $parameters['_pointsToNextItems']; |
| 129 |
|
| 130 |
unset($parameters['_pointsToNextItems']); |
| 131 |
|
| 132 |
return new static($parameters, $pointsToNextItems); |
| 133 |
} |
| 134 |
} |