comparison core/modules/jsonapi/src/Query/OffsetPage.php @ 5:12f9dff5fda9 tip

Update to Drupal core 8.7.1
author Chris Cannam
date Thu, 09 May 2019 15:34:47 +0100
parents
children
comparison
equal deleted inserted replaced
4:a9cd425dd02b 5:12f9dff5fda9
1 <?php
2
3 namespace Drupal\jsonapi\Query;
4
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Http\Exception\CacheableBadRequestHttpException;
7
8 /**
9 * Value object for containing the requested offset and page parameters.
10 *
11 * @internal JSON:API maintains no PHP API since its API is the HTTP API. This
12 * class may change at any time and this will break any dependencies on it.
13 *
14 * @see https://www.drupal.org/project/jsonapi/issues/3032787
15 * @see jsonapi.api.php
16 */
17 class OffsetPage {
18
19 /**
20 * The JSON:API pagination key name.
21 *
22 * @var string
23 */
24 const KEY_NAME = 'page';
25
26 /**
27 * The offset key in the page parameter: page[offset].
28 *
29 * @var string
30 */
31 const OFFSET_KEY = 'offset';
32
33 /**
34 * The size key in the page parameter: page[limit].
35 *
36 * @var string
37 */
38 const SIZE_KEY = 'limit';
39
40 /**
41 * Default offset.
42 *
43 * @var int
44 */
45 const DEFAULT_OFFSET = 0;
46
47 /**
48 * Max size.
49 *
50 * @var int
51 */
52 const SIZE_MAX = 50;
53
54 /**
55 * The offset for the query.
56 *
57 * @var int
58 */
59 protected $offset;
60
61 /**
62 * The size of the query.
63 *
64 * @var int
65 */
66 protected $size;
67
68 /**
69 * Instantiates an OffsetPage object.
70 *
71 * @param int $offset
72 * The query offset.
73 * @param int $size
74 * The query size limit.
75 */
76 public function __construct($offset, $size) {
77 $this->offset = $offset;
78 $this->size = $size;
79 }
80
81 /**
82 * Returns the current offset.
83 *
84 * @return int
85 * The query offset.
86 */
87 public function getOffset() {
88 return $this->offset;
89 }
90
91 /**
92 * Returns the page size.
93 *
94 * @return int
95 * The requested size of the query result.
96 */
97 public function getSize() {
98 return $this->size;
99 }
100
101 /**
102 * Creates an OffsetPage object from a query parameter.
103 *
104 * @param mixed $parameter
105 * The `page` query parameter from the Symfony request object.
106 *
107 * @return \Drupal\jsonapi\Query\OffsetPage
108 * An OffsetPage object with defaults.
109 */
110 public static function createFromQueryParameter($parameter) {
111 if (!is_array($parameter)) {
112 $cacheability = (new CacheableMetadata())->addCacheContexts(['url.query_args:page']);
113 throw new CacheableBadRequestHttpException($cacheability, 'The page parameter needs to be an array.');
114 }
115
116 $expanded = $parameter + [
117 static::OFFSET_KEY => static::DEFAULT_OFFSET,
118 static::SIZE_KEY => static::SIZE_MAX,
119 ];
120
121 if ($expanded[static::SIZE_KEY] > static::SIZE_MAX) {
122 $expanded[static::SIZE_KEY] = static::SIZE_MAX;
123 }
124
125 return new static($expanded[static::OFFSET_KEY], $expanded[static::SIZE_KEY]);
126 }
127
128 }