KernelDestructionSubscriber.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  4. use Symfony\Component\DependencyInjection\ContainerAwareTrait;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Event\PostResponseEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. /**
  9. * Destructs services that are initiated and tagged with "needs_destruction".
  10. *
  11. * @see \Drupal\Core\DestructableInterface
  12. */
  13. class KernelDestructionSubscriber implements EventSubscriberInterface, ContainerAwareInterface {
  14. use ContainerAwareTrait;
  15. /**
  16. * Holds an array of service ID's that will require destruction.
  17. *
  18. * @var array
  19. */
  20. protected $services = [];
  21. /**
  22. * Registers a service for destruction.
  23. *
  24. * Calls to this method are set up in
  25. * RegisterServicesForDestructionPass::process().
  26. *
  27. * @param string $id
  28. * Name of the service.
  29. */
  30. public function registerService($id) {
  31. $this->services[] = $id;
  32. }
  33. /**
  34. * Invoked by the terminate kernel event.
  35. *
  36. * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
  37. * The event object.
  38. */
  39. public function onKernelTerminate(PostResponseEvent $event) {
  40. foreach ($this->services as $id) {
  41. // Check if the service was initialized during this request, destruction
  42. // is not necessary if the service was not used.
  43. if ($this->container->initialized($id)) {
  44. $service = $this->container->get($id);
  45. $service->destruct();
  46. }
  47. }
  48. }
  49. /**
  50. * Registers the methods in this class that should be listeners.
  51. *
  52. * @return array
  53. * An array of event listener definitions.
  54. */
  55. public static function getSubscribedEvents() {
  56. $events[KernelEvents::TERMINATE][] = ['onKernelTerminate', 100];
  57. return $events;
  58. }
  59. }