Completed
Push — master ( ed6a4c...a3a62e )
by James Ekow Abaka
03:18
created

DataOperations::saveRecord()   C

Complexity

Conditions 10
Paths 52

Size

Total Lines 69
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 10.2918

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 69
ccs 30
cts 35
cp 0.8571
rs 6.0493
cc 10
eloc 40
nc 52
nop 2
crap 10.2918

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 10
        $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
64 10
        $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...
65 10
        $succesful = true;
66
67 10
        if (count($primaryKey) == 1) {
68 10
            $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...
69
        }
70
71
        // Assign an empty array to force a validation error for empty models
72 10
        if (empty($data)) {
73 2
            $data = [[]];
74
        }
75
76 10
        $this->driver->beginTransaction();
77
78 10
        foreach ($data as $i => $datum) {
79 10
            $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...
80 6
            $data[$i] = $datum;
81
82 6
            if (!$status['success']) {
83
                $succesful = false;
84
                $invalidFields[$i] = $status['invalid_fields'];
85
                $this->driver->rollback();
86 6
                break;
87
            }
88
        }
89
90 6
        if ($succesful) {
91 6
            $this->driver->commit();
92
        } else {
93
            $this->assignValue($this->invalidFields, $invalidFields);
94
        }
95
96 6
        $this->wrapper->setData($hasMultipleData ? $data : $data[0]);
97
98 6
        return $succesful;
99
    }
100
    
101
    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...
102
        $record = $this->wrapper->getData()[0];
103
        $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
104
        $pkSet = $this->isPrimaryKeySet($primaryKey, $record);
105
        return $this->validate(
106
            $record, $pkSet ? DataOperations::MODE_UPDATE : DataOperations::MODE_SAVE
107
        );
108
    }
109
110
    /**
111
     * Save an individual record.
112
     * 
113
     * @param array $record The record to be saved
114
     * @param type $primaryKey The primary keys of the record
115
     * @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...
116
     */
117 10
    private function saveRecord(&$record, $primaryKey) {
118
        $status = [
119 10
            'success' => true,
120
            'pk_assigned' => null,
121
            'invalid_fields' => []
122
        ];
123
124
        // Determine if the primary key of the record is set.
125 10
        $pkSet = $this->isPrimaryKeySet($primaryKey, $record);
126
127
        // Reset the data in the model to contain only the data to be saved
128 10
        $this->wrapper->setData($record);
129
130
        // Run preUpdate or preSave callbacks on models and behaviours
131 10
        if ($pkSet) {
132 2
            $this->wrapper->preUpdateCallback();
133 2
            $record = $this->wrapper->getData();
134 2
            $record = reset($record) === false ? [] : reset($record);
135
        } else {
136 8
            $this->wrapper->preSaveCallback();
137 8
            $record = $this->wrapper->getData();
138 8
            $record = reset($record) === false ? [] : reset($record);
139
        }
140
141
        // Validate the data
142 10
        $validity = $this->validate(
143 10
            $record, $pkSet ? DataOperations::MODE_UPDATE : DataOperations::MODE_SAVE
144
        );
145
146
        // Exit if data is invalid
147 10
        if ($validity !== true) {
148
            $status['invalid_fields'] = $validity;
149
            $status['success'] = false;
150
            return $status;
151
        }
152
        
153
        // Save any relationships that are attached to the data
154 10
        $relationships = $this->wrapper->getDescription()->getRelationships();
155 10
        $presentRelationships = [];
156
        
157 10
        foreach($relationships ?? [] as $model => $relationship) {
158 10
            if(isset($record[$model])) {
159
                $relationship->preSave($record, $record[$model]);
160 10
                $presentRelationships[$model] = $relationship;
161
            }
162
        }
163
        
164
        // Assign the data to the wrapper again
165 10
        $this->wrapper->setData($record);
166
167
        // Update or save the data and run post callbacks
168 10
        if ($pkSet) {
169 2
            $this->adapter->update($record);
170 2
            $this->wrapper->postUpdateCallback();
171
        } else {
172 8
            $this->adapter->insert($record);
173 4
            $keyValue = $this->driver->getLastInsertId();
174 4
            $this->wrapper->{$primaryKey[0]} = $keyValue;
175 4
            $this->wrapper->postSaveCallback($keyValue);
176
        }
177
        
178
        // Reset the data so it contains any modifications made by callbacks
179 6
        $record = $this->wrapper->getData()[0];
180 6
        foreach($presentRelationships as $model => $relationship) {
181
            $relationship->postSave($record);
182
        }        
183
184 6
        return $status;
185
    }
186
187 10
    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...
188 10
        $validator = $this->container->resolve(
189 10
            ModelValidator::class, ['model' => $this->wrapper, 'mode' => $mode]
190
        );
191 10
        $errors = [];
192
193 10
        if (!$validator->validate($data)) {
194 4
            $errors = $this->getInvalidFields();
195
        }
196 10
        $errors = $this->wrapper->onValidate($errors);
197 10
        return empty($errors) ? true : $errors;
198
    }
199
200 10
    private function isPrimaryKeySet($primaryKey, $data) {
201 10
        if (is_string($primaryKey) && ($data[$primaryKey] !== null || $data[$primaryKey] !== '')) {
202
            return true;
203
        }
204 10
        foreach ($primaryKey as $keyField) {
205 10
            if (!isset($data[$keyField]) || $data[$keyField] === null || $data[$keyField] === '') {
206 10
                return false;
207
            }
208
        }
209 2
        return true;
210
    }
211
212
    private function assignValue(&$property, $value) {
213
        if ($this->hasMultipleData) {
214
            $property = $value;
215
        } else {
216
            $property = $value[0];
217
        }
218
    }
219
220
    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...
221
        return $this->data;
222
    }
223
224 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...
225 10
        return $this->invalidFields;
226
    }
227
228
    public function isItemDeletable($primaryKey, $data) {
229
        if ($this->isPrimaryKeySet($primaryKey, $data)) {
230
            return true;
231
        } else {
232
            return false;
233
        }
234
    }
235
236
}
237