Completed
Pull Request — master (#8)
by Yonel Ceruto
15:14 queued 06:25
created

AllNodesWithPagination::createConnection()   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 10
    protected function createConnection(): ConnectionInterface
101
    {
102 10
        return new NodeConnection();
103
    }
104
105 10
    protected function createPaginator(): DoctrineCursorPaginatorInterface
106
    {
107 10
        return new DoctrineOffsetCursorPaginator();
108
    }
109
110
    /**
111
     * Apply advanced filters
112
     */
113
    protected function applyFilters(QueryBuilder $qb, array $filters)
114
    {
115
        $definition = $this->objectDefinition;
116
        foreach ($filters as $field => $value) {
117
            if (!$definition->hasField($field) || !$prop = $definition->getField($field)->getOriginName()) {
118
                continue;
119
            }
120
121
            $entityField = sprintf('%s.%s', $this->queryAlias, $prop);
122
123
            switch (gettype($value)) {
124
                case 'string':
125
                    $qb->andWhere($qb->expr()->eq($entityField, $qb->expr()->literal($value)));
126
                    break;
127
                case 'integer':
128
                case 'double':
129
                    $qb->andWhere($qb->expr()->eq($entityField, $value));
130
                    break;
131
                case 'boolean':
132
                    $qb->andWhere($qb->expr()->eq($entityField, (int) $value));
133
                    break;
134
                case 'array':
135
                    foreach ($value as &$val) {
136
                        if ($val instanceof ID) {
137
                            $val = (int) $val->getDatabaseId();
138
                        }
139
                    }
140
                    if (empty($value)) {
141
                        $qb->andWhere($qb->expr()->isNull($entityField));
142
                    } else {
143
                        $qb->andWhere($qb->expr()->in($entityField, $value));
144
                    }
145
                    break;
146
                case 'NULL':
147
                    $qb->andWhere($qb->expr()->isNull($entityField));
148
                    break;
149
            }
150
        }
151
    }
152
153
    /**
154
     * Filter some columns with simple string.
155
     */
156
    protected function search(QueryBuilder $qb, string $search)
157
    {
158
        //search every word separate
159
        $searchArray = explode(' ', $search);
160
161
        $alias = $qb->getRootAliases()[0];
162
163
        //TODO: allow some config to customize search fields
164
        $em = $this->getManager();
165
        $metadata = $em->getClassMetadata($this->entity);
166
        $searchFields = $metadata->getFieldNames();
167
168
        if (count($searchFields) > 0) {
169
            $meta = $qb->getEntityManager()->getClassMetadata($qb->getRootEntities()[0]);
170
            foreach ($searchArray as $q) {
171
                $q = trim(rtrim($q));
172
                $id = md5($q);
173
                $orx = new Orx();
174
                foreach ($searchFields as $field) {
175
                    if (strpos($field, '.') !== false && !isset($meta->embeddedClasses[explode('.', $field)[0]])) {
176
                        $orx->add("$field LIKE :search_$id");
177
                    } else { //append current alias
178
                        $orx->add("$alias.$field LIKE :search_$id");
179
                    }
180
                }
181
                $qb->andWhere($orx);
182
                $qb->setParameter("search_$id", "%$q%");
183
            }
184
        }
185
    }
186
187 3
    protected function applyFilterByParent(QueryBuilder $qb, NodeInterface $root)
188
    {
189 3
        $parentField = null;
190 3
        if ($this->queryDefinition->hasMeta('pagination')) {
191 3
            $parentField = $this->queryDefinition->getMeta('pagination')['parent_field'] ?? null;
192
        }
193 3
        if (!$parentField) {
194
            throw new \RuntimeException(
195
                sprintf(
196
                    'Missing parent field to filter "%s" by given parent.
197
             The "parent_field" should be specified.',
198
                    $this->queryDefinition->getName()
199
                )
200
            );
201
        }
202
203 3
        if ($this->objectDefinition->hasField($parentField)) {
204 3
            $parentField = $this->objectDefinition->getField($parentField)->getOriginName();
205
        }
206
207 3
        $paramName = 'root'.mt_rand();
208 3
        if ($this->queryDefinition->getMeta('pagination')['parent_relation'] === PaginationDefinitionExtension::MANY_TO_MANY) {
209 2
            $qb->andWhere(sprintf(':%s MEMBER OF %s.%s', $paramName, $this->queryAlias, $parentField))
210 2
               ->setParameter($paramName, $root);
211
        } else {
212 1
            $qb->andWhere(sprintf('%s.%s = :%s', $this->queryAlias, $parentField, $paramName))
213 1
               ->setParameter($paramName, $root);
214
        }
215 3
    }
216
}
217