Version 1
[yaffs-website] / web / core / lib / Drupal / Core / DependencyInjection / DependencySerializationTrait.php
1 <?php
2
3 namespace Drupal\Core\DependencyInjection;
4
5 use Symfony\Component\DependencyInjection\ContainerInterface;
6
7 /**
8  * Provides dependency injection friendly methods for serialization.
9  */
10 trait DependencySerializationTrait {
11
12   /**
13    * An array of service IDs keyed by property name used for serialization.
14    *
15    * @var array
16    */
17   protected $_serviceIds = [];
18
19   /**
20    * {@inheritdoc}
21    */
22   public function __sleep() {
23     $this->_serviceIds = [];
24     $vars = get_object_vars($this);
25     foreach ($vars as $key => $value) {
26       if (is_object($value) && isset($value->_serviceId)) {
27         // If a class member was instantiated by the dependency injection
28         // container, only store its ID so it can be used to get a fresh object
29         // on unserialization.
30         $this->_serviceIds[$key] = $value->_serviceId;
31         unset($vars[$key]);
32       }
33       // Special case the container, which might not have a service ID.
34       elseif ($value instanceof ContainerInterface) {
35         $this->_serviceIds[$key] = 'service_container';
36         unset($vars[$key]);
37       }
38     }
39
40     return array_keys($vars);
41   }
42
43   /**
44    * {@inheritdoc}
45    */
46   public function __wakeup() {
47     // Tests in isolation potentially unserialize in the parent process.
48     if (isset($GLOBALS['__PHPUNIT_BOOTSTRAP']) && !\Drupal::hasContainer()) {
49       return;
50     }
51     $container = \Drupal::getContainer();
52     foreach ($this->_serviceIds as $key => $service_id) {
53       $this->$key = $container->get($service_id);
54     }
55     $this->_serviceIds = [];
56   }
57
58 }