Completed
Push — master ( 551cc9...be1647 )
by James Ekow Abaka
06:35
created

DataOperations   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 208
Duplicated Lines 2.88 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 72.55%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 38
c 5
b 0
f 0
lcom 1
cbo 7
dl 6
loc 208
ccs 74
cts 102
cp 0.7255
rs 8.3999

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 6 6 1
C doSave() 0 46 8
A doValidate() 0 8 2
C saveRecord() 0 69 10
A validate() 0 12 3
B isPrimaryKeySet() 0 11 8
A assignValue() 0 7 2
A getData() 0 3 1
A getInvalidFields() 0 3 1
A isItemDeletable() 0 7 2

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
/**
30
 * Description of DataOperations
31
 *
32
 * @author ekow
33
 */
34
class DataOperations {
35
36
    private $wrapper;
37
38
    /**
39
     *
40
     * @var DriverAdapter
41
     */
42
    private $adapter;
43
    private $data;
44
    private $invalidFields;
45
    private $hasMultipleData;
46
    private $driver;
47
    private $container;
48
49
    const MODE_SAVE = 0;
50
    const MODE_UPDATE = 1;
51
52 35 View Code Duplication
    public function __construct(ORMContext $context, RecordWrapper $wrapper, DriverAdapter $adapter) {
53 35
        $this->wrapper = $wrapper;
54 35
        $this->adapter = $adapter;
55 35
        $this->driver = $context->getDbContext()->getDriver();
56 35
        $this->container = $context->getContainer();
57 35
    }
58
59 10
    public function doSave($hasMultipleData) {
60 10
        $this->hasMultipleData = $hasMultipleData;
61 10
        $invalidFields = [];
62 10
        $data = $this->wrapper->getData();
63
64 10
        if(empty($data)) {
65 2
            return true;
66
        }
67
        
68 8
        $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
69 8
        $singlePrimaryKey = null;
0 ignored issues
show
Unused Code introduced by
$singlePrimaryKey is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
70 8
        $succesful = true;
71
72 8
        if (count($primaryKey) == 1) {
73 8
            $singlePrimaryKey = $primaryKey[0];
0 ignored issues
show
Unused Code introduced by
$singlePrimaryKey is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
74
        }
75
76
        // Assign an empty array to force a validation error for empty models
77 8
        if (empty($data)) {
78
            $data = [[]];
79
        }
80
81 8
        $this->driver->beginTransaction();
82
83 8
        foreach ($data as $i => $datum) {
84 8
            $status = $this->saveRecord($datum, $primaryKey);
0 ignored issues
show
Documentation introduced by
$primaryKey is of type array, but the function expects a object<ntentan\nibii\type>.

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...
85 6
            $data[$i] = $datum;
86
87 6
            if (!$status['success']) {
88
                $succesful = false;
89
                $invalidFields[$i] = $status['invalid_fields'];
90
                $this->driver->rollback();
91 6
                break;
92
            }
93
        }
94
95 6
        if ($succesful) {
96 6
            $this->driver->commit();
97
        } else {
98
            $this->assignValue($this->invalidFields, $invalidFields);
99
        }
100
101 6
        $this->wrapper->setData($hasMultipleData ? $data : $data[0]);
102
103 6
        return $succesful;
104
    }
105
    
106
    public function doValidate() {
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...
107
        $record = $this->wrapper->getData()[0];
108
        $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
109
        $pkSet = $this->isPrimaryKeySet($primaryKey, $record);
110
        return $this->validate(
111
            $record, $pkSet ? DataOperations::MODE_UPDATE : DataOperations::MODE_SAVE
112
        );
113
    }
114
115
    /**
116
     * Save an individual record.
117
     * 
118
     * @param array $record The record to be saved
119
     * @param type $primaryKey The primary keys of the record
120
     * @return boolean
0 ignored issues
show
Documentation introduced by
Should the return type not be array?

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...
121
     */
122 8
    private function saveRecord(&$record, $primaryKey) {
123
        $status = [
124 8
            'success' => true,
125
            'pk_assigned' => null,
126
            'invalid_fields' => []
127
        ];
128
129
        // Determine if the primary key of the record is set.
130 8
        $pkSet = $this->isPrimaryKeySet($primaryKey, $record);
131
132
        // Reset the data in the model to contain only the data to be saved
133 8
        $this->wrapper->setData($record);
134
135
        // Run preUpdate or preSave callbacks on models and behaviours
136 8
        if ($pkSet) {
137 2
            $this->wrapper->preUpdateCallback();
138 2
            $record = $this->wrapper->getData();
139 2
            $record = reset($record) === false ? [] : reset($record);
140
        } else {
141 6
            $this->wrapper->preSaveCallback();
142 6
            $record = $this->wrapper->getData();
143 6
            $record = reset($record) === false ? [] : reset($record);
144
        }
145
146
        // Validate the data
147 8
        $validity = $this->validate(
148 8
            $record, $pkSet ? DataOperations::MODE_UPDATE : DataOperations::MODE_SAVE
149
        );
150
151
        // Exit if data is invalid
152 8
        if ($validity !== true) {
153
            $status['invalid_fields'] = $validity;
154
            $status['success'] = false;
155
            return $status;
156
        }
157
        
158
        // Save any relationships that are attached to the data
159 8
        $relationships = $this->wrapper->getDescription()->getRelationships();
160 8
        $presentRelationships = [];
161
        
162 8
        foreach($relationships ?? [] as $model => $relationship) {
163 8
            if(isset($record[$model])) {
164
                $relationship->preSave($record, $record[$model]);
165 8
                $presentRelationships[$model] = $relationship;
166
            }
167
        }
168
        
169
        // Assign the data to the wrapper again
170 8
        $this->wrapper->setData($record);
171
172
        // Update or save the data and run post callbacks
173 8
        if ($pkSet) {
174 2
            $this->adapter->update($record);
175 2
            $this->wrapper->postUpdateCallback();
176
        } else {
177 6
            $this->adapter->insert($record);
178 4
            $keyValue = $this->driver->getLastInsertId();
179 4
            $this->wrapper->{$primaryKey[0]} = $keyValue;
180 4
            $this->wrapper->postSaveCallback($keyValue);
181
        }
182
        
183
        // Reset the data so it contains any modifications made by callbacks
184 6
        $record = $this->wrapper->getData()[0];
185 6
        foreach($presentRelationships as $model => $relationship) {
186
            $relationship->postSave($record);
187
        }        
188
189 6
        return $status;
190
    }
191
192 8
    private function validate($data, $mode) {
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...
193 8
        $validator = $this->container->resolve(
194 8
            ModelValidator::class, ['model' => $this->wrapper, 'mode' => $mode]
195
        );
196 8
        $errors = [];
197
198 8
        if (!$validator->validate($data)) {
199 2
            $errors = $this->getInvalidFields();
200
        }
201 8
        $errors = $this->wrapper->onValidate($errors);
202 8
        return empty($errors) ? true : $errors;
203
    }
204
205 8
    private function isPrimaryKeySet($primaryKey, $data) {
206 8
        if (is_string($primaryKey) && ($data[$primaryKey] !== null || $data[$primaryKey] !== '')) {
207
            return true;
208
        }
209 8
        foreach ($primaryKey as $keyField) {
210 8
            if (!isset($data[$keyField]) || $data[$keyField] === null || $data[$keyField] === '') {
211 8
                return false;
212
            }
213
        }
214 2
        return true;
215
    }
216
217
    private function assignValue(&$property, $value) {
218
        if ($this->hasMultipleData) {
219
            $property = $value;
220
        } else {
221
            $property = $value[0];
222
        }
223
    }
224
225
    public function getData() {
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...
226
        return $this->data;
227
    }
228
229 10
    public function getInvalidFields() {
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...
230 10
        return $this->invalidFields;
231
    }
232
233
    public function isItemDeletable($primaryKey, $data) {
234
        if ($this->isPrimaryKeySet($primaryKey, $data)) {
235
            return true;
236
        } else {
237
            return false;
238
        }
239
    }
240
241
}
242