Completed
Push — master ( a30571...7a668c )
by James Ekow Abaka
02:45
created

QueryOperations::runDynamicMethod()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6.2373

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 13
cts 16
cp 0.8125
rs 8.8571
cc 6
eloc 15
nc 10
nop 1
crap 6.2373
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
class QueryOperations {
33
34
    /**
35
     *
36
     * @var RecordWrapper
37
     */
38
    private $wrapper;
39
    private $adapter;
40
    private $queryParameters;
41
    private $pendingMethod;
42
    private $dynamicMethods = [
43
        "/(?<method>filterBy)(?<variable>[A-Z][A-Za-z]+){1}/",
44
        "/(?<method>sort)(?<direction>Asc|Desc)?(By)(?<variable>[A-Z][A-Za-z]+){1}/",
45
        "/(?<method>fetch)(?<first>First)?(With)(?<variable>[A-Za-z]+)/"
46
    ];
47
    private $dataOperations;
48
    private $driver;
49
50
    /**
51
     * 
52
     * @param RecordWrapper $wrapper
53
     * @param DriverAdapter $adapter
0 ignored issues
show
Bug introduced by
There is no parameter named $adapter. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
54
     * @param DataOperations $dataOperations
55
     */
56 34
    public function __construct(RecordWrapper $wrapper, DataOperations $dataOperations, Driver $driver) {
57 34
        $this->wrapper = $wrapper;
58 34
        $this->adapter = $wrapper->getAdapter();
59 34
        $this->dataOperations = $dataOperations;
60 34
        $this->driver = $driver;
61 34
    }
62
63 24
    public function doFetch($id = null) {
64 24
        $parameters = $this->getFetchQueryParameters($id);
65 24
        $data = $this->adapter->select($parameters);
66 24
        $this->wrapper->setData($data);
67 24
        $this->resetQueryParameters();
68 24
        return $this->wrapper;
69
    }
70
71 26
    private function getFetchQueryParameters($arg, $instantiate = true) {
72 26
        if ($arg instanceof \ntentan\nibii\QueryParameters) {
73 12
            return $arg;
74
        }        
75
        
76 26
        $parameters = $this->getQueryParameters($instantiate);
77
        
78 26
        if (is_numeric($arg)) {
79 6
            $description = $this->wrapper->getDescription();
80 6
            $parameters->addFilter($description->getPrimaryKey()[0], $arg);
81 6
            $parameters->setFirstOnly(true);
82 22
        } else if (is_array($arg)) {
83 6
            foreach ($arg as $field => $value) {
84 6
                $parameters->addFilter($field, $value);
85
            }
86
        }
87
        
88 26
        return $parameters;
89
    }
90
91
    /**
92
     *
93
     * @return \ntentan\nibii\QueryParameters
94
     */
95 32
    private function getQueryParameters($instantiate = true) {
96 32
        if ($this->queryParameters === null && $instantiate) {
97 32
            $this->queryParameters = new QueryParameters($this->wrapper->getDBStoreInformation()['quoted_table']);
98
        }
99 32
        return $this->queryParameters;
100
    }
101
102 32
    private function resetQueryParameters() {
103 32
        $this->queryParameters = null;
104 32
    }
105
106 10
    public function doFetchFirst($id = null) {
107 10
        $this->getQueryParameters()->setFirstOnly(true);
108 10
        return $this->doFetch($id);
109
    }
110
111 12
    public function doFields() {
112 12
        $fields = [];
113 12
        $arguments = func_get_args();
114 12
        foreach ($arguments as $argument) {
115 12
            if (is_array($argument)) {
116 6
                $fields = array_merge($fields, $argument);
117
            } else {
118 12
                $fields[] = $argument;
119
            }
120
        }
121 12
        $this->getQueryParameters()->setFields($fields);
122 12
        return $this->wrapper;
123
    }
124
    
125
    public function doSortBy($field, $direction = 'ASC') {
126
        $this->getQueryParameters()->addSort($field, $direction);
127
    }
128
129 10
    private function getFilter($arguments) {
130 10
        if (count($arguments) == 2 && is_array($arguments[1])) {
131 2
            $filter = $arguments[0];
132 2
            $data = $arguments[1];
133
        } else {
134 10
            $filter = array_shift($arguments);
135 10
            $data = $arguments;
136
        }
137 10
        return ['filter' => $filter, 'data' => $data];
138
    }
139
140 6 View Code Duplication
    public function doFilter() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
141 6
        $arguments = func_get_args();
142 6
        $details = $this->getFilter($arguments);
143 6
        $this->getQueryParameters()->setFilter($details['filter'], $details['data']);
144 6
        return $this->wrapper;
145
    }
146
147 4 View Code Duplication
    public function doFilterBy() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148 4
        $arguments = func_get_args();
149 4
        $details = $this->getFilter($arguments);
150 4
        $this->getQueryParameters()->addFilter($details['filter'], $details['data']);
151 4
        return $this->wrapper;
152
    }
153
154 6
    public function doUpdate($data) {
155 6
        $this->driver->beginTransaction();
156 6
        $parameters = $this->getQueryParameters();
157 6
        $this->adapter->bulkUpdate($data, $parameters);
158 6
        $this->driver->commit();
159 6
        $this->resetQueryParameters();
160 6
    }
161
162 2
    public function doDelete($args = null) {
163 2
        $this->driver->beginTransaction();
164 2
        $parameters = $this->getFetchQueryParameters($args);
165
166 2
        if ($parameters === null) {
167
            $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
168
            $parameters = $this->getQueryParameters();
169
            $data = $this->wrapper->getData();
170
            $keys = [];
171
172
            foreach ($data as $datum) {
173
                if ($this->dataOperations->isItemDeletable($primaryKey, $datum)) {
174
                    $keys[] = $datum[$primaryKey[0]];
175
                }
176
            }
177
178
            $parameters->addFilter($primaryKey[0], $keys);
179
            $this->adapter->delete($parameters);
180
        } else {
181 2
            $this->adapter->delete($parameters);
182
        }
183
184 2
        $this->driver->commit();
185 2
        $this->resetQueryParameters();
186 2
    }
187
188 10
    public function runDynamicMethod($arguments) {
189 10
        $arguments = count($arguments) > 1 ? $arguments : $arguments[0];
190 10
        switch ($this->pendingMethod['method']) {
191 10
            case 'filterBy':
192 4
                $this->getQueryParameters()->addFilter(Text::deCamelize($this->pendingMethod['variable']), $arguments);
193 4
                return $this->wrapper;
194 8
            case 'sort':
195
                $this->getQueryParameters()->addSort(Text::deCamelize($this->pendingMethod['variable']), $this->pendingMethod['direction']);
196
                return $this->wrapper;
197 8
            case 'fetch':
198 8
                $parameters = $this->getQueryParameters();
199 8
                $parameters->addFilter(Text::deCamelize($this->pendingMethod['variable']), $arguments);
200 8
                if ($this->pendingMethod['first'] === 'First') {
201 8
                    $parameters->setFirstOnly(true);
202
                }
203 8
                return $this->doFetch();
204
        }
205
    }
206
207 10
    public function initDynamicMethod($method) {
208 10
        $return = false;
209
210 10
        foreach ($this->dynamicMethods as $regexp) {
211 10
            if (preg_match($regexp, $method, $matches)) {
212 10
                $return = true;
213 10
                $this->pendingMethod = $matches;
214 10
                break;
215
            }
216
        }
217
218 10
        return $return;
219
    }
220
221
    public function doCount() {
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...
222
        return $this->adapter->count($this->getQueryParameters());
223
    }
224
225
    public function doLimit($numItems) {
226
        $this->getQueryParameters()->setLimit($numItems);
227
        return $this->wrapper;
228
    }
229
230
    public function doOffset($offset) {
231
        $this->getQueryParameters()->setOffset($offset);
232
        return $this->wrapper;
233
    }
234
    
235
    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...
236
        $relationship = $this->wrapper->getDescription()->getRelationships()[$model];
237
        return $relationship->getQuery();
238
    }
239
240
}
241