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

DataOperations::validate()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 7
nc 4
nop 2
crap 3
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
31
/**
32
 * Description of DataOperations
33
 *
34
 * @author ekow
35
 */
36
class DataOperations
37
{
38
39
    private $wrapper;
40
41
    /**
42
     * Private instance of driver adapter
43
     *
44
     * @var DriverAdapter
45
     */
46
    private $adapter;
47
48
    /**
49
     *
50
     * @var array
51
     */
52
    private $data;
53
    private $invalidFields;
54
    private $hasMultipleData;
55
    private $validator;
56
    private $driver;
57
58
    const MODE_SAVE = 0;
59
    const MODE_UPDATE = 1;
60
61 34
    public function __construct(RecordWrapper $wrapper, Driver $driver)
62
    {
63 34
        $this->wrapper = $wrapper;
64 34
        $this->adapter = $wrapper->getAdapter();
65 34
        $this->driver = $driver;
66 34
    }
67
68 10
    public function doSave($hasMultipleData)
69
    {
70 10
        $this->hasMultipleData = $hasMultipleData;
71 10
        $invalidFields = [];
72 10
        $data = $this->wrapper->getData();
73
74 10
        $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
75 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...
76 10
        $succesful = true;
77
78 10
        if (count($primaryKey) == 1) {
79 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...
80
        }
81
82
        // Assign an empty array to force a validation error for empty models
83 10
        if (empty($data)) {
84 2
            $data = [[]];
85
        }
86
87 10
        $this->driver->beginTransaction();
88
89 10
        foreach ($data as $i => $datum) {
90 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...
91 10
            $data[$i] = $datum;
92
93 10
            if (!$status['success']) {
94 4
                $succesful = false;
95 4
                $invalidFields[$i] = $status['invalid_fields'];
96 4
                $this->driver->rollback();
97 10
                break;
98
            }
99
        }
100
101 10
        if ($succesful) {
102 6
            $this->driver->commit();
103
        } else {
104 4
            $this->assignValue($this->invalidFields, $invalidFields);
105
        }
106
107 10
        $this->wrapper->setData($hasMultipleData ? $data : $data[0]);
108
109 10
        return $succesful;
110
    }
111
112
    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...
113
    {
114
        $record = $this->wrapper->getData()[0];
115
        $primaryKey = $this->wrapper->getDescription()->getPrimaryKey();
116
        $pkSet = $this->isPrimaryKeySet($primaryKey, $record);
117
        return $this->validate(
118
                $record, $pkSet ? DataOperations::MODE_UPDATE : DataOperations::MODE_SAVE
119
        );
120
    }
121
122
    /**
123
     * Save an individual record.
124
     * 
125
     * @param array $record The record to be saved
126
     * @param type $primaryKey The primary keys of the record
127
     * @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...
128
     */
129 10
    private function saveRecord(&$record, $primaryKey)
130
    {
131
        $status = [
132 10
            'success' => true,
133
            'pk_assigned' => null,
134
            'invalid_fields' => []
135
        ];
136
137
        // Determine if the primary key of the record is set.
138 10
        $pkSet = $this->isPrimaryKeySet($primaryKey, $record);
139
140
        // Reset the data in the model to contain only the data to be saved
141 10
        $this->wrapper->setData($record);
142
143
        // Run preUpdate or preSave callbacks on models and behaviours
144 10
        if ($pkSet) {
145 2
            $this->wrapper->preUpdateCallback();
146 2
            $record = $this->wrapper->getData();
147 2
            $record = reset($record) === false ? [] : reset($record);
148
        } else {
149 8
            $this->wrapper->preSaveCallback();
150 8
            $record = $this->wrapper->getData();
151 8
            $record = reset($record) === false ? [] : reset($record);
152
        }
153
154
        // Validate the data
155 10
        $validity = $this->validate(
156 10
            $record, $pkSet ? DataOperations::MODE_UPDATE : DataOperations::MODE_SAVE
157
        );
158
159
        // Exit if data is invalid
160 10
        if ($validity !== true) {
161 4
            $status['invalid_fields'] = $validity;
162 4
            $status['success'] = false;
163 4
            return $status;
164
        }
165
166
        // Save any relationships that are attached to the data
167 6
        $relationships = $this->wrapper->getDescription()->getRelationships();
168 6
        $presentRelationships = [];
169
170 6
        foreach ($relationships ?? [] as $model => $relationship) {
171 6
            if (isset($record[$model])) {
172
                $relationship->preSave($record, $record[$model]);
173 6
                $presentRelationships[$model] = $relationship;
174
            }
175
        }
176
177
        // Assign the data to the wrapper again
178 6
        $this->wrapper->setData($record);
179
180
        // Update or save the data and run post callbacks
181 6
        if ($pkSet) {
182 2
            $this->adapter->update($record);
183 2
            $this->wrapper->postUpdateCallback();
184
        } else {
185 4
            $this->adapter->insert($record);
186 4
            $keyValue = $this->driver->getLastInsertId();
187 4
            $this->wrapper->{$primaryKey[0]} = $keyValue;
188 4
            $this->wrapper->postSaveCallback($keyValue);
189
        }
190
191
        // Reset the data so it contains any modifications made by callbacks
192 6
        $record = $this->wrapper->getData()[0];
193 6
        foreach ($presentRelationships as $model => $relationship) {
194
            $relationship->postSave($record);
195
        }
196
197 6
        return $status;
198
    }
199
200 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...
201
    {
202
        /*$validator = $this->container->resolve(
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
203
            ModelValidator::class, ['model' => $this->wrapper, 'mode' => $mode]
204
        );*/
205 10
        $validator = ORMContext::getInstance()->getModelValidatorFactory()->createModelValidator($this->wrapper, $mode);
206 10
        $errors = [];
207
208 10
        if (!$validator->validate($data)) {
209 4
            $errors = $validator->getInvalidFields();
210
        }
211 10
        $errors = $this->wrapper->onValidate($errors);
212 10
        return empty($errors) ? true : $errors;
213
    }
214
215 10
    private function isPrimaryKeySet($primaryKey, $data)
216
    {
217 10
        if (is_string($primaryKey) && ($data[$primaryKey] !== null || $data[$primaryKey] !== '')) {
218
            return true;
219
        }
220 10
        foreach ($primaryKey as $keyField) {
221 10
            if (!isset($data[$keyField]) || $data[$keyField] === null || $data[$keyField] === '') {
222 10
                return false;
223
            }
224
        }
225 2
        return true;
226
    }
227
228 4
    private function assignValue(&$property, $value)
229
    {
230 4
        if ($this->hasMultipleData) {
231
            $property = $value;
232
        } else {
233 4
            $property = $value[0];
234
        }
235 4
    }
236
237
    public function getData()
238
    {
239
        return $this->data;
240
    }
241
242 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...
243
    {
244 10
        return $this->invalidFields;
245
    }
246
247
    public function isItemDeletable($primaryKey, $data)
248
    {
249
        if ($this->isPrimaryKeySet($primaryKey, $data)) {
250
            return true;
251
        } else {
252
            return false;
253
        }
254
    }
255
256
}
257