EmitterTrait.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Hooks;
  8. /**
  9. * @deprecated 18.0.0 use events and the \OCP\EventDispatcher\IEventDispatcher service
  10. */
  11. trait EmitterTrait {
  12. /**
  13. * @var callable[][] $listeners
  14. */
  15. protected $listeners = [];
  16. /**
  17. * @param string $scope
  18. * @param string $method
  19. * @param callable $callback
  20. * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher::addListener
  21. */
  22. public function listen($scope, $method, callable $callback) {
  23. $eventName = $scope . '::' . $method;
  24. if (!isset($this->listeners[$eventName])) {
  25. $this->listeners[$eventName] = [];
  26. }
  27. if (!in_array($callback, $this->listeners[$eventName], true)) {
  28. $this->listeners[$eventName][] = $callback;
  29. }
  30. }
  31. /**
  32. * @param string $scope optional
  33. * @param string $method optional
  34. * @param callable $callback optional
  35. * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher::removeListener
  36. */
  37. public function removeListener($scope = null, $method = null, ?callable $callback = null) {
  38. $names = [];
  39. $allNames = array_keys($this->listeners);
  40. if ($scope and $method) {
  41. $name = $scope . '::' . $method;
  42. if (isset($this->listeners[$name])) {
  43. $names[] = $name;
  44. }
  45. } elseif ($scope) {
  46. foreach ($allNames as $name) {
  47. $parts = explode('::', $name, 2);
  48. if ($parts[0] == $scope) {
  49. $names[] = $name;
  50. }
  51. }
  52. } elseif ($method) {
  53. foreach ($allNames as $name) {
  54. $parts = explode('::', $name, 2);
  55. if ($parts[1] == $method) {
  56. $names[] = $name;
  57. }
  58. }
  59. } else {
  60. $names = $allNames;
  61. }
  62. foreach ($names as $name) {
  63. if ($callback) {
  64. $index = array_search($callback, $this->listeners[$name], true);
  65. if ($index !== false) {
  66. unset($this->listeners[$name][$index]);
  67. }
  68. } else {
  69. $this->listeners[$name] = [];
  70. }
  71. }
  72. }
  73. /**
  74. * @param string $scope
  75. * @param string $method
  76. * @param array $arguments optional
  77. * @deprecated 18.0.0 use \OCP\EventDispatcher\IEventDispatcher::dispatchTyped
  78. */
  79. protected function emit($scope, $method, array $arguments = []) {
  80. $eventName = $scope . '::' . $method;
  81. if (isset($this->listeners[$eventName])) {
  82. foreach ($this->listeners[$eventName] as $callback) {
  83. call_user_func_array($callback, $arguments);
  84. }
  85. }
  86. }
  87. }