123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150 |
- <?php
- namespace yii\behaviors;
- use Closure;
- use yii\base\Behavior;
- use yii\base\Event;
- use yii\db\ActiveRecord;
- class AttributeBehavior extends Behavior
- {
-
- public $attributes = [];
-
- public $value;
-
- public $skipUpdateOnClean = true;
-
- public $preserveNonEmptyValues = false;
-
- public function events()
- {
- return array_fill_keys(
- array_keys($this->attributes),
- 'evaluateAttributes'
- );
- }
-
- public function evaluateAttributes($event)
- {
- if ($this->skipUpdateOnClean
- && $event->name == ActiveRecord::EVENT_BEFORE_UPDATE
- && empty($this->owner->dirtyAttributes)
- ) {
- return;
- }
- if (!empty($this->attributes[$event->name])) {
- $attributes = (array) $this->attributes[$event->name];
- $value = $this->getValue($event);
- foreach ($attributes as $attribute) {
-
- if (is_string($attribute)) {
- if ($this->preserveNonEmptyValues && !empty($this->owner->$attribute)) {
- continue;
- }
- $this->owner->$attribute = $value;
- }
- }
- }
- }
-
- protected function getValue($event)
- {
- if ($this->value instanceof Closure || (is_array($this->value) && is_callable($this->value))) {
- return call_user_func($this->value, $event);
- }
- return $this->value;
- }
- }
|