Completed
Push — master ( 64d485...3e5573 )
by Dmitry
02:48
created

ActiveRecord::from()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Tools to use API as ActiveRecord for Yii2
4
 *
5
 * @link      https://github.com/hiqdev/yii2-hiart
6
 * @package   yii2-hiart
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\hiart;
12
13
use yii\base\InvalidConfigException;
14
use yii\base\NotSupportedException;
15
use yii\db\ActiveQueryInterface;
16
use yii\db\BaseActiveRecord;
17
use yii\helpers\ArrayHelper;
18
use yii\helpers\Inflector;
19
use yii\helpers\StringHelper;
20
21
class ActiveRecord extends BaseActiveRecord
22
{
23
    /**
24
     * Returns the database connection used by this AR class.
25
     * By default, the "hiart" application component is used as the database connection.
26
     * You may override this method if you want to use a different database connection.
27
     *
28
     * @return AbstractConnection the database connection used by this AR class
29
     */
30
    public static function getDb()
31
    {
32
        return AbstractConnection::getDb();
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     * @return ActiveQuery the newly created [[ActiveQuery]] instance
38
     */
39 2
    public static function find()
40
    {
41 2
        $class = static::getDb()->activeQueryClass;
42
43 2
        return new $class(get_called_class());
44
    }
45
46
    public function isScenarioDefault()
47
    {
48
        return $this->scenario === static::SCENARIO_DEFAULT;
49
    }
50
51
    /**
52
     * Gets a record by its primary key.
53
     *
54
     * @param mixed $primaryKey the primaryKey value
55
     * @param array $options    options given in this parameter are passed to API
56
     *
57
     * @return null|static the record instance or null if it was not found
58
     */
59
    public static function get($primaryKey = null, $options = [])
60
    {
61
        if ($primaryKey === null) {
62
            return null;
63
        }
64
        $command = static::getDb()->createCommand();
65
        $result  = $command->get(static::from(), $primaryKey, $options);
0 ignored issues
show
Documentation Bug introduced by
The method get does not exist on object<hiqdev\hiart\Command>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
66
67
        if ($result) {
68
            $model = static::instantiate($result);
69
            static::populateRecord($model, $result);
70
            $model->afterFind();
71
72
            return $model;
73
        }
74
75
        return null;
76
    }
77
78
    /**
79
     * This method defines the attribute that uniquely identifies a record.
80
     *
81
     * The primaryKey for HiArt objects is the `id` field by default. This field is not part of the
82
     * ActiveRecord attributes so you should never add `_id` to the list of [[attributes()|attributes]].
83
     *
84
     * You may override this method to define the primary key name.
85
     *
86
     * Note that HiArt only supports _one_ attribute to be the primary key. However to match the signature
87
     * of the [[\yii\db\ActiveRecordInterface|ActiveRecordInterface]] this methods returns an array instead of a
88
     * single string.
89
     *
90
     * @return string[] array of primary key attributes. Only the first element of the array will be used.
91
     */
92
    public static function primaryKey()
93
    {
94
        return ['id'];
95
    }
96
97
    /**
98
     * +     * The name of the main attribute
99
     * +     *
100
     * Examples:.
101
     *
102
     * This will directly reference to the attribute 'name'
103
     * ```
104
     *     return 'name';
105
     * ```
106
     *
107
     * This will concatenate listed attributes, separated with `delimiter` value.
108
     * If delimiter is not set, space is used by default.
109
     * ```
110
     *     return ['seller', 'client', 'delimiter' => '/'];
111
     * ```
112
     *
113
     * The callable method, that will get [[$model]] and should return value of name attribute
114
     * ```
115
     *     return function ($model) {
116
     *        return $model->someField ? $model->name : $model->otherName;
117
     *     };
118
     * ```
119
     *
120
     * @throws InvalidConfigException
121
     *
122
     * @return string|callable|array
123
     *
124
     * @author SilverFire
125
     */
126
    public function primaryValue()
127
    {
128
        return static::formName();
129
    }
130
131
    /**
132
     * Returns the value of the primary attribute.
133
     *
134
     * @throws InvalidConfigException
135
     *
136
     * @return mixed|null
137
     *
138
     * @see primaryValue()
139
     */
140
    public function getPrimaryValue()
141
    {
142
        $primaryValue = $this->primaryValue();
143
144
        if ($primaryValue instanceof \Closure) {
145
            return call_user_func($primaryValue, [$this]);
146
        } elseif (is_array($primaryValue)) {
147
            $delimiter = ArrayHelper::remove($primaryValue, 'delimiter', ' ');
148
149
            return implode($delimiter, $this->getAttributes($primaryValue));
150
        } else {
151
            return $this->getAttribute($primaryValue);
152
        }
153
    }
154
155
    /**
156
     * Returns the list of attribute names.
157
     * By default, this method returns all attributes mentioned in rules.
158
     * You may override this method to change the default behavior.
159
     * @return string[] list of attribute names
160
     */
161 2
    public function attributes()
162
    {
163 2
        $attributes = [];
164 2
        foreach ($this->rules() as $rule) {
165 2
            $names = reset($rule);
166 2
            if (is_string($names)) {
167 2
                $names = [$names];
168 2
            }
169 2
            foreach ($names as $name) {
0 ignored issues
show
Bug introduced by
The expression $names of type object|integer|double|null|array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
170 2
                if (substr_compare($name, '!', 0, 1) === 0) {
171
                    $name = mb_substr($name, 1);
172
                }
173 2
                $attributes[$name] = $name;
174 2
            }
175 2
        }
176
177 2
        return array_values($attributes);
178
    }
179
180
    /**
181
     * @return string the name of the index this record is stored in
182
     */
183
    public static function index()
184
    {
185
        //        return Inflector::pluralize(Inflector::camel2id(StringHelper::basename(get_called_class()), '-'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
186
        return mb_strtolower(StringHelper::basename(get_called_class()) . 's');
187
    }
188
189
    public static function joinIndex()
190
    {
191
        return static::index();
192
    }
193
194
    /**
195
     * Creates an active record instance.
196
     *
197
     * This method is called together with [[populateRecord()]] by [[ActiveQuery]].
198
     * It is not meant to be used for creating new records directly.
199
     *
200
     * You may override this method if the instance being created
201
     * depends on the row data to be populated into the record.
202
     * For example, by creating a record based on the value of a column,
203
     * you may implement the so-called single-table inheritance mapping.
204
     *
205
     * @return static the newly created active record
206
     */
207 2
    public static function instantiate($row)
208
    {
209 2
        return new static();
210
    }
211
212
    /**
213
     * @return string the name of the entity of this record
214
     */
215 2
    public static function from()
216
    {
217 2
        return Inflector::camel2id(StringHelper::basename(get_called_class()), '-');
218
    }
219
220
    /**
221
     * Declares the name of the model associated with this class.
222
     * By default this method returns the class name by calling [[Inflector::camel2id()]].
223
     *
224
     * @return string the module name
225
     */
226
    public static function modelName()
227
    {
228
        return Inflector::camel2id(StringHelper::basename(get_called_class()));
229
    }
230
231
    public function insert($runValidation = true, $attributes = null, $options = [])
232
    {
233
        if ($runValidation && !$this->validate($attributes)) {
234
            return false;
235
        }
236
237
        if (!$this->beforeSave(true)) {
238
            return false;
239
        }
240
241
        $values = $this->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 231 can also be of type array; however, yii\db\BaseActiveRecord::getDirtyAttributes() does only seem to accept array<integer,string>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
242
        $data   = array_merge($values, $options, ['id' => $this->getOldPrimaryKey()]);
243
        $result = $this->performScenario('insert', $data);
244
245
        $pk        = static::primaryKey()[0];
246
        $this->$pk = $result['id'];
247
        if ($pk !== 'id') {
248
            $values[$pk] = $result['id'];
249
        }
250
        $changedAttributes = array_fill_keys(array_keys($values), null);
251
        $this->setOldAttributes($values);
252
        $this->afterSave(true, $changedAttributes);
253
254
        return true;
255
    }
256
257
    /**
258
     * {@inheritdoc}
259
     */
260
    public function delete($options = [])
261
    {
262
        if (!$this->beforeDelete()) {
263
            return false;
264
        }
265
266
        $data   = array_merge($options, ['id' => $this->getOldPrimaryKey()]);
267
        $result = $this->performScenario('delete', $data);
268
269
        $this->setOldAttributes(null);
270
        $this->afterDelete();
271
272
        return $result === false ? false : true;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $result === false ? false : true; (boolean) is incompatible with the return type of the parent method yii\db\BaseActiveRecord::delete of type integer|false.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
273
    }
274
275
    public function update($runValidation = true, $attributeNames = null, $options = [])
276
    {
277
        if ($runValidation && !$this->validate($attributeNames)) {
278
            return false;
279
        }
280
281
        return $this->updateInternal($attributeNames, $options);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->updateInternal($attributeNames, $options); of type integer|boolean adds the type boolean to the return on line 281 which is incompatible with the return type of the parent method yii\db\BaseActiveRecord::update of type false|integer.
Loading history...
282
    }
283
284
    protected function updateInternal($attributes = null, $options = [])
285
    {
286
        if (!$this->beforeSave(false)) {
287
            return false;
288
        }
289
290
        $values = $this->getAttributes($attributes);
291
        if (empty($values)) {
292
            $this->afterSave(false, $values);
293
294
            return 0;
295
        }
296
297
        $result = $this->performScenario('update', $values, $options);
298
299
        $changedAttributes = [];
300
        foreach ($values as $name => $value) {
301
            $changedAttributes[$name] = $this->getOldAttribute($name);
302
            $this->setOldAttribute($name, $value);
303
        }
304
305
        $this->afterSave(false, $changedAttributes);
306
307
        return $result === false ? false : true;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $result === false ? false : true; (boolean) is incompatible with the return type of the parent method yii\db\BaseActiveRecord::updateInternal of type false|integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
308
    }
309
310
    public function performScenario($defaultScenario, $data, array $options = [])
311
    {
312
        $action = $this->getScenarioAction($defaultScenario);
313
314
        return static::perform($action, $data, $options);
315
    }
316
317
    public static function perform($action, $data, array $options = [])
318
    {
319
        return static::getDb()->createCommand()->perform($action, static::from(), $data, $options);
320
    }
321
322
    /**
323
     * Converts scenario name to action.
324
     * @param string $default default action name
325
     * @throws InvalidConfigException
326
     * @throws NotSupportedException
327
     * @return string
328
     */
329
    public function getScenarioAction($default = '')
330
    {
331
        if ($this->isScenarioDefault()) {
332
            if ($default !== '') {
333
                $result = Inflector::id2camel($default);
334
            } else {
335
                throw new InvalidConfigException('Scenario not specified');
336
            }
337
        } else {
338
            $scenarioCommands = static::scenarioCommands();
339
            if ($action = $scenarioCommands[$this->scenario]) {
340
                if ($action === false) {
341
                    throw new NotSupportedException('The scenario can not be saved');
342
                }
343
344
                if (is_array($action) && $action[0] === null) {
345
                    $result = $action[1];
346
                } elseif (is_array($action)) {
347
                    $result = $action;
348
                } else {
349
                    $result = Inflector::id2camel($action);
350
                }
351
            } else {
352
                $result = Inflector::id2camel($this->scenario);
353
            }
354
        }
355
356
        return is_array($result) ? implode('', $result) : $result;
357
    }
358
359
    /**
360
     * Define an array of relations between scenario and API call action.
361
     *
362
     * Example:
363
     *
364
     * ```
365
     * [
366
     *      'update-name'                => 'set-name', /// ModuleSetName
367
     *      'update-related-name'        => [Action::formName(), 'SetName'], /// ActionSetName
368
     *      'update-self-case-sensetive' => [null, 'SomeSENSETIVE'] /// ModuleSomeSENSETIVE
369
     * ]
370
     * ~~
371
     *
372
     *  key string name of scenario
373
     *  value string|array
374
     *              string will be passed to [[Inflector::id2camel|id2camel]] inflator
375
     *              array - first attribute a module name, second - value
376
     *
377
     * Tricks: pass null as first argument of array to leave command's case unchanged (no inflator calling)
378
     *
379
     * @return array
380
     */
381
    public function scenarioCommands()
382
    {
383
        return [];
384
    }
385
386
    /**
387
     * @return bool
388
     */
389
    public function getIsNewRecord()
390
    {
391
        return !$this->getPrimaryKey();
392
    }
393
394
    /**
395
     * This method has no effect in HiArt ActiveRecord.
396
     */
397
    public function optimisticLock()
398
    {
399
        return null;
400
    }
401
402
    /**
403
     * Destroys the relationship in current model.
404
     *
405
     * This method is not supported by HiArt.
406
     */
407
    public function unlinkAll($name, $delete = false)
408
    {
409
        throw new NotSupportedException('unlinkAll() is not supported by HiArt, use unlink() instead.');
410
    }
411
412
    /**
413
     * {@inheritdoc}
414
     *
415
     * @return ActiveQueryInterface|ActiveQuery the relational query object. If the relation does not exist
416
     *                                          and `$throwException` is false, null will be returned.
417
     */
418
    public function getRelation($name, $throwException = true)
419
    {
420
        return parent::getRelation($name, $throwException);
421
    }
422
423
    /**
424
     * {@inheritdoc}
425
     * @return ActiveQuery the relational query object
426
     */
427
    public function hasOne($class, $link)
428
    {
429
        return parent::hasOne($class, $link);
430
    }
431
432
    /**
433
     * {@inheritdoc}
434
     * @return ActiveQuery the relational query object
435
     */
436
    public function hasMany($class, $link)
437
    {
438
        return parent::hasMany($class, $link);
439
    }
440
}
441