Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace common\behaviors;
- use yii\base\Behavior;
- use yii\db\ActiveRecord;
- use yii\db\AfterSaveEvent;
- use frontend\events\ChangedOrderStatusEvent;
- use yii\base\ErrorException;
- use yii\base\InvalidConfigException;
- /**
- * The behavior triggers a status change event
- */
- class StatusEventsBehavior extends Behavior
- {
- /**
- * Attribute name
- *
- * @var string
- */
- public $attribute;
- /**
- * Status name
- *
- * @var string|callable
- */
- public $statusName;
- public function events()
- {
- return [
- ActiveRecord::EVENT_AFTER_INSERT => 'handle',
- ActiveRecord::EVENT_AFTER_UPDATE => 'handle',
- ];
- }
- public function handle(AfterSaveEvent $event)
- {
- if (!$this->statusName || !$this->attribute) {
- throw new InvalidConfigException(Yii::t('common/behaviors/status-events-behavior', 'Attribute and status name must be specified.'));
- }
- if (!$this->whetherTheStatusHasBeenChanged($event)) {
- return;
- }
- $statusName = $this->getStatusName();
- if (!$statusName) {
- return;
- }
- $event = new ChangedOrderStatusEvent([
- 'order' => $this->owner,
- 'statusName' => $statusName
- ]);
- $this->owner->trigger($statusName, $event);
- }
- protected function whetherTheStatusHasBeenChanged(AfterSaveEvent $event)
- {
- $newOrderStatusId = $this->owner->getAttribute($this->attribute);
- if (!$newOrderStatusId) {
- return false;
- }
- if (!$event->changedAttributes || !array_key_exists($this->attribute, $event->changedAttributes)) {
- return false;
- }
- if ($newOrderStatusId === $event->changedAttributes[$this->attribute]) {
- return false;
- }
- return true;
- }
- protected function getStatusName()
- {
- if (is_callable($this->statusName)) {
- $statusName = call_user_func($this->statusName, $this->owner);
- } elseif (is_string($this->statusName)) {
- $statusName = $this->statusName;
- } else {
- throw new ErrorException(Yii::t('common/behaviors/status-events-behavior', 'Status name must be string or callable.'));
- }
- return $statusName;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement