QueryBuilder::getQuery()   A
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 8
nop 0
crap 4
1
<?php
2
/**
3
 * MOJEPANSTWO-API
4
 *
5
 * Copyright © 2017 pudelek.org.pl
6
 *
7
 * @license MIT License (MIT)
8
 *
9
 * For the full copyright and license information, please view source file
10
 * that is bundled with this package in the file LICENSE
11
 *
12
 * @author  Marcin Pudełek <[email protected]>
13
 */
14
declare (strict_types=1);
15
16
namespace mrcnpdlk\MojePanstwo;
17
18
19
use mrcnpdlk\MojePanstwo\Model\ModelAbstract;
20
use mrcnpdlk\MojePanstwo\Model\SearchResponse;
21
use mrcnpdlk\MojePanstwo\Model\SearchResponseItem;
22
use mrcnpdlk\MojePanstwo\Model\SearchResponseLinks;
23
24
class QueryBuilder
25
{
26
    /**
27
     * @var array
28
     */
29
    private $query = [];
30
    /**
31
     * @var string
32
     */
33
    private $sContext;
34
    /**
35
     * @var string
36
     */
37
    private $sPrefixedContext;
38
    /**
39
     * @var string|null
40
     */
41
    private $sReturnedClass;
42
43
    /**
44
     * QueryBuilder constructor.
45
     *
46
     * @param string|null $returnedClass
47
     *
48
     * @throws \mrcnpdlk\MojePanstwo\Exception
49
     */
50 8
    private function __construct(string $returnedClass)
51
    {
52 8
        if (!class_exists($returnedClass)) {
53
            throw new Exception(sprintf('Cannot create QueryBuilder instance. Class [%s] not defined', $returnedClass));
54
        }
55 8
        $reflectionA = new \ReflectionClass($returnedClass);
56 8
        if (!$reflectionA->isSubclassOf(ModelAbstract::class)) {
57
            throw new Exception(sprintf('Cannot create QueryBuilder instance. Class [%s] not extend ModelAbstract', $returnedClass));
58
        }
59
60 8
        $this->query['conditions'] = [];
61 8
        $this->query['order']      = null;
62 8
        $this->query['page']       = null;
63 8
        $this->query['limit']      = null;
64 8
        $this->sReturnedClass      = $returnedClass;
65
        /** @noinspection PhpUndefinedFieldInspection */
66 8
        $this->sContext         = $returnedClass::CONTEXT;
67 8
        $this->sPrefixedContext = '/dane/' . $this->sContext;
68 8
    }
69
70
    /**
71
     * @param string|null $returnedClass
72
     *
73
     * @return \mrcnpdlk\MojePanstwo\QueryBuilder
74
     */
75 8
    public static function create(string $returnedClass): QueryBuilder
76
    {
77 8
        return new QueryBuilder($returnedClass);
78
    }
79
80
    /**
81
     * @param string $layerName
82
     *
83
     * @return $this
84
     */
85
    public function addLayer(string $layerName)
86
    {
87
        $this->query['layers'][] = $layerName;
88
89
        return $this;
90
    }
91
92
    /**
93
     * Find object having ID
94
     *
95
     * @param string|int $id
96
     *
97
     * @return mixed
98
     * @throws \mrcnpdlk\MojePanstwo\Exception
99
     */
100 2
    public function find($id)
101
    {
102 2
        $res = Api::getInstance()
103 2
                  ->getClient()
104 2
                  ->request($this->sPrefixedContext, (string)$id, $this)
105
        ;
106
107 1
        return new $this->sReturnedClass($res->data ?? null, $res->layers ?? null);
108
    }
109
110
    /**
111
     * Search result
112
     *
113
     * @return SearchResponse
114
     * @throws \mrcnpdlk\MojePanstwo\Exception
115
     */
116 6
    public function get(): SearchResponse
117
    {
118
119 6
        $res    = Api::getInstance()
120 6
                     ->getClient()
121 6
                     ->request($this->sPrefixedContext, null, $this)
122
        ;
123 6
        $oLinks = new SearchResponseLinks(
124 6
            $res->Links->self ?? null,
125 6
            $res->Links->first ?? $res->Links->self ?? null,
126 6
            $res->Links->next ?? null,
127 6
            $res->Links->last ?? null,
128 6
            $res->Links->prev ?? null
129
        );
130 6
        $items  = [];
131 6
        foreach ((array)$res->Dataobject as $i) {
132 6
            $oItem             = new SearchResponseItem();
133 6
            $oItem->id         = (int)$i->id;
0 ignored issues
show
Documentation Bug introduced by
The property $id was declared of type string, but (int) $i->id is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
134 6
            $oItem->dataset    = $i->dataset;
135 6
            $oItem->url        = $i->url;
136 6
            $oItem->mp_url     = $i->mp_url;
137 6
            $oItem->schema_url = $i->schema_url;
138 6
            $oItem->global_id  = (int)$i->global_id;
0 ignored issues
show
Documentation Bug introduced by
The property $global_id was declared of type string, but (int) $i->global_id is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
139 6
            $oItem->slug       = $i->slug;
140 6
            $oItem->score      = $i->score;
141 6
            $oItem->data       = new $this->sReturnedClass($i->data ?? null);
142 6
            $items[]           = $oItem;
143
        }
144
145 6
        return new SearchResponse($res->Count, $res->Took, $oLinks, $items);
146
    }
147
148
    /**
149
     * Return params as formatted string
150
     *
151
     * @return string
152
     */
153 8
    public function getQuery(): string
154
    {
155 8
        if (empty($this->query['order'])) {
156 8
            unset($this->query['order']);
157
        }
158 8
        if (empty($this->query['page'])) {
159 8
            unset($this->query['page']);
160
        }
161 8
        if (empty($this->query['limit'])) {
162 2
            unset($this->query['limit']);
163
        }
164
165 8
        return http_build_query($this->query);
166
167
    }
168
169
    /**
170
     * @param int $limit
171
     *
172
     * @return $this
173
     */
174 6
    public function limit(int $limit = 50)
175
    {
176 6
        $this->query['limit'] = $limit;
177
178 6
        return $this;
179
    }
180
181
    /**
182
     * Order by option settings
183
     *
184
     * @param string $property
185
     * @param string $order
186
     *
187
     * @return $this
188
     */
189
    public function orderBy(string $property, string $order = 'asc')
190
    {
191
        if (empty($this->sContext)) {
192
            $this->query['order'] = $property . ' ' . $order;
193
        } else {
194
            $this->query['order'] = $this->sContext . '.' . $property . ' ' . $order;
195
        }
196
197
198
        return $this;
199
    }
200
201
    /**
202
     * Get page number
203
     *
204
     * @param int $page
205
     *
206
     * @return $this
207
     */
208
    public function page(int $page = 1)
209
    {
210
        $this->query['page'] = $page < 1 ? 1 : $page;
211
212
        return $this;
213
    }
214
215
    /**
216
     * Where option settings
217
     *
218
     * @param string $property
219
     * @param        $value
220
     *
221
     * @return $this
222
     */
223
    public function where(string $property = null, $value)
224
    {
225
        if (null === $property || 'q' === $property) {
226
            return $this->whereQ($value);
227
        }
228
        if (empty($this->sContext)) {
229
            $this->query['conditions'][$property] = $value;
230
        } else {
231
            $this->query['conditions'][sprintf('%s.%s', $this->sContext, $property)] = $value;
232
        }
233
234
235
        return $this;
236
    }
237
238
    /**
239
     * Full text search WHERE
240
     *
241
     * @param $value
242
     *
243
     * @return $this
244
     */
245
    public function whereQ($value)
246
    {
247
        $this->query['conditions']['q'] = $value;
248
249
        return $this;
250
    }
251
252
}
253