Passed
Pull Request — master (#7)
by Yonel Ceruto
07:02
created

AllNodesWithPagination::createPaginator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 3
c 1
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 1
nc 1
nop 0
crap 1
1
<?php
2
/*******************************************************************************
3
 *  This file is part of the GraphQL Bundle package.
4
 *
5
 *  (c) YnloUltratech <[email protected]>
6
 *
7
 *  For the full copyright and license information, please view the LICENSE
8
 *  file that was distributed with this source code.
9
 ******************************************************************************/
10
11
namespace Ynlo\GraphQLBundle\Query\Node;
12
13
use Doctrine\ORM\Query\Expr\Orx;
14
use Doctrine\ORM\QueryBuilder;
15
use GraphQL\Error\Error;
16
use Ynlo\GraphQLBundle\Definition\Extension\PaginationDefinitionExtension;
17
use Ynlo\GraphQLBundle\Model\ConnectionInterface;
18
use Ynlo\GraphQLBundle\Model\ID;
19
use Ynlo\GraphQLBundle\Model\NodeConnection;
20
use Ynlo\GraphQLBundle\Model\NodeInterface;
21
use Ynlo\GraphQLBundle\Pagination\DoctrineCursorPaginatorInterface;
22
use Ynlo\GraphQLBundle\Pagination\DoctrineOffsetCursorPaginator;
23
use Ynlo\GraphQLBundle\Pagination\PaginationRequest;
24
25
/**
26
 * Base class to fetch nodes
27
 */
28
class AllNodesWithPagination extends AllNodes
29
{
30
    /**
31
     * @param array[] $args
32
     *
33
     * @return mixed
34
     *
35
     * @throws Error
36
     */
37 10
    public function __invoke($args = [])
38
    {
39 10
        $orderBy = $args['orderBy'] ?? [];
40 10
        $first = $args['first'] ?? null;
41 10
        $last = $args['last'] ?? null;
42 10
        $before = $args['before'] ?? null;
43 10
        $after = $args['after'] ?? null;
44 10
        $search = $args['search'] ?? null;
45 10
        $filters = $args['filters'] ?? null;
46
47 10
        $this->initialize();
48
49 10
        $qb = $this->createQuery();
50 10
        $this->applyOrderBy($qb, $orderBy);
51
52 10
        if ($this->getContext()->getRoot()) {
53 3
            $this->applyFilterByParent($qb, $this->getContext()->getRoot());
54
        }
55
56 10
        if ($search) {
57
            $this->search($qb, $search);
58
        }
59
60 10
        if ($filters) {
61
            $this->applyFilters($qb, $filters);
62
        }
63
64 10
        $this->configureQuery($qb);
65 10
        foreach ($this->extensions as $extension) {
66 4
            $extension->configureQuery($qb, $this, $this->context);
67
        }
68
69 10
        if (!$first && !$last) {
70
            $error = sprintf('You must provide a `first` or `last` value to properly paginate records in "%s" connection.', $this->queryDefinition->getName());
71
            throw new Error($error);
72
        }
73
74 10
        if ($this->queryDefinition->hasMeta('pagination')) {
75 10
            $limitAllowed = $this->queryDefinition->getMeta('pagination')['limit'];
76
77 10
            if ($first > $limitAllowed || $last > $limitAllowed) {
78
                $current = $first ?? $last;
79
                $where = $first ? 'first' : 'last';
80
                $error = sprintf(
81
                    'Requesting %s records for `%s` exceeds the `%s` limit of %s records for "%s" connection',
82
                    $current,
83
                    $this->queryDefinition->getName(),
84
                    $where,
85
                    $limitAllowed,
86
                    $this->queryDefinition->getName()
87
                );
88
                throw new Error($error);
89
            }
90
        }
91
92 10
        $paginator = $this->createPaginator();
93
94 10
        $connection = $this->createConnection();
95 10
        $paginator->paginate($qb, new PaginationRequest($first, $last, $after, $before), $connection);
96
97 10
        return $connection;
98
    }
99
100
    /**
101
     * @return ConnectionInterface
102
     */
103 10
    protected function createConnection(): ConnectionInterface
104
    {
105 10
        return new NodeConnection();
106
    }
107
108
    /**
109
     * @return DoctrineCursorPaginatorInterface
110
     */
111 10
    protected function createPaginator(): DoctrineCursorPaginatorInterface
112
    {
113 10
        return new DoctrineOffsetCursorPaginator();
114
    }
115
116
    /**
117
     * Apply advanced filters
118
     *
119
     * @param QueryBuilder $qb
120
     * @param array        $filters string to search
121
     */
122
    protected function applyFilters(QueryBuilder $qb, $filters)
123
    {
124
        $definition = $this->objectDefinition;
125
        foreach ($filters as $field => $value) {
126
            if (!$definition->hasField($field) || !$prop = $definition->getField($field)->getOriginName()) {
127
                continue;
128
            }
129
130
            $entityField = sprintf('%s.%s', $this->queryAlias, $prop);
131
132
            switch (gettype($value)) {
133
                case 'string':
134
                    $qb->andWhere($qb->expr()->eq($entityField, $qb->expr()->literal($value)));
135
                    break;
136
                case 'integer':
137
                case 'double':
138
                    $qb->andWhere($qb->expr()->eq($entityField, $value));
139
                    break;
140
                case 'boolean':
141
                    $qb->andWhere($qb->expr()->eq($entityField, (int) $value));
142
                    break;
143
                case 'array':
144
                    foreach ($value as &$val) {
145
                        if ($val instanceof ID) {
146
                            $val = (int) $val->getDatabaseId();
147
                        }
148
                    }
149
                    if (empty($value)) {
150
                        $qb->andWhere($qb->expr()->isNull($entityField));
151
                    } else {
152
                        $qb->andWhere($qb->expr()->in($entityField, $value));
153
                    }
154
                    break;
155
                case 'NULL':
156
                    $qb->andWhere($qb->expr()->isNull($entityField));
157
                    break;
158
            }
159
        }
160
    }
161
162
    /**
163
     * Filter some columns with simple string.
164
     *
165
     * @param QueryBuilder $qb
166
     * @param string       $search string to search
167
     */
168
    protected function search(QueryBuilder $qb, $search)
169
    {
170
        //search every word separate
171
        $searchArray = explode(' ', $search);
172
173
        $alias = $qb->getRootAliases()[0];
174
175
        //TODO: allow some config to customize search fields
176
        $em = $this->getManager();
177
        $metadata = $em->getClassMetadata($this->entity);
178
        $searchFields = $metadata->getFieldNames();
179
180
        if (count($searchFields) > 0) {
181
            $meta = $qb->getEntityManager()->getClassMetadata($qb->getRootEntities()[0]);
182
            foreach ($searchArray as $q) {
183
                $q = trim(rtrim($q));
184
                $id = md5($q);
185
                $orx = new Orx();
186
                foreach ($searchFields as $field) {
187
                    if (strpos($field, '.') !== false && !isset($meta->embeddedClasses[explode('.', $field)[0]])) {
188
                        $orx->add("$field LIKE :search_$id");
189
                    } else { //append current alias
190
                        $orx->add("$alias.$field LIKE :search_$id");
191
                    }
192
                }
193
                $qb->andWhere($orx);
194 3
                $qb->setParameter("search_$id", "%$q%");
195
            }
196 3
        }
197 3
    }
198 3
199
    /**
200 3
     * @param QueryBuilder  $qb
201
     * @param NodeInterface $root
202
     */
203
    protected function applyFilterByParent(QueryBuilder $qb, NodeInterface $root)
204
    {
205
        $parentField = null;
206
        if ($this->queryDefinition->hasMeta('pagination')) {
207
            $parentField = $this->queryDefinition->getMeta('pagination')['parent_field'] ?? null;
208
        }
209
        if (!$parentField) {
210 3
            throw new \RuntimeException(
211 3
                sprintf(
212
                    'Missing parent field to filter "%s" by given parent.
213
             The "parent_field" should be specified.',
214 3
                    $this->queryDefinition->getName()
215 3
                )
216 2
            );
217 2
        }
218
219 1
        if ($this->objectDefinition->hasField($parentField)) {
220 1
            $parentField = $this->objectDefinition->getField($parentField)->getOriginName();
221
        }
222 3
223
        $paramName = 'root'.mt_rand();
0 ignored issues
show
Bug introduced by
The call to mt_rand() has too few arguments starting with min. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

223
        $paramName = 'root'./** @scrutinizer ignore-call */ mt_rand();

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
224
        if ($this->queryDefinition->getMeta('pagination')['parent_relation'] === PaginationDefinitionExtension::MANY_TO_MANY) {
225
            $qb->andWhere(sprintf(':%s MEMBER OF %s.%s', $paramName, $this->queryAlias, $parentField))
226
               ->setParameter($paramName, $root);
227
        } else {
228
            $qb->andWhere(sprintf('%s.%s = :%s', $this->queryAlias, $parentField, $paramName))
229
               ->setParameter($paramName, $root);
230
        }
231
    }
232
}
233