Completed
Push — master ( 7fd5f6...af8ac7 )
by James Ekow Abaka
01:40
created

QueryOperations   B

Complexity

Total Complexity 39

Size/Duplication

Total Lines 209
Duplicated Lines 8.61 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 20.49%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 39
lcom 1
cbo 10
dl 18
loc 209
ccs 25
cts 122
cp 0.2049
rs 8.2857
c 3
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
A doCount() 0 3 1
A doLimit() 0 4 1
A doOffset() 0 4 1
A __construct() 6 6 1
A doFetch() 0 7 1
A getQueryParameters() 0 6 3
A resetQueryParameters() 0 3 1
A doSortBy() 0 3 1
B doDelete() 0 25 4
A doWith() 0 4 1
B getFetchQueryParameters() 0 19 5
A doFetchFirst() 0 4 1
A doFields() 0 13 3
A getFilter() 0 10 3
A doFilter() 6 6 1
A doFilterBy() 6 6 1
A doUpdate() 0 7 1
B runDynamicMethod() 0 18 6
A initDynamicMethod() 0 13 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\utils\Text;
30
31
class QueryOperations {
32
33
    /**
34
     *
35
     * @var RecordWrapper
36
     */
37
    private $wrapper;
38
    private $adapter;
39
    private $queryParameters;
40
    private $pendingMethod;
41
    private $dynamicMethods = [
42
        "/(?<method>filterBy)(?<variable>[A-Z][A-Za-z]+){1}/",
43
        "/(?<method>sort)(?<direction>Asc|Desc)?(By)(?<variable>[A-Z][A-Za-z]+){1}/",
44
        "/(?<method>fetch)(?<first>First)?(With)(?<variable>[A-Za-z]+)/"
45
    ];
46
    private $dataOperations;
47
    private $driver;
48
49
    /**
50
     * 
51
     * @param RecordWrapper $wrapper
52
     * @param DriverAdapter $adapter
53
     * @param DataOperations $dataOperations
54
     */
55 1 View Code Duplication
    public function __construct(ORMContext $context, RecordWrapper $wrapper, DriverAdapter $adapter, $dataOperations) {
56 1
        $this->wrapper = $wrapper;
57 1
        $this->adapter = $adapter;
58 1
        $this->dataOperations = $dataOperations;
59 1
        $this->driver = $context->getDbContext()->getDriver();
60 1
    }
61
62 1
    public function doFetch($id = null) {
63 1
        $parameters = $this->getFetchQueryParameters($id);
64 1
        $data = $this->adapter->select($parameters);
65 1
        $this->wrapper->setData($data);
66 1
        $this->resetQueryParameters();
67 1
        return $this->wrapper;
68
    }
69
70 1
    private function getFetchQueryParameters($arg, $instantiate = true) {
71 1
        if ($arg instanceof \ntentan\nibii\QueryParameters) {
72
            return $arg;
73
        }        
74
        
75 1
        $parameters = $this->getQueryParameters($instantiate);
76
        
77 1
        if (is_numeric($arg)) {
78
            $description = $this->wrapper->getDescription();
79
            $parameters->addFilter($description->getPrimaryKey()[0], $arg);
80
            $parameters->setFirstOnly(true);
81 1
        } else if (is_array($arg)) {
82
            foreach ($arg as $field => $value) {
83
                $parameters->addFilter($field, $value);
84
            }
85
        }
86
        
87 1
        return $parameters;
88
    }
89
90
    /**
91
     *
92
     * @return \ntentan\nibii\QueryParameters
93
     */
94 1
    private function getQueryParameters($instantiate = true) {
95 1
        if ($this->queryParameters === null && $instantiate) {
96 1
            $this->queryParameters = new QueryParameters($this->wrapper->getDBStoreInformation()['quoted_table']);
97
        }
98 1
        return $this->queryParameters;
99
    }
100
101 1
    private function resetQueryParameters() {
102 1
        $this->queryParameters = null;
103 1
    }
104
105
    public function doFetchFirst($id = null) {
106
        $this->getQueryParameters()->setFirstOnly(true);
107
        return $this->doFetch($id);
108
    }
109
110
    public function doFields() {
111
        $fields = [];
112
        $arguments = func_get_args();
113
        foreach ($arguments as $argument) {
114
            if (is_array($argument)) {
115
                $fields = array_merge($fields, $argument);
116
            } else {
117
                $fields[] = $argument;
118
            }
119
        }
120
        $this->getQueryParameters()->setFields($fields);
121
        return $this->wrapper;
122
    }
123
    
124
    public function doSortBy($field, $direction = 'ASC') {
125
        $this->getQueryParameters()->addSort($field, $direction);
126
    }
127
128
    private function getFilter($arguments) {
129
        if (count($arguments) == 2 && is_array($arguments[1])) {
130
            $filter = $arguments[0];
131
            $data = $arguments[1];
132
        } else {
133
            $filter = array_shift($arguments);
134
            $data = $arguments;
135
        }
136
        return ['filter' => $filter, 'data' => $data];
137
    }
138
139 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...
140
        $arguments = func_get_args();
141
        $details = $this->getFilter($arguments);
142
        $this->getQueryParameters()->setFilter($details['filter'], $details['data']);
143
        return $this->wrapper;
144
    }
145
146 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...
147
        $arguments = func_get_args();
148
        $details = $this->getFilter($arguments);
149
        $this->getQueryParameters()->addFilter($details['filter'], $details['data']);
150
        return $this->wrapper;
151
    }
152
153
    public function doUpdate($data) {
154
        $this->driver->beginTransaction();
155
        $parameters = $this->getQueryParameters();
156
        $this->adapter->bulkUpdate($data, $parameters);
157
        $this->driver->commit();
158
        $this->resetQueryParameters();
159
    }
160
161
    public function doDelete($args = null) {
162
        $this->driver->beginTransaction();
163
        $parameters = $this->getFetchQueryParameters($args);
164
165
        if ($parameters === null) {
166
            $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
167
            $parameters = $this->getQueryParameters();
168
            $data = $this->wrapper->getData();
169
            $keys = [];
170
171
            foreach ($data as $datum) {
172
                if ($this->dataOperations->isItemDeletable($primaryKey, $datum)) {
173
                    $keys[] = $datum[$primaryKey[0]];
174
                }
175
            }
176
177
            $parameters->addFilter($primaryKey[0], $keys);
178
            $this->adapter->delete($parameters);
179
        } else {
180
            $this->adapter->delete($parameters);
181
        }
182
183
        $this->driver->commit();
184
        $this->resetQueryParameters();
185
    }
186
187
    public function runDynamicMethod($arguments) {
188
        $arguments = count($arguments) > 1 ? $arguments : $arguments[0];
189
        switch ($this->pendingMethod['method']) {
190
            case 'filterBy':
191
                $this->getQueryParameters()->addFilter(Text::deCamelize($this->pendingMethod['variable']), $arguments);
192
                return $this->wrapper;
193
            case 'sort':
194
                $this->getQueryParameters()->addSort(Text::deCamelize($this->pendingMethod['variable']), $this->pendingMethod['direction']);
195
                return $this->wrapper;
196
            case 'fetch':
197
                $parameters = $this->getQueryParameters();
198
                $parameters->addFilter(Text::deCamelize($this->pendingMethod['variable']), $arguments);
199
                if ($this->pendingMethod['first'] === 'First') {
200
                    $parameters->setFirstOnly(true);
201
                }
202
                return $this->doFetch();
203
        }
204
    }
205
206
    public function initDynamicMethod($method) {
207
        $return = false;
208
209
        foreach ($this->dynamicMethods as $regexp) {
210
            if (preg_match($regexp, $method, $matches)) {
211
                $return = true;
212
                $this->pendingMethod = $matches;
213
                break;
214
            }
215
        }
216
217
        return $return;
218
    }
219
220
    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...
221
        return $this->adapter->count($this->getQueryParameters());
222
    }
223
224
    public function doLimit($numItems) {
225
        $this->getQueryParameters()->setLimit($numItems);
226
        return $this->wrapper;
227
    }
228
229
    public function doOffset($offset) {
230
        $this->getQueryParameters()->setOffset($offset);
231
        return $this->wrapper;
232
    }
233
    
234
    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...
235
        $relationship = $this->wrapper->getDescription()->getRelationships()[$model];
236
        return $relationship->getQuery();
237
    }
238
239
}
240