Observer.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Event;
  7. use Magento\Framework\Event;
  8. /**
  9. * @api
  10. * @since 100.0.2
  11. */
  12. class Observer extends \Magento\Framework\DataObject
  13. {
  14. /**
  15. * Checks the observer's event_regex against event's name
  16. *
  17. * @param Event $event
  18. * @return boolean
  19. */
  20. public function isValidFor(Event $event)
  21. {
  22. return $this->getEventName() === $event->getName();
  23. }
  24. /**
  25. * Dispatches an event to observer's callback
  26. *
  27. * @param Event $event
  28. * @return $this
  29. */
  30. public function dispatch(Event $event)
  31. {
  32. if (!$this->isValidFor($event)) {
  33. return $this;
  34. }
  35. $callback = $this->getCallback();
  36. $this->setEvent($event);
  37. $_profilerKey = 'OBSERVER: ';
  38. if (is_object($callback[0])) {
  39. $_profilerKey .= get_class($callback[0]);
  40. } else {
  41. $_profilerKey .= (string)$callback[0];
  42. }
  43. $_profilerKey .= ' -> ' . $callback[1];
  44. \Magento\Framework\Profiler::start($_profilerKey);
  45. call_user_func($callback, $this);
  46. \Magento\Framework\Profiler::stop($_profilerKey);
  47. return $this;
  48. }
  49. /**
  50. * @return string
  51. */
  52. public function getName()
  53. {
  54. return $this->getData('name');
  55. }
  56. /**
  57. * @param string $data
  58. * @return \Magento\Framework\DataObject
  59. */
  60. public function setName($data)
  61. {
  62. return $this->setData('name', $data);
  63. }
  64. /**
  65. * @return string
  66. */
  67. public function getEventName()
  68. {
  69. return $this->getData('event_name');
  70. }
  71. /**
  72. * @param string $data
  73. * @return \Magento\Framework\DataObject
  74. */
  75. public function setEventName($data)
  76. {
  77. return $this->setData('event_name', $data);
  78. }
  79. /**
  80. * @return string
  81. */
  82. public function getCallback()
  83. {
  84. return $this->getData('callback');
  85. }
  86. /**
  87. * @param string $data
  88. * @return \Magento\Framework\DataObject
  89. */
  90. public function setCallback($data)
  91. {
  92. return $this->setData('callback', $data);
  93. }
  94. /**
  95. * Get observer event object
  96. *
  97. * @return Event
  98. */
  99. public function getEvent()
  100. {
  101. return $this->getData('event');
  102. }
  103. /**
  104. * @param mixed $data
  105. * @return \Magento\Framework\DataObject
  106. */
  107. public function setEvent($data)
  108. {
  109. return $this->setData('event', $data);
  110. }
  111. }