ServiceEventListener.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright 2019 Christoph Wurst <christoph@winzerhof-wurst.at>
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. *
  9. * @license GNU AGPL version 3 or any later version
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License as
  13. * published by the Free Software Foundation, either version 3 of the
  14. * License, or (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. */
  25. namespace OC\EventDispatcher;
  26. use OCP\AppFramework\QueryException;
  27. use OCP\EventDispatcher\Event;
  28. use OCP\EventDispatcher\IEventListener;
  29. use OCP\IServerContainer;
  30. use Psr\Log\LoggerInterface;
  31. use function sprintf;
  32. /**
  33. * Lazy service event listener
  34. *
  35. * Makes it possible to lazy-route a dispatched event to a service instance
  36. * created by the service container
  37. */
  38. final class ServiceEventListener {
  39. /** @var IServerContainer */
  40. private $container;
  41. /** @var string */
  42. private $class;
  43. /** @var LoggerInterface */
  44. private $logger;
  45. /** @var null|IEventListener */
  46. private $service;
  47. public function __construct(IServerContainer $container,
  48. string $class,
  49. LoggerInterface $logger) {
  50. $this->container = $container;
  51. $this->class = $class;
  52. $this->logger = $logger;
  53. }
  54. public function __invoke(Event $event) {
  55. if ($this->service === null) {
  56. try {
  57. // TODO: fetch from the app containers, otherwise any custom services,
  58. // parameters and aliases won't be resolved.
  59. // See https://github.com/nextcloud/server/issues/27793 for details.
  60. $this->service = $this->container->query($this->class);
  61. } catch (QueryException $e) {
  62. $this->logger->error(
  63. sprintf(
  64. 'Could not load event listener service %s: %s. Make sure the class is auto-loadable by the Nextcloud server container',
  65. $this->class,
  66. $e->getMessage()
  67. ),
  68. [
  69. 'exception' => $e,
  70. ]
  71. );
  72. return;
  73. }
  74. }
  75. $this->service->handle($event);
  76. }
  77. }