Completed
Push — master ( 798733...6762cf )
by James Ekow Abaka
01:47
created

QueryOperations::buildFetchQueryParameters()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 20
ccs 12
cts 12
cp 1
rs 8.8571
cc 5
eloc 12
nc 4
nop 2
crap 5
1
<?php
2
3
/*
4
 * The MIT License
5
 *
6
 * Copyright 2015 ekow.
7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a copy
9
 * of this software and associated documentation files (the "Software"), to deal
10
 * in the Software without restriction, including without limitation the rights
11
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
 * copies of the Software, and to permit persons to whom the Software is
13
 * furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in
16
 * all copies or substantial portions of the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
 * THE SOFTWARE.
25
 */
26
27
namespace ntentan\nibii;
28
29
use ntentan\atiaa\Driver;
30
use ntentan\utils\Text;
31
32
/**
33
 * Performs operations that query the database.
34
 *
35
 * @package ntentan\nibii
36
 */
37
class QueryOperations
38
{
39
40
    /**
41
     * An instance of the record wrapper being used.
42
     *
43
     * @var RecordWrapper
44
     */
45
    private $wrapper;
46
47
    /**
48
     * An instance of the driver adapter used in the database connection.
49
     *
50
     * @var DriverAdapter
51
     */
52
    private $adapter;
53
54
    /**
55
     * An instance of query parameters used to perform the various queries.
56
     *
57
     * @var QueryParameters
58
     */
59
    private $queryParameters;
60
61
    /**
62
     * The name of a method initialized through a dynamic method waiting to be executed.
63
     *
64
     * @var string
65
     */
66
    private $pendingMethod;
67
68
    /**
69
     * Regular expressions for matching dynamic methods.
70
     *
71
     * @var array
72
     */
73
    private $dynamicMethods = [
74
        "/(?<method>filterBy)(?<variable>[A-Z][A-Za-z]+){1}/",
75
        "/(?<method>sort)(?<direction>Asc|Desc)?(By)(?<variable>[A-Z][A-Za-z]+){1}/",
76
        "/(?<method>fetch)(?<first>First)?(With)(?<variable>[A-Za-z]+)/"
77
    ];
78
79
    /**
80
     * An instance of the DataOperations class used for filtered deletes.
81
     *
82
     * @var DataOperations
83
     */
84
    private $dataOperations;
85
86
    /**
87
     * An instance of the Driver class used for establishing database connections.
88
     *
89
     * @var Driver
90
     */
91
    private $driver;
92
93
    /**
94
     * QueryOperations constructor
95
     *
96
     * @param RecordWrapper $wrapper
97
     * @param DataOperations $dataOperations
98
     * @param Driver $driver
99
     * @internal param DriverAdapter $adapter
100
     */
101 34
    public function __construct(RecordWrapper $wrapper, DataOperations $dataOperations, Driver $driver)
102
    {
103 34
        $this->wrapper = $wrapper;
104 34
        $this->adapter = $wrapper->getAdapter();
105 34
        $this->dataOperations = $dataOperations;
106 34
        $this->driver = $driver;
107 34
    }
108
109
    /**
110
     * Fetches items from the database.
111
     *
112
     * @param int|array|QueryParameters $query
113
     * @return RecordWrapper
114
     */
115 24
    public function doFetch($query = null)
116
    {
117 24
        $parameters = $this->buildFetchQueryParameters($query);
118 24
        $data = $this->adapter->select($parameters);
119 24
        $this->wrapper->setData($data);
120 24
        $this->resetQueryParameters();
121 24
        return $this->wrapper;
122
    }
123
124
    /**
125
     * The method takes multiple types of arguments and converts it to a QueryParametersObject.
126
     * When this method receives null, it returns a new instance of QueryParameters. When it receives an integer, it
127
     * returns a QueryParameters object that points the primary key to the integer. When it receives an associative
128
     * array, it builds a series of conditions with array key-value pairs.
129
     *
130
     * @param int|array|QueryParameters $arg
131
     * @param bool $instantiate
132
     * @return QueryParameters
133
     */
134 26
    private function buildFetchQueryParameters($arg, $instantiate = true)
135
    {
136 26
        if ($arg instanceof QueryParameters) {
137 12
            return $arg;
138
        }
139
140 26
        $parameters = $this->getQueryParameters($instantiate);
141
142 26
        if (is_numeric($arg)) {
143 6
            $description = $this->wrapper->getDescription();
144 6
            $parameters->addFilter($description->getPrimaryKey()[0], $arg);
145 6
            $parameters->setFirstOnly(true);
146 22
        } else if (is_array($arg)) {
147 6
            foreach ($arg as $field => $value) {
148 6
                $parameters->addFilter($field, $value);
149
            }
150
        }
151
152 26
        return $parameters;
153
    }
154
155
    /**
156
     * Creates a new instance of the QueryParameters if required or just returns an already instance.
157
     *
158
     * @param bool $forceInstantiation
159
     * @return QueryParameters
160
     */
161 32
    private function getQueryParameters($forceInstantiation = true)
162
    {
163 32
        if ($this->queryParameters === null && $forceInstantiation) {
164 32
            $this->queryParameters = new QueryParameters($this->wrapper->getDBStoreInformation()['quoted_table']);
165
        }
166 32
        return $this->queryParameters;
167
    }
168
169
    /**
170
     * Clears up the query parameters.
171
     */
172 32
    private function resetQueryParameters()
173
    {
174 32
        $this->queryParameters = null;
175 32
    }
176
177
    /**
178
     * Performs the fetch operation and returns just the first item.
179
     *
180
     * @param mixed $id
181
     * @return RecordWrapper
182
     */
183 10
    public function doFetchFirst($id = null)
184
    {
185 10
        $this->getQueryParameters()->setFirstOnly(true);
186 10
        return $this->doFetch($id);
187
    }
188
189
    /**
190
     * Set the fields that should be returned for each record.
191
     *
192
     * @return RecordWrapper
193
     */
194 12
    public function doFields()
195
    {
196 12
        $fields = [];
197 12
        $arguments = func_get_args();
198 12
        foreach ($arguments as $argument) {
199 12
            if (is_array($argument)) {
200 6
                $fields = array_merge($fields, $argument);
201
            } else {
202 12
                $fields[] = $argument;
203
            }
204
        }
205 12
        $this->getQueryParameters()->setFields($fields);
206 12
        return $this->wrapper;
207
    }
208
209
    /**
210
     * Sort the query by a given field in a given directory.
211
     *
212
     * @param string $field
213
     * @param string $direction
214
     */
215
    public function doSortBy($field, $direction = 'ASC')
216
    {
217
        $this->getQueryParameters()->addSort($field, $direction);
218
    }
219
220
    /**
221
     *
222
     *
223
     * @param mixed $arguments
224
     * @return array
225
     */
226 10
    private function getFilter($arguments)
227
    {
228 10
        if (count($arguments) == 2 && is_array($arguments[1])) {
229 2
            $filter = $arguments[0];
230 2
            $data = $arguments[1];
231
        } else {
232 10
            $filter = array_shift($arguments);
233 10
            $data = $arguments;
234
        }
235 10
        return ['filter' => $filter, 'data' => $data];
236
    }
237
238 6
    public function doFilter()
239
    {
240 6
        $arguments = func_get_args();
241 6
        if(count($arguments) == 1 && is_array($arguments[0])) {
242
            foreach($arguments[0] as $field => $value) {
243
                $this->getQueryParameters()->addFilter($field, $value);
244
            }
245
        } else {
246 6
            $details = $this->getFilter($arguments);
247 6
            $this->getQueryParameters()->setFilter($details['filter'], $details['data']);
248
        }
249 6
        return $this->wrapper;
250
    }
251
252 4
    public function doFilterBy()
253
    {
254 4
        $arguments = func_get_args();
255 4
        $details = $this->getFilter($arguments);
256 4
        $this->getQueryParameters()->addFilter($details['filter'], $details['data']);
257 4
        return $this->wrapper;
258
    }
259
260 6
    public function doUpdate($data)
261
    {
262 6
        $this->driver->beginTransaction();
263 6
        $parameters = $this->getQueryParameters();
264 6
        $this->adapter->bulkUpdate($data, $parameters);
265 6
        $this->driver->commit();
266 6
        $this->resetQueryParameters();
267 6
    }
268
269 2
    public function doDelete($args = null)
270
    {
271 2
        $this->driver->beginTransaction();
272 2
        $parameters = $this->buildFetchQueryParameters($args);
273
274 2
        if ($parameters === null) {
275
            $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
276
            $parameters = $this->getQueryParameters();
277
            $data = $this->wrapper->getData();
278
            $keys = [];
279
280
            foreach ($data as $datum) {
281
                if ($this->dataOperations->isItemDeletable($primaryKey, $datum)) {
0 ignored issues
show
Documentation introduced by
$primaryKey is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
282
                    $keys[] = $datum[$primaryKey[0]];
283
                }
284
            }
285
286
            $parameters->addFilter($primaryKey[0], $keys);
287
            $this->adapter->delete($parameters);
288
        } else {
289 2
            $this->adapter->delete($parameters);
290
        }
291
292 2
        $this->driver->commit();
293 2
        $this->resetQueryParameters();
294 2
    }
295
296 10
    public function runDynamicMethod($arguments)
297
    {
298 10
        $arguments = count($arguments) > 1 ? $arguments : $arguments[0];
299 10
        switch ($this->pendingMethod['method']) {
300 10
            case 'filterBy':
301 4
                $this->getQueryParameters()->addFilter(Text::deCamelize($this->pendingMethod['variable']), $arguments);
302 4
                return $this->wrapper;
303 8
            case 'sort':
304
                $this->getQueryParameters()->addSort(Text::deCamelize($this->pendingMethod['variable']), $this->pendingMethod['direction']);
305
                return $this->wrapper;
306 8
            case 'fetch':
307 8
                $parameters = $this->getQueryParameters();
308 8
                $parameters->addFilter(Text::deCamelize($this->pendingMethod['variable']), $arguments);
309 8
                if ($this->pendingMethod['first'] === 'First') {
310 8
                    $parameters->setFirstOnly(true);
311
                }
312 8
                return $this->doFetch();
313
        }
314
    }
315
316 10
    public function initDynamicMethod($method)
317
    {
318 10
        $return = false;
319
320 10
        foreach ($this->dynamicMethods as $regexp) {
321 10
            if (preg_match($regexp, $method, $matches)) {
322 10
                $return = true;
323 10
                $this->pendingMethod = $matches;
0 ignored issues
show
Documentation Bug introduced by
It seems like $matches of type array<integer,string> is incompatible with the declared type string of property $pendingMethod.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
324 10
                break;
325
            }
326
        }
327
328 10
        return $return;
329
    }
330
331 4
    public function doCount($query = null)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
332
    {
333 4
        return $this->adapter->count($this->buildFetchQueryParameters($query));
334
    }
335
336
    public function doLimit($numItems)
337
    {
338
        $this->getQueryParameters()->setLimit($numItems);
339
        return $this->wrapper;
340
    }
341
342
    public function doOffset($offset)
343
    {
344
        $this->getQueryParameters()->setOffset($offset);
345
        return $this->wrapper;
346
    }
347
348
    public function doWith($model)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
349
    {
350
        $relationship = $this->wrapper->getDescription()->getRelationships()[$model];
351
        return $relationship->getQuery();
352
    }
353
354
}
355