123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186 |
- <?php
- namespace yii\behaviors;
- use Closure;
- use yii\base\Behavior;
- use yii\base\Event;
- use yii\db\ActiveRecord;
- class AttributesBehavior extends Behavior
- {
-
- public $attributes = [];
-
- public $order = [];
-
- public $skipUpdateOnClean = true;
-
- public $preserveNonEmptyValues = false;
-
- public function events()
- {
- return array_fill_keys(
- array_reduce($this->attributes, function ($carry, $item) {
- return array_merge($carry, array_keys($item));
- }, []),
- 'evaluateAttributes'
- );
- }
-
- public function evaluateAttributes($event)
- {
- if ($this->skipUpdateOnClean
- && $event->name === ActiveRecord::EVENT_BEFORE_UPDATE
- && empty($this->owner->dirtyAttributes)
- ) {
- return;
- }
- $attributes = array_keys(array_filter($this->attributes, function ($carry) use ($event) {
- return array_key_exists($event->name, $carry);
- }));
- if (!empty($this->order[$event->name])) {
- $attributes = array_merge(
- array_intersect((array) $this->order[$event->name], $attributes),
- array_diff($attributes, (array) $this->order[$event->name]));
- }
- foreach ($attributes as $attribute) {
- if ($this->preserveNonEmptyValues && !empty($this->owner->$attribute)) {
- continue;
- }
- $this->owner->$attribute = $this->getValue($attribute, $event);
- }
- }
-
- protected function getValue($attribute, $event)
- {
- if (!isset($this->attributes[$attribute][$event->name])) {
- return null;
- }
- $value = $this->attributes[$attribute][$event->name];
- if ($value instanceof Closure || (is_array($value) && is_callable($value))) {
- return $value($event, $attribute);
- }
- return $value;
- }
- }
|