basicemitter.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * Copyright (c) 2013 Robin Appelman <icewind@owncloud.com>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace OC\Hooks;
  9. abstract class BasicEmitter implements Emitter {
  10. /**
  11. * @var (callable[])[] $listeners
  12. */
  13. protected $listeners = array();
  14. /**
  15. * @param string $scope
  16. * @param string $method
  17. * @param callable $callback
  18. */
  19. public function listen($scope, $method, $callback) {
  20. $eventName = $scope . '::' . $method;
  21. if (!isset($this->listeners[$eventName])) {
  22. $this->listeners[$eventName] = array();
  23. }
  24. if (array_search($callback, $this->listeners[$eventName]) === false) {
  25. $this->listeners[$eventName][] = $callback;
  26. }
  27. }
  28. /**
  29. * @param string $scope optional
  30. * @param string $method optional
  31. * @param callable $callback optional
  32. */
  33. public function removeListener($scope = null, $method = null, $callback = null) {
  34. $names = array();
  35. $allNames = array_keys($this->listeners);
  36. if ($scope and $method) {
  37. $name = $scope . '::' . $method;
  38. if (isset($this->listeners[$name])) {
  39. $names[] = $name;
  40. }
  41. } elseif ($scope) {
  42. foreach ($allNames as $name) {
  43. $parts = explode('::', $name, 2);
  44. if ($parts[0] == $scope) {
  45. $names[] = $name;
  46. }
  47. }
  48. } elseif ($method) {
  49. foreach ($allNames as $name) {
  50. $parts = explode('::', $name, 2);
  51. if ($parts[1] == $method) {
  52. $names[] = $name;
  53. }
  54. }
  55. } else {
  56. $names = $allNames;
  57. }
  58. foreach ($names as $name) {
  59. if ($callback) {
  60. $index = array_search($callback, $this->listeners[$name]);
  61. if ($index !== false) {
  62. unset($this->listeners[$name][$index]);
  63. }
  64. } else {
  65. $this->listeners[$name] = array();
  66. }
  67. }
  68. }
  69. /**
  70. * @param string $scope
  71. * @param string $method
  72. * @param array $arguments optional
  73. */
  74. protected function emit($scope, $method, $arguments = array()) {
  75. $eventName = $scope . '::' . $method;
  76. if (isset($this->listeners[$eventName])) {
  77. foreach ($this->listeners[$eventName] as $callback) {
  78. call_user_func_array($callback, $arguments);
  79. }
  80. }
  81. }
  82. }