Completed
Push — master ( 54dcc0...96de4d )
by Andrii
02:28
created

ActiveRecord::tableName()   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\Inflector;
18
use yii\helpers\StringHelper;
19
20
class ActiveRecord extends BaseActiveRecord
21
{
22
    /**
23
     * Returns the database connection used by this AR class.
24
     * By default, the "hiart" application component is used as the database connection.
25
     * You may override this method if you want to use a different database connection.
26
     *
27
     * @return AbstractConnection the database connection used by this AR class
28
     */
29
    public static function getDb()
30
    {
31
        return AbstractConnection::getDb();
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     * @return ActiveQuery the newly created [[ActiveQuery]] instance
37
     */
38 2
    public static function find()
39
    {
40 2
        $class = static::getDb()->activeQueryClass;
41
42 2
        return new $class(get_called_class());
43
    }
44
45
    public function isScenarioDefault()
46
    {
47
        return $this->scenario === static::SCENARIO_DEFAULT;
48
    }
49
50
    /**
51
     * This method defines the attribute that uniquely identifies a record.
52
     *
53
     * The primaryKey for HiArt objects is the `id` field by default. This field is not part of the
54
     * ActiveRecord attributes so you should never add `_id` to the list of [[attributes()|attributes]].
55
     *
56
     * You may override this method to define the primary key name.
57
     *
58
     * Note that HiArt only supports _one_ attribute to be the primary key. However to match the signature
59
     * of the [[\yii\db\ActiveRecordInterface|ActiveRecordInterface]] this methods returns an array instead of a
60
     * single string.
61
     *
62
     * @return string[] array of primary key attributes. Only the first element of the array will be used.
63
     */
64
    public static function primaryKey()
65
    {
66
        return ['id'];
67
    }
68
69
    /**
70
     * Returns the list of attribute names.
71
     * By default, this method returns all attributes mentioned in rules.
72
     * You may override this method to change the default behavior.
73
     * @return string[] list of attribute names
74
     */
75 2
    public function attributes()
76
    {
77 2
        $attributes = [];
78 2
        foreach ($this->rules() as $rule) {
79 2
            $names = reset($rule);
80 2
            if (is_string($names)) {
81 2
                $names = [$names];
82 2
            }
83 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...
84 2
                if (substr_compare($name, '!', 0, 1) === 0) {
85
                    $name = mb_substr($name, 1);
86
                }
87 2
                $attributes[$name] = $name;
88 2
            }
89 2
        }
90
91 2
        return array_values($attributes);
92
    }
93
94
    /**
95
     * Creates an active record instance.
96
     *
97
     * This method is called together with [[populateRecord()]] by [[ActiveQuery]].
98
     * It is not meant to be used for creating new records directly.
99
     *
100
     * You may override this method if the instance being created
101
     * depends on the row data to be populated into the record.
102
     * For example, by creating a record based on the value of a column,
103
     * you may implement the so-called single-table inheritance mapping.
104
     *
105
     * @return static the newly created active record
106
     */
107 2
    public static function instantiate($row)
108
    {
109 2
        return new static();
110
    }
111
112
    /**
113
     * @return string the name of the entity of this record
114
     */
115 2
    public static function tableName()
116
    {
117 2
        return Inflector::camel2id(StringHelper::basename(get_called_class()), '-');
118
    }
119
120
    /**
121
     * Declares the name of the model associated with this class.
122
     * By default this method returns the class name by calling [[Inflector::camel2id()]].
123
     *
124
     * @return string the module name
125
     */
126
    public static function modelName()
127
    {
128
        return Inflector::camel2id(StringHelper::basename(get_called_class()));
129
    }
130
131
    public function insert($runValidation = true, $attributes = null, $options = [])
132
    {
133
        if ($runValidation && !$this->validate($attributes)) {
134
            return false;
135
        }
136
137
        if (!$this->beforeSave(true)) {
138
            return false;
139
        }
140
141
        $values = $this->getDirtyAttributes($attributes);
0 ignored issues
show
Bug introduced by
It seems like $attributes defined by parameter $attributes on line 131 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...
142
        $data   = array_merge($values, $options, ['id' => $this->getOldPrimaryKey()]);
143
        $result = $this->performScenario('insert', $data);
144
145
        $pk        = static::primaryKey()[0];
146
        $this->$pk = $result['id'];
147
        if ($pk !== 'id') {
148
            $values[$pk] = $result['id'];
149
        }
150
        $changedAttributes = array_fill_keys(array_keys($values), null);
151
        $this->setOldAttributes($values);
152
        $this->afterSave(true, $changedAttributes);
153
154
        return true;
155
    }
156
157
    /**
158
     * {@inheritdoc}
159
     */
160
    public function delete($options = [])
161
    {
162
        if (!$this->beforeDelete()) {
163
            return false;
164
        }
165
166
        $data   = array_merge($options, ['id' => $this->getOldPrimaryKey()]);
167
        $result = $this->performScenario('delete', $data);
168
169
        $this->setOldAttributes(null);
170
        $this->afterDelete();
171
172
        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...
173
    }
174
175
    public function update($runValidation = true, $attributeNames = null, $options = [])
176
    {
177
        if ($runValidation && !$this->validate($attributeNames)) {
178
            return false;
179
        }
180
181
        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 181 which is incompatible with the return type of the parent method yii\db\BaseActiveRecord::update of type false|integer.
Loading history...
182
    }
183
184
    protected function updateInternal($attributes = null, $options = [])
185
    {
186
        if (!$this->beforeSave(false)) {
187
            return false;
188
        }
189
190
        $values = $this->getAttributes($attributes);
191
        if (empty($values)) {
192
            $this->afterSave(false, $values);
193
194
            return 0;
195
        }
196
197
        $result = $this->performScenario('update', $values, $options);
198
199
        $changedAttributes = [];
200
        foreach ($values as $name => $value) {
201
            $changedAttributes[$name] = $this->getOldAttribute($name);
202
            $this->setOldAttribute($name, $value);
203
        }
204
205
        $this->afterSave(false, $changedAttributes);
206
207
        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...
208
    }
209
210
    public function performScenario($defaultScenario, $data, array $options = [])
211
    {
212
        $action = $this->getScenarioAction($defaultScenario);
213
214
        return static::perform($action, $data, $options);
215
    }
216
217
    public static function perform($action, $data, array $options = [])
218
    {
219
        return static::getDb()->createCommand()->perform($action, static::tableName(), $data, $options);
220
    }
221
222
    /**
223
     * Converts scenario name to action.
224
     * @param string $default default action name
225
     * @throws InvalidConfigException
226
     * @throws NotSupportedException
227
     * @return string
228
     */
229
    public function getScenarioAction($default = '')
230
    {
231
        if ($this->isScenarioDefault()) {
232
            if ($default !== '') {
233
                $result = Inflector::id2camel($default);
234
            } else {
235
                throw new InvalidConfigException('Scenario not specified');
236
            }
237
        } else {
238
            $scenarioCommands = static::scenarioCommands();
239
            if ($action = $scenarioCommands[$this->scenario]) {
240
                if ($action === false) {
241
                    throw new NotSupportedException('The scenario can not be saved');
242
                }
243
244
                if (is_array($action) && $action[0] === null) {
245
                    $result = $action[1];
246
                } elseif (is_array($action)) {
247
                    $result = $action;
248
                } else {
249
                    $result = Inflector::id2camel($action);
250
                }
251
            } else {
252
                $result = Inflector::id2camel($this->scenario);
253
            }
254
        }
255
256
        return is_array($result) ? implode('', $result) : $result;
257
    }
258
259
    /**
260
     * Define an array of relations between scenario and API call action.
261
     *
262
     * Example:
263
     *
264
     * ```
265
     * [
266
     *      'update-name'                => 'set-name', /// ModuleSetName
267
     *      'update-related-name'        => [Action::formName(), 'SetName'], /// ActionSetName
268
     *      'update-self-case-sensetive' => [null, 'SomeSENSETIVE'] /// ModuleSomeSENSETIVE
269
     * ]
270
     * ~~
271
     *
272
     *  key string name of scenario
273
     *  value string|array
274
     *              string will be passed to [[Inflector::id2camel|id2camel]] inflator
275
     *              array - first attribute a module name, second - value
276
     *
277
     * Tricks: pass null as first argument of array to leave command's case unchanged (no inflator calling)
278
     *
279
     * @return array
280
     */
281
    public function scenarioCommands()
282
    {
283
        return [];
284
    }
285
286
    /**
287
     * @return bool
288
     */
289
    public function getIsNewRecord()
290
    {
291
        return !$this->getPrimaryKey();
292
    }
293
294
    /**
295
     * This method has no effect in HiArt ActiveRecord.
296
     */
297
    public function optimisticLock()
298
    {
299
        return null;
300
    }
301
302
    /**
303
     * Destroys the relationship in current model.
304
     *
305
     * This method is not supported by HiArt.
306
     */
307
    public function unlinkAll($name, $delete = false)
308
    {
309
        throw new NotSupportedException('unlinkAll() is not supported by HiArt, use unlink() instead.');
310
    }
311
312
    /**
313
     * {@inheritdoc}
314
     *
315
     * @return ActiveQueryInterface|ActiveQuery the relational query object. If the relation does not exist
316
     *                                          and `$throwException` is false, null will be returned.
317
     */
318
    public function getRelation($name, $throwException = true)
319
    {
320
        return parent::getRelation($name, $throwException);
321
    }
322
323
    /**
324
     * {@inheritdoc}
325
     * @return ActiveQuery the relational query object
326
     */
327
    public function hasOne($class, $link)
328
    {
329
        return parent::hasOne($class, $link);
330
    }
331
332
    /**
333
     * {@inheritdoc}
334
     * @return ActiveQuery the relational query object
335
     */
336
    public function hasMany($class, $link)
337
    {
338
        return parent::hasMany($class, $link);
339
    }
340
}
341