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