Complex classes like BaseActiveRecord often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use BaseActiveRecord, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
43 | abstract class BaseActiveRecord extends Model implements ActiveRecordInterface |
||
44 | { |
||
45 | /** |
||
46 | * @event Event an event that is triggered when the record is initialized via [[init()]]. |
||
47 | */ |
||
48 | const EVENT_INIT = 'init'; |
||
49 | /** |
||
50 | * @event Event an event that is triggered after the record is created and populated with query result. |
||
51 | */ |
||
52 | const EVENT_AFTER_FIND = 'afterFind'; |
||
53 | /** |
||
54 | * @event ModelEvent an event that is triggered before inserting a record. |
||
55 | * You may set [[ModelEvent::isValid]] to be `false` to stop the insertion. |
||
56 | */ |
||
57 | const EVENT_BEFORE_INSERT = 'beforeInsert'; |
||
58 | /** |
||
59 | * @event AfterSaveEvent an event that is triggered after a record is inserted. |
||
60 | */ |
||
61 | const EVENT_AFTER_INSERT = 'afterInsert'; |
||
62 | /** |
||
63 | * @event ModelEvent an event that is triggered before updating a record. |
||
64 | * You may set [[ModelEvent::isValid]] to be `false` to stop the update. |
||
65 | */ |
||
66 | const EVENT_BEFORE_UPDATE = 'beforeUpdate'; |
||
67 | /** |
||
68 | * @event AfterSaveEvent an event that is triggered after a record is updated. |
||
69 | */ |
||
70 | const EVENT_AFTER_UPDATE = 'afterUpdate'; |
||
71 | /** |
||
72 | * @event ModelEvent an event that is triggered before deleting a record. |
||
73 | * You may set [[ModelEvent::isValid]] to be `false` to stop the deletion. |
||
74 | */ |
||
75 | const EVENT_BEFORE_DELETE = 'beforeDelete'; |
||
76 | /** |
||
77 | * @event Event an event that is triggered after a record is deleted. |
||
78 | */ |
||
79 | const EVENT_AFTER_DELETE = 'afterDelete'; |
||
80 | /** |
||
81 | * @event Event an event that is triggered after a record is refreshed. |
||
82 | * @since 2.0.8 |
||
83 | */ |
||
84 | const EVENT_AFTER_REFRESH = 'afterRefresh'; |
||
85 | |||
86 | /** |
||
87 | * @var array attribute values indexed by attribute names |
||
88 | */ |
||
89 | private $_attributes = []; |
||
90 | /** |
||
91 | * @var array|null old attribute values indexed by attribute names. |
||
92 | * This is `null` if the record [[isNewRecord|is new]]. |
||
93 | */ |
||
94 | private $_oldAttributes; |
||
95 | /** |
||
96 | * @var array related models indexed by the relation names |
||
97 | */ |
||
98 | private $_related = []; |
||
99 | /** |
||
100 | * @var array relation names indexed by their link attributes |
||
101 | */ |
||
102 | private $_relationsDependencies = []; |
||
103 | |||
104 | |||
105 | /** |
||
106 | * {@inheritdoc} |
||
107 | * @return static|null ActiveRecord instance matching the condition, or `null` if nothing matches. |
||
108 | */ |
||
109 | 187 | public static function findOne($condition) |
|
113 | |||
114 | /** |
||
115 | * {@inheritdoc} |
||
116 | * @return static[] an array of ActiveRecord instances, or an empty array if nothing matches. |
||
117 | */ |
||
118 | public static function findAll($condition) |
||
122 | |||
123 | /** |
||
124 | * Finds ActiveRecord instance(s) by the given condition. |
||
125 | * This method is internally called by [[findOne()]] and [[findAll()]]. |
||
126 | * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter |
||
127 | * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance. |
||
128 | * @throws InvalidConfigException if there is no primary key defined |
||
129 | * @internal |
||
130 | */ |
||
131 | protected static function findByCondition($condition) |
||
132 | { |
||
133 | $query = static::find(); |
||
134 | |||
135 | if (!ArrayHelper::isAssociative($condition)) { |
||
136 | // query by primary key |
||
137 | $primaryKey = static::primaryKey(); |
||
138 | if (isset($primaryKey[0])) { |
||
139 | $condition = [$primaryKey[0] => $condition]; |
||
140 | } else { |
||
141 | throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.'); |
||
142 | } |
||
143 | } |
||
144 | |||
145 | return $query->andWhere($condition); |
||
146 | } |
||
147 | |||
148 | /** |
||
149 | * Updates the whole table using the provided attribute values and conditions. |
||
150 | * |
||
151 | * For example, to change the status to be 1 for all customers whose status is 2: |
||
152 | * |
||
153 | * ```php |
||
154 | * Customer::updateAll(['status' => 1], 'status = 2'); |
||
155 | * ``` |
||
156 | * |
||
157 | * @param array $attributes attribute values (name-value pairs) to be saved into the table |
||
158 | * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL. |
||
159 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||
160 | * @return int the number of rows updated |
||
161 | * @throws NotSupportedException if not overridden |
||
162 | */ |
||
163 | public static function updateAll($attributes, $condition = '') |
||
164 | { |
||
165 | throw new NotSupportedException(__METHOD__ . ' is not supported.'); |
||
166 | } |
||
167 | |||
168 | /** |
||
169 | * Updates the whole table using the provided counter changes and conditions. |
||
170 | * |
||
171 | * For example, to increment all customers' age by 1, |
||
172 | * |
||
173 | * ```php |
||
174 | * Customer::updateAllCounters(['age' => 1]); |
||
175 | * ``` |
||
176 | * |
||
177 | * @param array $counters the counters to be updated (attribute name => increment value). |
||
178 | * Use negative values if you want to decrement the counters. |
||
179 | * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL. |
||
180 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||
181 | * @return int the number of rows updated |
||
182 | * @throws NotSupportedException if not overrided |
||
183 | */ |
||
184 | public static function updateAllCounters($counters, $condition = '') |
||
185 | { |
||
186 | throw new NotSupportedException(__METHOD__ . ' is not supported.'); |
||
187 | } |
||
188 | |||
189 | /** |
||
190 | * Deletes rows in the table using the provided conditions. |
||
191 | * WARNING: If you do not specify any condition, this method will delete ALL rows in the table. |
||
192 | * |
||
193 | * For example, to delete all customers whose status is 3: |
||
194 | * |
||
195 | * ```php |
||
196 | * Customer::deleteAll('status = 3'); |
||
197 | * ``` |
||
198 | * |
||
199 | * @param string|array $condition the conditions that will be put in the WHERE part of the DELETE SQL. |
||
200 | * Please refer to [[Query::where()]] on how to specify this parameter. |
||
201 | * @return int the number of rows deleted |
||
202 | * @throws NotSupportedException if not overridden. |
||
203 | */ |
||
204 | public static function deleteAll($condition = null) |
||
205 | { |
||
206 | throw new NotSupportedException(__METHOD__ . ' is not supported.'); |
||
207 | } |
||
208 | |||
209 | /** |
||
210 | * Returns the name of the column that stores the lock version for implementing optimistic locking. |
||
211 | * |
||
212 | * Optimistic locking allows multiple users to access the same record for edits and avoids |
||
213 | * potential conflicts. In case when a user attempts to save the record upon some staled data |
||
214 | * (because another user has modified the data), a [[StaleObjectException]] exception will be thrown, |
||
215 | * and the update or deletion is skipped. |
||
216 | * |
||
217 | * Optimistic locking is only supported by [[update()]] and [[delete()]]. |
||
218 | * |
||
219 | * To use Optimistic locking: |
||
220 | * |
||
221 | * 1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`. |
||
222 | * Override this method to return the name of this column. |
||
223 | * 2. Add a `required` validation rule for the version column to ensure the version value is submitted. |
||
224 | * 3. In the Web form that collects the user input, add a hidden field that stores |
||
225 | * the lock version of the recording being updated. |
||
226 | * 4. In the controller action that does the data updating, try to catch the [[StaleObjectException]] |
||
227 | * and implement necessary business logic (e.g. merging the changes, prompting stated data) |
||
228 | * to resolve the conflict. |
||
229 | * |
||
230 | * @return string the column name that stores the lock version of a table row. |
||
231 | * If `null` is returned (default implemented), optimistic locking will not be supported. |
||
232 | */ |
||
233 | 33 | public function optimisticLock() |
|
234 | { |
||
235 | 33 | return null; |
|
236 | } |
||
237 | |||
238 | /** |
||
239 | * {@inheritdoc} |
||
240 | */ |
||
241 | 3 | public function canGetProperty($name, $checkVars = true, $checkBehaviors = true) |
|
242 | { |
||
243 | 3 | if (parent::canGetProperty($name, $checkVars, $checkBehaviors)) { |
|
244 | 3 | return true; |
|
245 | } |
||
246 | |||
247 | try { |
||
248 | 3 | return $this->hasAttribute($name); |
|
249 | } catch (\Exception $e) { |
||
250 | // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used |
||
251 | return false; |
||
252 | } |
||
253 | } |
||
254 | |||
255 | /** |
||
256 | * {@inheritdoc} |
||
257 | */ |
||
258 | 9 | public function canSetProperty($name, $checkVars = true, $checkBehaviors = true) |
|
259 | { |
||
260 | 9 | if (parent::canSetProperty($name, $checkVars, $checkBehaviors)) { |
|
261 | 6 | return true; |
|
262 | } |
||
263 | |||
264 | try { |
||
265 | 3 | return $this->hasAttribute($name); |
|
266 | } catch (\Exception $e) { |
||
267 | // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used |
||
268 | return false; |
||
269 | } |
||
270 | } |
||
271 | |||
272 | /** |
||
273 | * PHP getter magic method. |
||
274 | * This method is overridden so that attributes and related objects can be accessed like properties. |
||
275 | * |
||
276 | * @param string $name property name |
||
277 | * @throws \yii\base\InvalidArgumentException if relation name is wrong |
||
278 | * @return mixed property value |
||
279 | * @see getAttribute() |
||
280 | */ |
||
281 | 381 | public function __get($name) |
|
282 | { |
||
283 | 381 | if (isset($this->_attributes[$name]) || array_key_exists($name, $this->_attributes)) { |
|
284 | 358 | return $this->_attributes[$name]; |
|
285 | } |
||
286 | |||
287 | 197 | if ($this->hasAttribute($name)) { |
|
288 | 52 | return null; |
|
289 | } |
||
290 | |||
291 | 163 | if (isset($this->_related[$name]) || array_key_exists($name, $this->_related)) { |
|
292 | 90 | return $this->_related[$name]; |
|
293 | } |
||
294 | 115 | $value = parent::__get($name); |
|
295 | 115 | if ($value instanceof ActiveQueryInterface) { |
|
296 | 70 | $this->setRelationDependencies($name, $value); |
|
297 | 70 | return $this->_related[$name] = $value->findFor($name, $this); |
|
298 | } |
||
299 | |||
300 | 54 | return $value; |
|
301 | } |
||
302 | |||
303 | /** |
||
304 | * PHP setter magic method. |
||
305 | * This method is overridden so that AR attributes can be accessed like properties. |
||
306 | * @param string $name property name |
||
307 | * @param mixed $value property value |
||
308 | */ |
||
309 | 182 | public function __set($name, $value) |
|
310 | { |
||
311 | 182 | if ($this->hasAttribute($name)) { |
|
312 | if ( |
||
313 | 182 | !empty($this->_relationsDependencies[$name]) |
|
314 | 182 | && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value) |
|
315 | ) { |
||
316 | 15 | $this->resetDependentRelations($name); |
|
317 | } |
||
318 | 182 | $this->_attributes[$name] = $value; |
|
319 | } else { |
||
320 | 5 | parent::__set($name, $value); |
|
321 | } |
||
322 | 182 | } |
|
323 | |||
324 | /** |
||
325 | * Checks if a property value is null. |
||
326 | * This method overrides the parent implementation by checking if the named attribute is `null` or not. |
||
327 | * @param string $name the property name or the event name |
||
328 | * @return bool whether the property value is null |
||
329 | */ |
||
330 | 56 | public function __isset($name) |
|
331 | { |
||
332 | try { |
||
333 | 56 | return $this->__get($name) !== null; |
|
334 | } catch (\Exception $e) { |
||
335 | return false; |
||
336 | } |
||
337 | } |
||
338 | |||
339 | /** |
||
340 | * Sets a component property to be null. |
||
341 | * This method overrides the parent implementation by clearing |
||
342 | * the specified attribute value. |
||
343 | * @param string $name the property name or the event name |
||
344 | */ |
||
345 | 15 | public function __unset($name) |
|
346 | { |
||
347 | 15 | if ($this->hasAttribute($name)) { |
|
348 | 9 | unset($this->_attributes[$name]); |
|
349 | 9 | if (!empty($this->_relationsDependencies[$name])) { |
|
350 | 9 | $this->resetDependentRelations($name); |
|
351 | } |
||
352 | 6 | } elseif (array_key_exists($name, $this->_related)) { |
|
353 | 6 | unset($this->_related[$name]); |
|
354 | } elseif ($this->getRelation($name, false) === null) { |
||
355 | parent::__unset($name); |
||
356 | } |
||
357 | 15 | } |
|
358 | |||
359 | /** |
||
360 | * Declares a `has-one` relation. |
||
361 | * The declaration is returned in terms of a relational [[ActiveQuery]] instance |
||
362 | * through which the related record can be queried and retrieved back. |
||
363 | * |
||
364 | * A `has-one` relation means that there is at most one related record matching |
||
365 | * the criteria set by this relation, e.g., a customer has one country. |
||
366 | * |
||
367 | * For example, to declare the `country` relation for `Customer` class, we can write |
||
368 | * the following code in the `Customer` class: |
||
369 | * |
||
370 | * ```php |
||
371 | * public function getCountry() |
||
372 | * { |
||
373 | * return $this->hasOne(Country::class, ['id' => 'country_id']); |
||
374 | * } |
||
375 | * ``` |
||
376 | * |
||
377 | * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name |
||
378 | * in the related class `Country`, while the 'country_id' value refers to an attribute name |
||
379 | * in the current AR class. |
||
380 | * |
||
381 | * Call methods declared in [[ActiveQuery]] to further customize the relation. |
||
382 | * |
||
383 | * @param string $class the class name of the related record |
||
384 | * @param array $link the primary-foreign key constraint. The keys of the array refer to |
||
385 | * the attributes of the record associated with the `$class` model, while the values of the |
||
386 | * array refer to the corresponding attributes in **this** AR class. |
||
387 | * @return ActiveQueryInterface the relational query object. |
||
388 | */ |
||
389 | 70 | public function hasOne($class, $link) |
|
390 | { |
||
391 | 70 | return $this->createRelationQuery($class, $link, false); |
|
392 | } |
||
393 | |||
394 | /** |
||
395 | * Declares a `has-many` relation. |
||
396 | * The declaration is returned in terms of a relational [[ActiveQuery]] instance |
||
397 | * through which the related record can be queried and retrieved back. |
||
398 | * |
||
399 | * A `has-many` relation means that there are multiple related records matching |
||
400 | * the criteria set by this relation, e.g., a customer has many orders. |
||
401 | * |
||
402 | * For example, to declare the `orders` relation for `Customer` class, we can write |
||
403 | * the following code in the `Customer` class: |
||
404 | * |
||
405 | * ```php |
||
406 | * public function getOrders() |
||
407 | * { |
||
408 | * return $this->hasMany(Order::class, ['customer_id' => 'id']); |
||
409 | * } |
||
410 | * ``` |
||
411 | * |
||
412 | * Note that in the above, the 'customer_id' key in the `$link` parameter refers to |
||
413 | * an attribute name in the related class `Order`, while the 'id' value refers to |
||
414 | * an attribute name in the current AR class. |
||
415 | * |
||
416 | * Call methods declared in [[ActiveQuery]] to further customize the relation. |
||
417 | * |
||
418 | * @param string $class the class name of the related record |
||
419 | * @param array $link the primary-foreign key constraint. The keys of the array refer to |
||
420 | * the attributes of the record associated with the `$class` model, while the values of the |
||
421 | * array refer to the corresponding attributes in **this** AR class. |
||
422 | * @return ActiveQueryInterface the relational query object. |
||
423 | */ |
||
424 | 147 | public function hasMany($class, $link) |
|
425 | { |
||
426 | 147 | return $this->createRelationQuery($class, $link, true); |
|
427 | } |
||
428 | |||
429 | /** |
||
430 | * Creates a query instance for `has-one` or `has-many` relation. |
||
431 | * @param string $class the class name of the related record. |
||
432 | * @param array $link the primary-foreign key constraint. |
||
433 | * @param bool $multiple whether this query represents a relation to more than one record. |
||
434 | * @return ActiveQueryInterface the relational query object. |
||
435 | * @since 2.0.12 |
||
436 | * @see hasOne() |
||
437 | * @see hasMany() |
||
438 | */ |
||
439 | 175 | protected function createRelationQuery($class, $link, $multiple) |
|
440 | { |
||
441 | /* @var $class ActiveRecordInterface */ |
||
442 | /* @var $query ActiveQuery */ |
||
443 | 175 | $query = $class::find(); |
|
444 | 175 | $query->primaryModel = $this; |
|
445 | 175 | $query->link = $link; |
|
446 | 175 | $query->multiple = $multiple; |
|
447 | 175 | return $query; |
|
448 | } |
||
449 | |||
450 | /** |
||
451 | * Populates the named relation with the related records. |
||
452 | * Note that this method does not check if the relation exists or not. |
||
453 | * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
||
454 | * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation. |
||
455 | * @see getRelation() |
||
456 | */ |
||
457 | 117 | public function populateRelation($name, $records) |
|
458 | { |
||
459 | 117 | $this->_related[$name] = $records; |
|
460 | 117 | } |
|
461 | |||
462 | /** |
||
463 | * Check whether the named relation has been populated with records. |
||
464 | * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
||
465 | * @return bool whether relation has been populated with records. |
||
466 | * @see getRelation() |
||
467 | */ |
||
468 | 48 | public function isRelationPopulated($name) |
|
469 | { |
||
470 | 48 | return array_key_exists($name, $this->_related); |
|
471 | } |
||
472 | |||
473 | /** |
||
474 | * Returns all populated related records. |
||
475 | * @return array an array of related records indexed by relation names. |
||
476 | * @see getRelation() |
||
477 | */ |
||
478 | 6 | public function getRelatedRecords() |
|
479 | { |
||
480 | 6 | return $this->_related; |
|
481 | } |
||
482 | |||
483 | /** |
||
484 | * Returns a value indicating whether the model has an attribute with the specified name. |
||
485 | * @param string $name the name of the attribute |
||
486 | * @return bool whether the model has an attribute with the specified name. |
||
487 | */ |
||
488 | 296 | public function hasAttribute($name) |
|
489 | { |
||
490 | 296 | return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true); |
|
491 | } |
||
492 | |||
493 | /** |
||
494 | * Returns the named attribute value. |
||
495 | * If this record is the result of a query and the attribute is not loaded, |
||
496 | * `null` will be returned. |
||
497 | * @param string $name the attribute name |
||
498 | * @return mixed the attribute value. `null` if the attribute is not set or does not exist. |
||
499 | * @see hasAttribute() |
||
500 | */ |
||
501 | public function getAttribute($name) |
||
502 | { |
||
503 | return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null; |
||
504 | } |
||
505 | |||
506 | /** |
||
507 | * Sets the named attribute value. |
||
508 | * @param string $name the attribute name |
||
509 | * @param mixed $value the attribute value. |
||
510 | * @throws InvalidArgumentException if the named attribute does not exist. |
||
511 | * @see hasAttribute() |
||
512 | */ |
||
513 | 83 | public function setAttribute($name, $value) |
|
514 | { |
||
515 | 83 | if ($this->hasAttribute($name)) { |
|
516 | if ( |
||
517 | 83 | !empty($this->_relationsDependencies[$name]) |
|
518 | 83 | && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value) |
|
519 | ) { |
||
520 | 6 | $this->resetDependentRelations($name); |
|
521 | } |
||
522 | 83 | $this->_attributes[$name] = $value; |
|
523 | } else { |
||
524 | throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".'); |
||
525 | } |
||
526 | 83 | } |
|
527 | |||
528 | /** |
||
529 | * Returns the old attribute values. |
||
530 | * @return array the old attribute values (name-value pairs) |
||
531 | */ |
||
532 | public function getOldAttributes() |
||
533 | { |
||
534 | return $this->_oldAttributes === null ? [] : $this->_oldAttributes; |
||
535 | } |
||
536 | |||
537 | /** |
||
538 | * Sets the old attribute values. |
||
539 | * All existing old attribute values will be discarded. |
||
540 | * @param array|null $values old attribute values to be set. |
||
541 | * If set to `null` this record is considered to be [[isNewRecord|new]]. |
||
542 | */ |
||
543 | 94 | public function setOldAttributes($values) |
|
544 | { |
||
545 | 94 | $this->_oldAttributes = $values; |
|
546 | 94 | } |
|
547 | |||
548 | /** |
||
549 | * Returns the old value of the named attribute. |
||
550 | * If this record is the result of a query and the attribute is not loaded, |
||
551 | * `null` will be returned. |
||
552 | * @param string $name the attribute name |
||
553 | * @return mixed the old attribute value. `null` if the attribute is not loaded before |
||
554 | * or does not exist. |
||
555 | * @see hasAttribute() |
||
556 | */ |
||
557 | public function getOldAttribute($name) |
||
558 | { |
||
559 | return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null; |
||
560 | } |
||
561 | |||
562 | /** |
||
563 | * Sets the old value of the named attribute. |
||
564 | * @param string $name the attribute name |
||
565 | * @param mixed $value the old attribute value. |
||
566 | * @throws InvalidArgumentException if the named attribute does not exist. |
||
567 | * @see hasAttribute() |
||
568 | */ |
||
569 | public function setOldAttribute($name, $value) |
||
570 | { |
||
571 | if (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name)) { |
||
572 | $this->_oldAttributes[$name] = $value; |
||
573 | } else { |
||
574 | throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".'); |
||
575 | } |
||
576 | } |
||
577 | |||
578 | /** |
||
579 | * Marks an attribute dirty. |
||
580 | * This method may be called to force updating a record when calling [[update()]], |
||
581 | * even if there is no change being made to the record. |
||
582 | * @param string $name the attribute name |
||
583 | */ |
||
584 | 3 | public function markAttributeDirty($name) |
|
585 | { |
||
586 | 3 | unset($this->_oldAttributes[$name]); |
|
587 | 3 | } |
|
588 | |||
589 | /** |
||
590 | * Returns a value indicating whether the named attribute has been changed. |
||
591 | * @param string $name the name of the attribute. |
||
592 | * @param bool $identical whether the comparison of new and old value is made for |
||
593 | * identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison. |
||
594 | * This parameter is available since version 2.0.4. |
||
595 | * @return bool whether the attribute has been changed |
||
596 | */ |
||
597 | 2 | public function isAttributeChanged($name, $identical = true) |
|
598 | { |
||
599 | 2 | if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) { |
|
600 | 1 | if ($identical) { |
|
601 | 1 | return $this->_attributes[$name] !== $this->_oldAttributes[$name]; |
|
602 | } |
||
603 | |||
604 | return $this->_attributes[$name] != $this->_oldAttributes[$name]; |
||
605 | } |
||
606 | |||
607 | 1 | return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]); |
|
608 | } |
||
609 | |||
610 | /** |
||
611 | * Returns the attribute values that have been modified since they are loaded or saved most recently. |
||
612 | * |
||
613 | * The comparison of new and old values is made for identical values using `===`. |
||
614 | * |
||
615 | * @param string[]|null $names the names of the attributes whose values may be returned if they are |
||
616 | * changed recently. If null, [[attributes()]] will be used. |
||
617 | * @return array the changed attribute values (name-value pairs) |
||
618 | */ |
||
619 | 104 | public function getDirtyAttributes($names = null) |
|
620 | { |
||
621 | 104 | if ($names === null) { |
|
622 | 101 | $names = $this->attributes(); |
|
623 | } |
||
624 | 104 | $names = array_flip($names); |
|
625 | 104 | $attributes = []; |
|
626 | 104 | if ($this->_oldAttributes === null) { |
|
627 | 91 | foreach ($this->_attributes as $name => $value) { |
|
628 | 87 | if (isset($names[$name])) { |
|
629 | 91 | $attributes[$name] = $value; |
|
630 | } |
||
631 | } |
||
632 | } else { |
||
633 | 39 | foreach ($this->_attributes as $name => $value) { |
|
634 | 39 | if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $value !== $this->_oldAttributes[$name])) { |
|
635 | 39 | $attributes[$name] = $value; |
|
636 | } |
||
637 | } |
||
638 | } |
||
639 | |||
640 | 104 | return $attributes; |
|
641 | } |
||
642 | |||
643 | /** |
||
644 | * Saves the current record. |
||
645 | * |
||
646 | * This method will call [[insert()]] when [[isNewRecord]] is `true`, or [[update()]] |
||
647 | * when [[isNewRecord]] is `false`. |
||
648 | * |
||
649 | * For example, to save a customer record: |
||
650 | * |
||
651 | * ```php |
||
652 | * $customer = new Customer; // or $customer = Customer::findOne($id); |
||
653 | * $customer->name = $name; |
||
654 | * $customer->email = $email; |
||
655 | * $customer->save(); |
||
656 | * ``` |
||
657 | * |
||
658 | * @param bool $runValidation whether to perform validation (calling [[validate()]]) |
||
659 | * before saving the record. Defaults to `true`. If the validation fails, the record |
||
660 | * will not be saved to the database and this method will return `false`. |
||
661 | * @param array $attributeNames list of attribute names that need to be saved. Defaults to null, |
||
662 | * meaning all attributes that are loaded from DB will be saved. |
||
663 | * @return bool whether the saving succeeded (i.e. no validation errors occurred). |
||
664 | */ |
||
665 | 98 | public function save($runValidation = true, $attributeNames = null) |
|
666 | { |
||
667 | 98 | if ($this->getIsNewRecord()) { |
|
668 | 85 | return $this->insert($runValidation, $attributeNames); |
|
669 | } |
||
670 | |||
671 | 28 | return $this->update($runValidation, $attributeNames) !== false; |
|
672 | } |
||
673 | |||
674 | /** |
||
675 | * Saves the changes to this active record into the associated database table. |
||
676 | * |
||
677 | * This method performs the following steps in order: |
||
678 | * |
||
679 | * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]] |
||
680 | * returns `false`, the rest of the steps will be skipped; |
||
681 | * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation |
||
682 | * failed, the rest of the steps will be skipped; |
||
683 | * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`, |
||
684 | * the rest of the steps will be skipped; |
||
685 | * 4. save the record into database. If this fails, it will skip the rest of the steps; |
||
686 | * 5. call [[afterSave()]]; |
||
687 | * |
||
688 | * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]], |
||
689 | * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]] |
||
690 | * will be raised by the corresponding methods. |
||
691 | * |
||
692 | * Only the [[dirtyAttributes|changed attribute values]] will be saved into database. |
||
693 | * |
||
694 | * For example, to update a customer record: |
||
695 | * |
||
696 | * ```php |
||
697 | * $customer = Customer::findOne($id); |
||
698 | * $customer->name = $name; |
||
699 | * $customer->email = $email; |
||
700 | * $customer->update(); |
||
701 | * ``` |
||
702 | * |
||
703 | * Note that it is possible the update does not affect any row in the table. |
||
704 | * In this case, this method will return 0. For this reason, you should use the following |
||
705 | * code to check if update() is successful or not: |
||
706 | * |
||
707 | * ```php |
||
708 | * if ($customer->update() !== false) { |
||
709 | * // update successful |
||
710 | * } else { |
||
711 | * // update failed |
||
712 | * } |
||
713 | * ``` |
||
714 | * |
||
715 | * @param bool $runValidation whether to perform validation (calling [[validate()]]) |
||
716 | * before saving the record. Defaults to `true`. If the validation fails, the record |
||
717 | * will not be saved to the database and this method will return `false`. |
||
718 | * @param array $attributeNames list of attribute names that need to be saved. Defaults to null, |
||
719 | * meaning all attributes that are loaded from DB will be saved. |
||
720 | * @return int|false the number of rows affected, or `false` if validation fails |
||
721 | * or [[beforeSave()]] stops the updating process. |
||
722 | * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data |
||
723 | * being updated is outdated. |
||
724 | * @throws Exception in case update failed. |
||
725 | */ |
||
726 | public function update($runValidation = true, $attributeNames = null) |
||
727 | { |
||
728 | if ($runValidation && !$this->validate($attributeNames)) { |
||
729 | return false; |
||
730 | } |
||
731 | |||
732 | return $this->updateInternal($attributeNames); |
||
733 | } |
||
734 | |||
735 | /** |
||
736 | * Updates the specified attributes. |
||
737 | * |
||
738 | * This method is a shortcut to [[update()]] when data validation is not needed |
||
739 | * and only a small set attributes need to be updated. |
||
740 | * |
||
741 | * You may specify the attributes to be updated as name list or name-value pairs. |
||
742 | * If the latter, the corresponding attribute values will be modified accordingly. |
||
743 | * The method will then save the specified attributes into database. |
||
744 | * |
||
745 | * Note that this method will **not** perform data validation and will **not** trigger events. |
||
746 | * |
||
747 | * @param array $attributes the attributes (names or name-value pairs) to be updated |
||
748 | * @return int the number of rows affected. |
||
749 | */ |
||
750 | 4 | public function updateAttributes($attributes) |
|
751 | { |
||
752 | 4 | $attrs = []; |
|
753 | 4 | foreach ($attributes as $name => $value) { |
|
754 | 4 | if (is_int($name)) { |
|
755 | $attrs[] = $value; |
||
756 | } else { |
||
757 | 4 | $this->$name = $value; |
|
758 | 4 | $attrs[] = $name; |
|
759 | } |
||
760 | } |
||
761 | |||
762 | 4 | $values = $this->getDirtyAttributes($attrs); |
|
763 | 4 | if (empty($values) || $this->getIsNewRecord()) { |
|
764 | 4 | return 0; |
|
765 | } |
||
766 | |||
767 | 3 | $rows = static::updateAll($values, $this->getOldPrimaryKey(true)); |
|
768 | |||
769 | 3 | foreach ($values as $name => $value) { |
|
770 | 3 | $this->_oldAttributes[$name] = $this->_attributes[$name]; |
|
771 | } |
||
772 | |||
773 | 3 | return $rows; |
|
774 | } |
||
775 | |||
776 | /** |
||
777 | * @see update() |
||
778 | * @param array $attributes attributes to update |
||
779 | * @return int|false the number of rows affected, or false if [[beforeSave()]] stops the updating process. |
||
780 | * @throws StaleObjectException |
||
781 | */ |
||
782 | 35 | protected function updateInternal($attributes = null) |
|
783 | { |
||
784 | 35 | if (!$this->beforeSave(false)) { |
|
785 | return false; |
||
786 | } |
||
787 | 35 | $values = $this->getDirtyAttributes($attributes); |
|
788 | 35 | if (empty($values)) { |
|
789 | 3 | $this->afterSave(false, $values); |
|
790 | 3 | return 0; |
|
791 | } |
||
792 | 33 | $condition = $this->getOldPrimaryKey(true); |
|
793 | 33 | $lock = $this->optimisticLock(); |
|
794 | 33 | if ($lock !== null) { |
|
795 | 3 | $values[$lock] = $this->$lock + 1; |
|
796 | 3 | $condition[$lock] = $this->$lock; |
|
797 | } |
||
798 | // We do not check the return value of updateAll() because it's possible |
||
799 | // that the UPDATE statement doesn't change anything and thus returns 0. |
||
800 | 33 | $rows = static::updateAll($values, $condition); |
|
801 | |||
802 | 33 | if ($lock !== null && !$rows) { |
|
803 | 3 | throw new StaleObjectException('The object being updated is outdated.'); |
|
804 | } |
||
805 | |||
806 | 33 | if (isset($values[$lock])) { |
|
807 | 3 | $this->$lock = $values[$lock]; |
|
808 | } |
||
809 | |||
810 | 33 | $changedAttributes = []; |
|
811 | 33 | foreach ($values as $name => $value) { |
|
812 | 33 | $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null; |
|
813 | 33 | $this->_oldAttributes[$name] = $value; |
|
814 | } |
||
815 | 33 | $this->afterSave(false, $changedAttributes); |
|
816 | |||
817 | 33 | return $rows; |
|
818 | } |
||
819 | |||
820 | /** |
||
821 | * Updates one or several counter columns for the current AR object. |
||
822 | * Note that this method differs from [[updateAllCounters()]] in that it only |
||
823 | * saves counters for the current AR object. |
||
824 | * |
||
825 | * An example usage is as follows: |
||
826 | * |
||
827 | * ```php |
||
828 | * $post = Post::findOne($id); |
||
829 | * $post->updateCounters(['view_count' => 1]); |
||
830 | * ``` |
||
831 | * |
||
832 | * @param array $counters the counters to be updated (attribute name => increment value) |
||
833 | * Use negative values if you want to decrement the counters. |
||
834 | * @return bool whether the saving is successful |
||
835 | * @see updateAllCounters() |
||
836 | */ |
||
837 | 6 | public function updateCounters($counters) |
|
838 | { |
||
839 | 6 | if (static::updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) { |
|
840 | 6 | foreach ($counters as $name => $value) { |
|
841 | 6 | if (!isset($this->_attributes[$name])) { |
|
842 | 3 | $this->_attributes[$name] = $value; |
|
843 | } else { |
||
844 | 3 | $this->_attributes[$name] += $value; |
|
845 | } |
||
846 | 6 | $this->_oldAttributes[$name] = $this->_attributes[$name]; |
|
847 | } |
||
848 | |||
849 | 6 | return true; |
|
850 | } |
||
851 | |||
852 | return false; |
||
853 | } |
||
854 | |||
855 | /** |
||
856 | * Deletes the table row corresponding to this active record. |
||
857 | * |
||
858 | * This method performs the following steps in order: |
||
859 | * |
||
860 | * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the |
||
861 | * rest of the steps; |
||
862 | * 2. delete the record from the database; |
||
863 | * 3. call [[afterDelete()]]. |
||
864 | * |
||
865 | * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]] |
||
866 | * will be raised by the corresponding methods. |
||
867 | * |
||
868 | * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason. |
||
869 | * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. |
||
870 | * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data |
||
871 | * being deleted is outdated. |
||
872 | * @throws Exception in case delete failed. |
||
873 | */ |
||
874 | public function delete() |
||
875 | { |
||
876 | $result = false; |
||
877 | if ($this->beforeDelete()) { |
||
878 | // we do not check the return value of deleteAll() because it's possible |
||
879 | // the record is already deleted in the database and thus the method will return 0 |
||
880 | $condition = $this->getOldPrimaryKey(true); |
||
881 | $lock = $this->optimisticLock(); |
||
882 | if ($lock !== null) { |
||
883 | $condition[$lock] = $this->$lock; |
||
884 | } |
||
885 | $result = static::deleteAll($condition); |
||
886 | if ($lock !== null && !$result) { |
||
887 | throw new StaleObjectException('The object being deleted is outdated.'); |
||
888 | } |
||
889 | $this->_oldAttributes = null; |
||
890 | $this->afterDelete(); |
||
891 | } |
||
892 | |||
893 | return $result; |
||
894 | } |
||
895 | |||
896 | /** |
||
897 | * Returns a value indicating whether the current record is new. |
||
898 | * @return bool whether the record is new and should be inserted when calling [[save()]]. |
||
899 | */ |
||
900 | 141 | public function getIsNewRecord() |
|
901 | { |
||
902 | 141 | return $this->_oldAttributes === null; |
|
903 | } |
||
904 | |||
905 | /** |
||
906 | * Sets the value indicating whether the record is new. |
||
907 | * @param bool $value whether the record is new and should be inserted when calling [[save()]]. |
||
908 | * @see getIsNewRecord() |
||
909 | */ |
||
910 | public function setIsNewRecord($value) |
||
911 | { |
||
912 | $this->_oldAttributes = $value ? null : $this->_attributes; |
||
913 | } |
||
914 | |||
915 | /** |
||
916 | * Initializes the object. |
||
917 | * This method is called at the end of the constructor. |
||
918 | * The default implementation will trigger an [[EVENT_INIT]] event. |
||
919 | */ |
||
920 | 410 | public function init() |
|
921 | { |
||
922 | 410 | parent::init(); |
|
923 | 410 | $this->trigger(self::EVENT_INIT); |
|
924 | 410 | } |
|
925 | |||
926 | /** |
||
927 | * This method is called when the AR object is created and populated with the query result. |
||
928 | * The default implementation will trigger an [[EVENT_AFTER_FIND]] event. |
||
929 | * When overriding this method, make sure you call the parent implementation to ensure the |
||
930 | * event is triggered. |
||
931 | */ |
||
932 | 316 | public function afterFind() |
|
933 | { |
||
934 | 316 | $this->trigger(self::EVENT_AFTER_FIND); |
|
935 | 316 | } |
|
936 | |||
937 | /** |
||
938 | * This method is called at the beginning of inserting or updating a record. |
||
939 | * |
||
940 | * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is `true`, |
||
941 | * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is `false`. |
||
942 | * When overriding this method, make sure you call the parent implementation like the following: |
||
943 | * |
||
944 | * ```php |
||
945 | * public function beforeSave($insert) |
||
946 | * { |
||
947 | * if (!parent::beforeSave($insert)) { |
||
948 | * return false; |
||
949 | * } |
||
950 | * |
||
951 | * // ...custom code here... |
||
952 | * return true; |
||
953 | * } |
||
954 | * ``` |
||
955 | * |
||
956 | * @param bool $insert whether this method called while inserting a record. |
||
957 | * If `false`, it means the method is called while updating a record. |
||
958 | * @return bool whether the insertion or updating should continue. |
||
959 | * If `false`, the insertion or updating will be cancelled. |
||
960 | */ |
||
961 | 108 | public function beforeSave($insert) |
|
962 | { |
||
963 | 108 | $event = new ModelEvent(); |
|
964 | 108 | $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event); |
|
965 | |||
966 | 108 | return $event->isValid; |
|
967 | } |
||
968 | |||
969 | /** |
||
970 | * This method is called at the end of inserting or updating a record. |
||
971 | * The default implementation will trigger an [[EVENT_AFTER_INSERT]] event when `$insert` is `true`, |
||
972 | * or an [[EVENT_AFTER_UPDATE]] event if `$insert` is `false`. The event class used is [[AfterSaveEvent]]. |
||
973 | * When overriding this method, make sure you call the parent implementation so that |
||
974 | * the event is triggered. |
||
975 | * @param bool $insert whether this method called while inserting a record. |
||
976 | * If `false`, it means the method is called while updating a record. |
||
977 | * @param array $changedAttributes The old values of attributes that had changed and were saved. |
||
978 | * You can use this parameter to take action based on the changes made for example send an email |
||
979 | * when the password had changed or implement audit trail that tracks all the changes. |
||
980 | * `$changedAttributes` gives you the old attribute values while the active record (`$this`) has |
||
981 | * already the new, updated values. |
||
982 | * |
||
983 | * Note that no automatic type conversion performed by default. You may use |
||
984 | * [[\yii\behaviors\AttributeTypecastBehavior]] to facilitate attribute typecasting. |
||
985 | * See http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting. |
||
986 | */ |
||
987 | 101 | public function afterSave($insert, $changedAttributes) |
|
988 | { |
||
989 | 101 | $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([ |
|
990 | 101 | 'changedAttributes' => $changedAttributes, |
|
991 | ])); |
||
992 | 101 | } |
|
993 | |||
994 | /** |
||
995 | * This method is invoked before deleting a record. |
||
996 | * |
||
997 | * The default implementation raises the [[EVENT_BEFORE_DELETE]] event. |
||
998 | * When overriding this method, make sure you call the parent implementation like the following: |
||
999 | * |
||
1000 | * ```php |
||
1001 | * public function beforeDelete() |
||
1002 | * { |
||
1003 | * if (!parent::beforeDelete()) { |
||
1004 | * return false; |
||
1005 | * } |
||
1006 | * |
||
1007 | * // ...custom code here... |
||
1008 | * return true; |
||
1009 | * } |
||
1010 | * ``` |
||
1011 | * |
||
1012 | * @return bool whether the record should be deleted. Defaults to `true`. |
||
1013 | */ |
||
1014 | 6 | public function beforeDelete() |
|
1015 | { |
||
1016 | 6 | $event = new ModelEvent(); |
|
1017 | 6 | $this->trigger(self::EVENT_BEFORE_DELETE, $event); |
|
1018 | |||
1019 | 6 | return $event->isValid; |
|
1020 | } |
||
1021 | |||
1022 | /** |
||
1023 | * This method is invoked after deleting a record. |
||
1024 | * The default implementation raises the [[EVENT_AFTER_DELETE]] event. |
||
1025 | * You may override this method to do postprocessing after the record is deleted. |
||
1026 | * Make sure you call the parent implementation so that the event is raised properly. |
||
1027 | */ |
||
1028 | 6 | public function afterDelete() |
|
1029 | { |
||
1030 | 6 | $this->trigger(self::EVENT_AFTER_DELETE); |
|
1031 | 6 | } |
|
1032 | |||
1033 | /** |
||
1034 | * Repopulates this active record with the latest data. |
||
1035 | * |
||
1036 | * If the refresh is successful, an [[EVENT_AFTER_REFRESH]] event will be triggered. |
||
1037 | * This event is available since version 2.0.8. |
||
1038 | * |
||
1039 | * @return bool whether the row still exists in the database. If `true`, the latest data |
||
1040 | * will be populated to this active record. Otherwise, this record will remain unchanged. |
||
1041 | */ |
||
1042 | public function refresh() |
||
1043 | { |
||
1044 | /* @var $record BaseActiveRecord */ |
||
1045 | $record = static::findOne($this->getPrimaryKey(true)); |
||
1046 | return $this->refreshInternal($record); |
||
1047 | } |
||
1048 | |||
1049 | /** |
||
1050 | * Repopulates this active record with the latest data from a newly fetched instance. |
||
1051 | * @param BaseActiveRecord $record the record to take attributes from. |
||
1052 | * @return bool whether refresh was successful. |
||
1053 | * @see refresh() |
||
1054 | * @since 2.0.13 |
||
1055 | */ |
||
1056 | 29 | protected function refreshInternal($record) |
|
1057 | { |
||
1058 | 29 | if ($record === null) { |
|
1059 | 3 | return false; |
|
1060 | } |
||
1061 | 29 | foreach ($this->attributes() as $name) { |
|
1062 | 29 | $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null; |
|
1063 | } |
||
1064 | 29 | $this->_oldAttributes = $record->_oldAttributes; |
|
1065 | 29 | $this->_related = []; |
|
1066 | 29 | $this->_relationsDependencies = []; |
|
1067 | 29 | $this->afterRefresh(); |
|
1068 | |||
1069 | 29 | return true; |
|
1070 | } |
||
1071 | |||
1072 | /** |
||
1073 | * This method is called when the AR object is refreshed. |
||
1074 | * The default implementation will trigger an [[EVENT_AFTER_REFRESH]] event. |
||
1075 | * When overriding this method, make sure you call the parent implementation to ensure the |
||
1076 | * event is triggered. |
||
1077 | * @since 2.0.8 |
||
1078 | */ |
||
1079 | 29 | public function afterRefresh() |
|
1080 | { |
||
1081 | 29 | $this->trigger(self::EVENT_AFTER_REFRESH); |
|
1082 | 29 | } |
|
1083 | |||
1084 | /** |
||
1085 | * Returns a value indicating whether the given active record is the same as the current one. |
||
1086 | * The comparison is made by comparing the table names and the primary key values of the two active records. |
||
1087 | * If one of the records [[isNewRecord|is new]] they are also considered not equal. |
||
1088 | * @param ActiveRecordInterface $record record to compare to |
||
1089 | * @return bool whether the two active records refer to the same row in the same database table. |
||
1090 | */ |
||
1091 | public function equals($record) |
||
1092 | { |
||
1093 | if ($this->getIsNewRecord() || $record->getIsNewRecord()) { |
||
1094 | return false; |
||
1095 | } |
||
1096 | |||
1097 | return get_class($this) === get_class($record) && $this->getPrimaryKey() === $record->getPrimaryKey(); |
||
1098 | } |
||
1099 | |||
1100 | /** |
||
1101 | * Returns the primary key value(s). |
||
1102 | * @param bool $asArray whether to return the primary key value as an array. If `true`, |
||
1103 | * the return value will be an array with column names as keys and column values as values. |
||
1104 | * Note that for composite primary keys, an array will always be returned regardless of this parameter value. |
||
1105 | * @property mixed The primary key value. An array (column name => column value) is returned if |
||
1106 | * the primary key is composite. A string is returned otherwise (null will be returned if |
||
1107 | * the key value is null). |
||
1108 | * @return mixed the primary key value. An array (column name => column value) is returned if the primary key |
||
1109 | * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if |
||
1110 | * the key value is null). |
||
1111 | */ |
||
1112 | 45 | public function getPrimaryKey($asArray = false) |
|
1113 | { |
||
1114 | 45 | $keys = $this->primaryKey(); |
|
1115 | 45 | if (!$asArray && count($keys) === 1) { |
|
1116 | 19 | return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null; |
|
1117 | } |
||
1118 | |||
1119 | 29 | $values = []; |
|
1120 | 29 | foreach ($keys as $name) { |
|
1121 | 29 | $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null; |
|
1122 | } |
||
1123 | |||
1124 | 29 | return $values; |
|
1125 | } |
||
1126 | |||
1127 | /** |
||
1128 | * Returns the old primary key value(s). |
||
1129 | * This refers to the primary key value that is populated into the record |
||
1130 | * after executing a find method (e.g. find(), findOne()). |
||
1131 | * The value remains unchanged even if the primary key attribute is manually assigned with a different value. |
||
1132 | * @param bool $asArray whether to return the primary key value as an array. If `true`, |
||
1133 | * the return value will be an array with column name as key and column value as value. |
||
1134 | * If this is `false` (default), a scalar value will be returned for non-composite primary key. |
||
1135 | * @property mixed The old primary key value. An array (column name => column value) is |
||
1136 | * returned if the primary key is composite. A string is returned otherwise (null will be |
||
1137 | * returned if the key value is null). |
||
1138 | * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key |
||
1139 | * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if |
||
1140 | * the key value is null). |
||
1141 | * @throws Exception if the AR model does not have a primary key |
||
1142 | */ |
||
1143 | 67 | public function getOldPrimaryKey($asArray = false) |
|
1144 | { |
||
1145 | 67 | $keys = $this->primaryKey(); |
|
1146 | 67 | if (empty($keys)) { |
|
1147 | throw new Exception(get_class($this) . ' does not have a primary key. You should either define a primary key for the corresponding table or override the primaryKey() method.'); |
||
1148 | } |
||
1149 | 67 | if (!$asArray && count($keys) === 1) { |
|
1150 | return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null; |
||
1151 | } |
||
1152 | |||
1153 | 67 | $values = []; |
|
1154 | 67 | foreach ($keys as $name) { |
|
1155 | 67 | $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null; |
|
1156 | } |
||
1157 | |||
1158 | 67 | return $values; |
|
1159 | } |
||
1160 | |||
1161 | /** |
||
1162 | * Populates an active record object using a row of data from the database/storage. |
||
1163 | * |
||
1164 | * This is an internal method meant to be called to create active record objects after |
||
1165 | * fetching data from the database. It is mainly used by [[ActiveQuery]] to populate |
||
1166 | * the query results into active records. |
||
1167 | * |
||
1168 | * When calling this method manually you should call [[afterFind()]] on the created |
||
1169 | * record to trigger the [[EVENT_AFTER_FIND|afterFind Event]]. |
||
1170 | * |
||
1171 | * @param BaseActiveRecord $record the record to be populated. In most cases this will be an instance |
||
1172 | * created by [[instantiate()]] beforehand. |
||
1173 | * @param array $row attribute values (name => value) |
||
1174 | */ |
||
1175 | 316 | public static function populateRecord($record, $row) |
|
1176 | { |
||
1177 | 316 | $columns = array_flip($record->attributes()); |
|
1178 | 316 | foreach ($row as $name => $value) { |
|
1179 | 316 | if (isset($columns[$name])) { |
|
1180 | 316 | $record->_attributes[$name] = $value; |
|
1181 | 6 | } elseif ($record->canSetProperty($name)) { |
|
1182 | 316 | $record->$name = $value; |
|
1183 | } |
||
1184 | } |
||
1185 | 316 | $record->_oldAttributes = $record->_attributes; |
|
1186 | 316 | $record->_related = []; |
|
1187 | 316 | $record->_relationsDependencies = []; |
|
1188 | 316 | } |
|
1189 | |||
1190 | /** |
||
1191 | * Creates an active record instance. |
||
1192 | * |
||
1193 | * This method is called together with [[populateRecord()]] by [[ActiveQuery]]. |
||
1194 | * It is not meant to be used for creating new records directly. |
||
1195 | * |
||
1196 | * You may override this method if the instance being created |
||
1197 | * depends on the row data to be populated into the record. |
||
1198 | * For example, by creating a record based on the value of a column, |
||
1199 | * you may implement the so-called single-table inheritance mapping. |
||
1200 | * @param array $row row data to be populated into the record. |
||
1201 | * @return static the newly created active record |
||
1202 | */ |
||
1203 | 310 | public static function instantiate($row) |
|
1207 | |||
1208 | /** |
||
1209 | * Returns whether there is an element at the specified offset. |
||
1210 | * This method is required by the interface [[\ArrayAccess]]. |
||
1211 | * @param mixed $offset the offset to check on |
||
1212 | * @return bool whether there is an element at the specified offset. |
||
1213 | */ |
||
1214 | 30 | public function offsetExists($offset) |
|
1215 | { |
||
1216 | 30 | return $this->__isset($offset); |
|
1217 | } |
||
1218 | |||
1219 | /** |
||
1220 | * Returns the relation object with the specified name. |
||
1221 | * A relation is defined by a getter method which returns an [[ActiveQueryInterface]] object. |
||
1222 | * It can be declared in either the Active Record class itself or one of its behaviors. |
||
1223 | * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
||
1224 | * @param bool $throwException whether to throw exception if the relation does not exist. |
||
1225 | * @return ActiveQueryInterface|ActiveQuery the relational query object. If the relation does not exist |
||
1226 | * and `$throwException` is `false`, `null` will be returned. |
||
1227 | * @throws InvalidArgumentException if the named relation does not exist. |
||
1228 | */ |
||
1229 | 147 | public function getRelation($name, $throwException = true) |
|
1230 | { |
||
1231 | 147 | $getter = 'get' . $name; |
|
1232 | try { |
||
1233 | // the relation could be defined in a behavior |
||
1234 | 147 | $relation = $this->$getter(); |
|
1235 | } catch (UnknownMethodException $e) { |
||
1236 | if ($throwException) { |
||
1237 | throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e); |
||
1238 | } |
||
1239 | |||
1240 | return null; |
||
1241 | } |
||
1242 | 147 | if (!$relation instanceof ActiveQueryInterface) { |
|
1243 | if ($throwException) { |
||
1244 | throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".'); |
||
1245 | } |
||
1246 | |||
1247 | return null; |
||
1248 | } |
||
1249 | |||
1250 | 147 | if (method_exists($this, $getter)) { |
|
1251 | // relation name is case sensitive, trying to validate it when the relation is defined within this class |
||
1252 | 147 | $method = new \ReflectionMethod($this, $getter); |
|
1253 | 147 | $realName = lcfirst(substr($method->getName(), 3)); |
|
1254 | 147 | if ($realName !== $name) { |
|
1255 | if ($throwException) { |
||
1265 | |||
1266 | /** |
||
1267 | * Establishes the relationship between two models. |
||
1268 | * |
||
1269 | * The relationship is established by setting the foreign key value(s) in one model |
||
1270 | * to be the corresponding primary key value(s) in the other model. |
||
1271 | * The model with the foreign key will be saved into database without performing validation. |
||
1272 | * |
||
1273 | * If the relationship involves a junction table, a new row will be inserted into the |
||
1274 | * junction table which contains the primary key values from both models. |
||
1275 | * |
||
1276 | * Note that this method requires that the primary key value is not null. |
||
1277 | * |
||
1278 | * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
||
1279 | * @param ActiveRecordInterface $model the model to be linked with the current one. |
||
1280 | * @param array $extraColumns additional column values to be saved into the junction table. |
||
1281 | * This parameter is only meaningful for a relationship involving a junction table |
||
1282 | * (i.e., a relation set with [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].) |
||
1283 | * @throws InvalidCallException if the method is unable to link two models. |
||
1284 | */ |
||
1285 | 9 | public function link($name, $model, $extraColumns = []) |
|
1362 | |||
1363 | /** |
||
1364 | * Destroys the relationship between two models. |
||
1365 | * |
||
1366 | * The model with the foreign key of the relationship will be deleted if `$delete` is `true`. |
||
1367 | * Otherwise, the foreign key will be set `null` and the model will be saved without validation. |
||
1368 | * |
||
1369 | * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
||
1370 | * @param ActiveRecordInterface $model the model to be unlinked from the current one. |
||
1371 | * You have to make sure that the model is really related with the current model as this method |
||
1372 | * does not check this. |
||
1373 | * @param bool $delete whether to delete the model that contains the foreign key. |
||
1374 | * If `false`, the model's foreign key will be set `null` and saved. |
||
1375 | * If `true`, the model containing the foreign key will be deleted. |
||
1376 | * @throws InvalidCallException if the models cannot be unlinked |
||
1377 | */ |
||
1378 | 3 | public function unlink($name, $model, $delete = false) |
|
1461 | |||
1462 | /** |
||
1463 | * Destroys the relationship in current model. |
||
1464 | * |
||
1465 | * The model with the foreign key of the relationship will be deleted if `$delete` is `true`. |
||
1466 | * Otherwise, the foreign key will be set `null` and the model will be saved without validation. |
||
1467 | * |
||
1468 | * Note that to destroy the relationship without removing records make sure your keys can be set to null |
||
1469 | * |
||
1470 | * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
||
1471 | * @param bool $delete whether to delete the model that contains the foreign key. |
||
1472 | * |
||
1473 | * Note that the deletion will be performed using [[deleteAll()]], which will not trigger any events on the related models. |
||
1474 | * If you need [[EVENT_BEFORE_DELETE]] or [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first |
||
1475 | * and then call [[delete()]] on each of them. |
||
1476 | */ |
||
1477 | 18 | public function unlinkAll($name, $delete = false) |
|
1550 | |||
1551 | /** |
||
1552 | * @param array $link |
||
1553 | * @param ActiveRecordInterface $foreignModel |
||
1554 | * @param ActiveRecordInterface $primaryModel |
||
1555 | * @throws InvalidCallException |
||
1556 | */ |
||
1557 | 9 | private function bindModels($link, $foreignModel, $primaryModel) |
|
1572 | |||
1573 | /** |
||
1574 | * Returns a value indicating whether the given set of attributes represents the primary key for this model. |
||
1575 | * @param array $keys the set of attributes to check |
||
1576 | * @return bool whether the given set of attributes represents the primary key for this model |
||
1577 | */ |
||
1578 | 15 | public static function isPrimaryKey($keys) |
|
1587 | |||
1588 | /** |
||
1589 | * Returns the text label for the specified attribute. |
||
1590 | * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model. |
||
1591 | * @param string $attribute the attribute name |
||
1592 | * @return string the attribute label |
||
1593 | * @see generateAttributeLabel() |
||
1594 | * @see attributeLabels() |
||
1595 | */ |
||
1596 | 57 | public function getAttributeLabel($attribute) |
|
1629 | |||
1630 | /** |
||
1631 | * Returns the text hint for the specified attribute. |
||
1632 | * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model. |
||
1633 | * @param string $attribute the attribute name |
||
1634 | * @return string the attribute hint |
||
1635 | * @see attributeHints() |
||
1636 | * @since 2.0.4 |
||
1637 | */ |
||
1638 | public function getAttributeHint($attribute) |
||
1671 | |||
1672 | /** |
||
1673 | * {@inheritdoc} |
||
1674 | * |
||
1675 | * The default implementation returns the names of the columns whose values have been populated into this record. |
||
1676 | */ |
||
1677 | public function fields() |
||
1683 | |||
1684 | /** |
||
1685 | * {@inheritdoc} |
||
1686 | * |
||
1687 | * The default implementation returns the names of the relations that have been populated into this record. |
||
1688 | */ |
||
1689 | public function extraFields() |
||
1695 | |||
1696 | /** |
||
1697 | * Sets the element value at the specified offset to null. |
||
1698 | * This method is required by the SPL interface [[\ArrayAccess]]. |
||
1699 | * It is implicitly called when you use something like `unset($model[$offset])`. |
||
1700 | * @param mixed $offset the offset to unset element |
||
1701 | */ |
||
1702 | 3 | public function offsetUnset($offset) |
|
1710 | |||
1711 | /** |
||
1712 | * Resets dependent related models checking if their links contain specific attribute. |
||
1713 | * @param string $attribute The changed attribute name. |
||
1714 | */ |
||
1715 | 15 | private function resetDependentRelations($attribute) |
|
1722 | |||
1723 | /** |
||
1724 | * Sets relation dependencies for a property |
||
1725 | * @param string $name property name |
||
1726 | * @param ActiveQueryInterface $relation relation instance |
||
1727 | */ |
||
1728 | 70 | private function setRelationDependencies($name, $relation) |
|
1741 | } |
||
1742 |