QueryOperations::doDelete()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6.3739

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 8
cts 17
cp 0.4706
rs 9.504
c 0
b 0
f 0
cc 4
nc 2
nop 1
crap 6.3739
1
<?php
2
3
/*
4
 * The MIT License
5
 *
6
 * Copyright 2014-2018 James Ekow Abaka Ainooson
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\nibii\exceptions\ModelNotFoundException;
31
use ntentan\utils\Text;
32
33
/**
34
 * Performs operations that query the database.
35
 */
36
class QueryOperations
37
{
38
    /**
39
     * An instance of the record wrapper being used.
40
     *
41
     * @var RecordWrapper
42
     */
43
    private $wrapper;
44
45
    /**
46
     * An instance of the driver adapter used in the database connection.
47
     *
48
     * @var DriverAdapter
49
     */
50
    private $adapter;
51
52
    /**
53
     * An instance of query parameters used to perform the various queries.
54
     *
55
     * @var QueryParameters
56
     */
57
    private $queryParameters;
58
59
    /**
60
     * The name of a method initialized through a dynamic method waiting to be executed.
61
     *
62
     * @var string
63
     */
64
    private $pendingMethod;
65
66
    /**
67
     * Regular expressions for matching dynamic methods.
68
     *
69
     * @var array
70
     */
71
    private $dynamicMethods = [
72
        '/(?<method>filterBy)(?<variable>[A-Z][A-Za-z]+){1}/',
73
        '/(?<method>sort)(?<direction>Asc|Desc)?(By)(?<variable>[A-Z][A-Za-z]+){1}/',
74
        '/(?<method>fetch)(?<first>First)?(With)(?<variable>[A-Za-z]+)/',
75
    ];
76
77
    /**
78
     * An instance of the DataOperations class used for filtered deletes.
79
     *
80
     * @var DataOperations
81
     */
82
    private $dataOperations;
83
84
    /**
85
     * An instance of the Driver class used for establishing database connections.
86
     *
87
     * @var Driver
88
     */
89
    private $driver;
90
91
    /**
92
     * QueryOperations constructor.
93
     *
94
     * @param RecordWrapper  $wrapper
95
     * @param DataOperations $dataOperations
96
     * @param Driver         $driver
97
     *
98
     * @internal param DriverAdapter $adapter
99
     */
100 34
    public function __construct(RecordWrapper $wrapper, DataOperations $dataOperations, Driver $driver)
101
    {
102 34
        $this->wrapper = $wrapper;
103 34
        $this->adapter = $wrapper->getAdapter();
104 34
        $this->dataOperations = $dataOperations;
105 34
        $this->driver = $driver;
106 34
    }
107
108
    /**
109
     * Fetches items from the database.
110
     *
111
     * @param int|array|QueryParameters $query
112
     *
113
     * @return RecordWrapper
0 ignored issues
show
Documentation introduced by
Should the return type not be RecordWrapper|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
114
     */
115 24
    public function doFetch($query = null)
116
    {
117 24
        $parameters = $this->buildFetchQueryParameters($query);
118 24
        $data = $this->adapter->select($parameters);
119 24
        if (empty($data)) {
120 4
            return;
121
        } else {
122 20
            $this->wrapper->setData($data);
123 20
            $this->resetQueryParameters();
124
125 20
            return $this->wrapper;
126
        }
127
    }
128
129
    /**
130
     * The method takes multiple types of arguments and converts it to a QueryParametersObject.
131
     * When this method receives null, it returns a new instance of QueryParameters. When it receives an integer, it
132
     * returns a QueryParameters object that points the primary key to the integer. When it receives an associative
133
     * array, it builds a series of conditions with array key-value pairs.
134
     *
135
     * @param int|array|QueryParameters $arg
136
     * @param bool                      $instantiate
137
     *
138
     * @return QueryParameters
139
     */
140 26
    private function buildFetchQueryParameters($arg, $instantiate = true)
141
    {
142 26
        if ($arg instanceof QueryParameters) {
143 12
            return $arg;
144
        }
145
146 26
        $parameters = $this->getQueryParameters($instantiate);
147
148 26
        if (is_numeric($arg)) {
149 6
            $description = $this->wrapper->getDescription();
150 6
            $parameters->addFilter($description->getPrimaryKey()[0], $arg);
151 6
            $parameters->setFirstOnly(true);
152 22
        } elseif (is_array($arg)) {
153 6
            foreach ($arg as $field => $value) {
154 6
                $parameters->addFilter($field, $value);
155
            }
156
        }
157
158 26
        return $parameters;
159
    }
160
161
    /**
162
     * Creates a new instance of the QueryParameters if required or just returns an already instance.
163
     *
164
     * @param bool $forceInstantiation
165
     *
166
     * @return QueryParameters
167
     */
168 32
    private function getQueryParameters($forceInstantiation = true)
169
    {
170 32
        if ($this->queryParameters === null && $forceInstantiation) {
171 32
            $this->queryParameters = new QueryParameters($this->wrapper->getDBStoreInformation()['quoted_table']);
172
        }
173
174 32
        return $this->queryParameters;
175
    }
176
177
    /**
178
     * Clears up the query parameters.
179
     */
180 28
    private function resetQueryParameters()
181
    {
182 28
        $this->queryParameters = null;
183 28
    }
184
185
    /**
186
     * Performs the fetch operation and returns just the first item.
187
     *
188
     * @param mixed $id
189
     *
190
     * @return RecordWrapper
0 ignored issues
show
Documentation introduced by
Should the return type not be RecordWrapper|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
191
     */
192 10
    public function doFetchFirst($id = null)
193
    {
194 10
        $this->getQueryParameters()->setFirstOnly(true);
195
196 10
        return $this->doFetch($id);
197
    }
198
199
    /**
200
     * Set the fields that should be returned for each record.
201
     *
202
     * @return RecordWrapper
203
     */
204 12
    public function doFields()
205
    {
206 12
        $fields = [];
207 12
        $arguments = func_get_args();
208 12
        foreach ($arguments as $argument) {
209 12
            if (is_array($argument)) {
210 6
                $fields = array_merge($fields, $argument);
211
            } else {
212 6
                $fields[] = $argument;
213
            }
214
        }
215 12
        $this->getQueryParameters()->setFields($fields);
216
217 12
        return $this->wrapper;
218
    }
219
220
    /**
221
     * Sort the query by a given field in a given directory.
222
     *
223
     * @param string $field
224
     * @param string $direction
225
     */
226
    public function doSortBy($field, $direction = 'ASC')
227
    {
228
        $this->getQueryParameters()->addSort($field, $direction);
229
    }
230
231
    /**
232
     * @param mixed $arguments
233
     *
234
     * @return array
235
     */
236 10
    private function getFilter($arguments)
237
    {
238 10
        if (count($arguments) == 2 && is_array($arguments[1])) {
239 2
            $filter = $arguments[0];
240 2
            $data = $arguments[1];
241
        } else {
242 10
            $filter = array_shift($arguments);
243 10
            $data = $arguments;
244
        }
245
246 10
        return ['filter' => $filter, 'data' => $data];
247
    }
248
249 6
    public function doFilter()
250
    {
251 6
        $arguments = func_get_args();
252 6
        if (count($arguments) == 1 && is_array($arguments[0])) {
253
            foreach ($arguments[0] as $field => $value) {
254
                $this->getQueryParameters()->addFilter($field, $value);
255
            }
256
        } else {
257 6
            $details = $this->getFilter($arguments);
258 6
            $this->getQueryParameters()->setFilter($details['filter'], $details['data']);
259
        }
260
261 6
        return $this->wrapper;
262
    }
263
264 4
    public function doFilterBy()
265
    {
266 4
        $arguments = func_get_args();
267 4
        $details = $this->getFilter($arguments);
268 4
        $this->getQueryParameters()->addFilter($details['filter'], $details['data']);
269
270 4
        return $this->wrapper;
271
    }
272
273 6
    public function doUpdate($data)
274
    {
275 6
        $this->driver->beginTransaction();
276 6
        $parameters = $this->getQueryParameters();
277 6
        $this->adapter->bulkUpdate($data, $parameters);
278 6
        $this->driver->commit();
279 6
        $this->resetQueryParameters();
280 6
    }
281
282 2
    public function doDelete($args = null)
283
    {
284 2
        $this->driver->beginTransaction();
285 2
        $parameters = $this->buildFetchQueryParameters($args);
286
287 2
        if ($parameters === null) {
288
            $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
289
            $parameters = $this->getQueryParameters();
290
            $data = $this->wrapper->getData();
291
            $keys = [];
292
293
            foreach ($data as $datum) {
294
                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...
295
                    $keys[] = $datum[$primaryKey[0]];
296
                }
297
            }
298
299
            $parameters->addFilter($primaryKey[0], $keys);
300
            $this->adapter->delete($parameters);
301
        } else {
302 2
            $this->adapter->delete($parameters);
303
        }
304
305 2
        $this->driver->commit();
306 2
        $this->resetQueryParameters();
307 2
    }
308
309 10
    public function runDynamicMethod($arguments)
310
    {
311 10
        $arguments = count($arguments) > 1 ? $arguments : ($arguments[0] ?? null);
312 10
        switch ($this->pendingMethod['method']) {
313 10
            case 'filterBy':
314 4
                $this->getQueryParameters()->addFilter(Text::deCamelize($this->pendingMethod['variable']), $arguments);
315
316 4
                return $this->wrapper;
317 8
            case 'sort':
318
                $this->getQueryParameters()->addSort(Text::deCamelize($this->pendingMethod['variable']), $this->pendingMethod['direction']);
319
320
                return $this->wrapper;
321 8
            case 'fetch':
322 8
                $parameters = $this->getQueryParameters();
323 8
                $parameters->addFilter(Text::deCamelize($this->pendingMethod['variable']), $arguments);
324 8
                if ($this->pendingMethod['first'] === 'First') {
325 8
                    $parameters->setFirstOnly(true);
326
                }
327
328 8
                return $this->doFetch();
329
        }
330
    }
331
332 10
    public function initDynamicMethod($method)
333
    {
334 10
        $return = false;
335
336 10
        foreach ($this->dynamicMethods as $regexp) {
337 10
            if (preg_match($regexp, $method, $matches)) {
338 10
                $return = true;
339 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...
340 10
                break;
341
            }
342
        }
343
344 10
        return $return;
345
    }
346
347
    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...
348
    {
349
        return $this->adapter->count($this->buildFetchQueryParameters($query));
350
    }
351
352
    public function doLimit($numItems)
353
    {
354
        $this->getQueryParameters()->setLimit($numItems);
355
356
        return $this->wrapper;
357
    }
358
359
    public function doOffset($offset)
360
    {
361
        $this->getQueryParameters()->setOffset($offset);
362
363
        return $this->wrapper;
364
    }
365
366
    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...
367
    {
368
        if (!isset($this->wrapper->getDescription()->getRelationships()[$model])) {
369
            throw new ModelNotFoundException("Could not find related model [$model]");
370
        }
371
        $relationship = $this->wrapper->getDescription()->getRelationships()[$model];
372
373
        return $relationship->getQuery();
374
    }
375
}
376