Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. <?php
  2.  
  3. namespace common\behaviors;
  4.  
  5. use yii\base\Behavior;
  6. use yii\db\ActiveRecord;
  7. use yii\db\AfterSaveEvent;
  8. use frontend\events\ChangedOrderStatusEvent;
  9. use yii\base\ErrorException;
  10. use yii\base\InvalidConfigException;
  11.  
  12. /**
  13. * The behavior triggers a status change event
  14. */
  15. class StatusEventsBehavior extends Behavior
  16. {
  17. /**
  18. * Attribute name
  19. *
  20. * @var string
  21. */
  22. public $attribute;
  23.  
  24. /**
  25. * Status name
  26. *
  27. * @var string|callable
  28. */
  29. public $statusName;
  30.  
  31. public function events()
  32. {
  33. return [
  34. ActiveRecord::EVENT_AFTER_INSERT => 'handle',
  35. ActiveRecord::EVENT_AFTER_UPDATE => 'handle',
  36. ];
  37. }
  38.  
  39. public function handle(AfterSaveEvent $event)
  40. {
  41. if (!$this->statusName || !$this->attribute) {
  42. throw new InvalidConfigException(Yii::t('common/behaviors/status-events-behavior', 'Attribute and status name must be specified.'));
  43. }
  44.  
  45. if (!$this->whetherTheStatusHasBeenChanged($event)) {
  46. return;
  47. }
  48.  
  49. $statusName = $this->getStatusName();
  50. if (!$statusName) {
  51. return;
  52. }
  53.  
  54. $event = new ChangedOrderStatusEvent([
  55. 'order' => $this->owner,
  56. 'statusName' => $statusName
  57. ]);
  58.  
  59. $this->owner->trigger($statusName, $event);
  60. }
  61.  
  62. protected function whetherTheStatusHasBeenChanged(AfterSaveEvent $event)
  63. {
  64. $newOrderStatusId = $this->owner->getAttribute($this->attribute);
  65. if (!$newOrderStatusId) {
  66. return false;
  67. }
  68.  
  69. if (!$event->changedAttributes || !array_key_exists($this->attribute, $event->changedAttributes)) {
  70. return false;
  71. }
  72.  
  73. if ($newOrderStatusId === $event->changedAttributes[$this->attribute]) {
  74. return false;
  75. }
  76.  
  77. return true;
  78. }
  79.  
  80. protected function getStatusName()
  81. {
  82. if (is_callable($this->statusName)) {
  83. $statusName = call_user_func($this->statusName, $this->owner);
  84. } elseif (is_string($this->statusName)) {
  85. $statusName = $this->statusName;
  86. } else {
  87. throw new ErrorException(Yii::t('common/behaviors/status-events-behavior', 'Status name must be string or callable.'));
  88. }
  89.  
  90. return $statusName;
  91. }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement