Passed
Push — master ( c20b86...cc4f3c )
by Kévin
03:14
created

Pagination::getPage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 13
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\DataProvider;
15
16
use ApiPlatform\Core\Exception\InvalidArgumentException;
17
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
18
19
/**
20
 * Pagination configuration.
21
 *
22
 * @author Baptiste Meyer <[email protected]>
23
 */
24
final class Pagination
25
{
26
    private $options;
27
    private $resourceMetadataFactory;
28
29
    public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, array $options = [])
30
    {
31
        $this->resourceMetadataFactory = $resourceMetadataFactory;
32
        $this->options = array_merge([
33
            'enabled' => true,
34
            'client_enabled' => false,
35
            'client_items_per_page' => false,
36
            'items_per_page' => 30,
37
            'page_default' => 1,
38
            'page_parameter_name' => 'page',
39
            'enabled_parameter_name' => 'pagination',
40
            'items_per_page_parameter_name' => 'itemsPerPage',
41
            'maximum_items_per_page' => null,
42
            'partial' => false,
43
            'client_partial' => false,
44
            'partial_parameter_name' => 'partial',
45
        ], $options);
46
    }
47
48
    /**
49
     * Gets the current page.
50
     *
51
     * @throws InvalidArgumentException
52
     */
53
    public function getPage(array $context = []): int
54
    {
55
        $page = (int) $this->getParameterFromContext(
56
            $context,
57
            $this->options['page_parameter_name'],
58
            $this->options['page_default']
59
        );
60
61
        if (1 > $page) {
62
            throw new InvalidArgumentException('Page should not be less than 1');
63
        }
64
65
        return $page;
66
    }
67
68
    /**
69
     * Gets the current offset.
70
     */
71
    public function getOffset(string $resourceClass = null, string $operationName = null, array $context = []): int
72
    {
73
        if (($context['graphql'] ?? false) && null !== ($after = $this->getParameterFromContext($context, 'after'))) {
74
            return false === ($after = base64_decode($after, true)) ? 0 : (int) $after + 1;
75
        }
76
77
        return ($this->getPage($context) - 1) * $this->getLimit($resourceClass, $operationName, $context);
78
    }
79
80
    /**
81
     * Gets the current limit.
82
     *
83
     * @throws InvalidArgumentException
84
     */
85
    public function getLimit(string $resourceClass = null, string $operationName = null, array $context = []): int
86
    {
87
        $limit = $this->options['items_per_page'];
88
        $clientLimit = $this->options['client_items_per_page'];
89
90
        if (null !== $resourceClass) {
91
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
92
            $limit = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_items_per_page', $limit, true);
93
            $clientLimit = $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_client_items_per_page', $clientLimit, true);
94
        }
95
96
        if ($context['graphql'] ?? false) {
97
            $limit = $this->getParameterFromContext($context, 'first', $limit);
98
        }
99
100
        if ($clientLimit) {
101
            $limit = (int) $this->getParameterFromContext($context, $this->options['items_per_page_parameter_name'], $limit);
102
            $maxItemsPerPage = $this->options['maximum_items_per_page'];
103
104
            if (null !== $resourceClass) {
105
                $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
106
                $maxItemsPerPage = $resourceMetadata->getCollectionOperationAttribute($operationName, 'maximum_items_per_page', $maxItemsPerPage, true);
107
            }
108
109
            if (null !== $maxItemsPerPage && $limit > $maxItemsPerPage) {
110
                $limit = $maxItemsPerPage;
111
            }
112
        }
113
114
        if (0 > $limit) {
115
            throw new InvalidArgumentException('Limit should not be less than 0');
116
        }
117
118
        return $limit;
119
    }
120
121
    /**
122
     * Gets info about the pagination.
123
     *
124
     * Returns an array with the following info as values:
125
     *   - the page {@see Pagination::getPage()}
126
     *   - the offset {@see Pagination::getOffset()}
127
     *   - the limit {@see Pagination::getLimit()}
128
     *
129
     * @throws InvalidArgumentException
130
     */
131
    public function getPagination(string $resourceClass = null, string $operationName = null, array $context = []): array
132
    {
133
        $page = $this->getPage($context);
134
        $limit = $this->getLimit($resourceClass, $operationName, $context);
135
136
        if (0 === $limit && 1 < $page) {
137
            throw new InvalidArgumentException('Page should not be greater than 1 if limit is equal to 0');
138
        }
139
140
        return [$page, $this->getOffset($resourceClass, $operationName, $context), $limit];
141
    }
142
143
    /**
144
     * Is the pagination enabled?
145
     */
146
    public function isEnabled(string $resourceClass = null, string $operationName = null, array $context = []): bool
147
    {
148
        return $this->getEnabled($context, $resourceClass, $operationName);
149
    }
150
151
    /**
152
     * Is the partial pagination enabled?
153
     */
154
    public function isPartialEnabled(string $resourceClass = null, string $operationName = null, array $context = []): bool
155
    {
156
        return $this->getEnabled($context, $resourceClass, $operationName, true);
157
    }
158
159
    /**
160
     * Is the classic or partial pagination enabled?
161
     */
162
    private function getEnabled(array $context, string $resourceClass = null, string $operationName = null, bool $partial = false): bool
163
    {
164
        $enabled = $this->options[$partial ? 'partial' : 'enabled'];
165
        $clientEnabled = $this->options[$partial ? 'client_partial' : 'client_enabled'];
166
167
        if (null !== $resourceClass) {
168
            $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
169
            $enabled = $resourceMetadata->getCollectionOperationAttribute($operationName, $partial ? 'pagination_partial' : 'pagination_enabled', $enabled, true);
170
171
            $clientEnabled = $resourceMetadata->getCollectionOperationAttribute($operationName, $partial ? 'pagination_client_partial' : 'pagination_client_enabled', $clientEnabled, true);
172
        }
173
174
        if ($clientEnabled) {
175
            return filter_var($this->getParameterFromContext($context, $this->options[$partial ? 'partial_parameter_name' : 'enabled_parameter_name'], $enabled), FILTER_VALIDATE_BOOLEAN);
176
        }
177
178
        return $enabled;
179
    }
180
181
    /**
182
     * Gets the given pagination parameter name from the given context.
183
     */
184
    private function getParameterFromContext(array $context, string $parameterName, $default = null)
185
    {
186
        $filters = $context['filters'] ?? [];
187
188
        return array_key_exists($parameterName, $filters) ? $filters[$parameterName] : $default;
189
    }
190
}
191