6e156919a1b392f16bdd532fe8b424be2f3a19db
[yaffs-website] / vendor / symfony / dependency-injection / Container.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\DependencyInjection;
13
14 use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException;
15 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
16 use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
17 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
18 use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
19 use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
20 use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
21
22 /**
23  * Container is a dependency injection container.
24  *
25  * It gives access to object instances (services).
26  *
27  * Services and parameters are simple key/pair stores.
28  *
29  * Parameter and service keys are case insensitive.
30  *
31  * A service can also be defined by creating a method named
32  * getXXXService(), where XXX is the camelized version of the id:
33  *
34  * <ul>
35  *   <li>request -> getRequestService()</li>
36  *   <li>mysql_session_storage -> getMysqlSessionStorageService()</li>
37  *   <li>symfony.mysql_session_storage -> getSymfony_MysqlSessionStorageService()</li>
38  * </ul>
39  *
40  * The container can have three possible behaviors when a service does not exist:
41  *
42  *  * EXCEPTION_ON_INVALID_REFERENCE: Throws an exception (the default)
43  *  * NULL_ON_INVALID_REFERENCE:      Returns null
44  *  * IGNORE_ON_INVALID_REFERENCE:    Ignores the wrapping command asking for the reference
45  *                                    (for instance, ignore a setter if the service does not exist)
46  *
47  * @author Fabien Potencier <fabien@symfony.com>
48  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
49  */
50 class Container implements ResettableContainerInterface
51 {
52     /**
53      * @var ParameterBagInterface
54      */
55     protected $parameterBag;
56
57     protected $services = array();
58     protected $methodMap = array();
59     protected $aliases = array();
60     protected $loading = array();
61
62     /**
63      * @internal
64      */
65     protected $privates = array();
66
67     private $underscoreMap = array('_' => '', '.' => '_', '\\' => '_');
68     private $envCache = array();
69
70     /**
71      * @param ParameterBagInterface $parameterBag A ParameterBagInterface instance
72      */
73     public function __construct(ParameterBagInterface $parameterBag = null)
74     {
75         $this->parameterBag = $parameterBag ?: new EnvPlaceholderParameterBag();
76     }
77
78     /**
79      * Compiles the container.
80      *
81      * This method does two things:
82      *
83      *  * Parameter values are resolved;
84      *  * The parameter bag is frozen.
85      */
86     public function compile()
87     {
88         $this->parameterBag->resolve();
89
90         $this->parameterBag = new FrozenParameterBag($this->parameterBag->all());
91     }
92
93     /**
94      * Returns true if the container parameter bag are frozen.
95      *
96      * @return bool true if the container parameter bag are frozen, false otherwise
97      */
98     public function isFrozen()
99     {
100         return $this->parameterBag instanceof FrozenParameterBag;
101     }
102
103     /**
104      * Gets the service container parameter bag.
105      *
106      * @return ParameterBagInterface A ParameterBagInterface instance
107      */
108     public function getParameterBag()
109     {
110         return $this->parameterBag;
111     }
112
113     /**
114      * Gets a parameter.
115      *
116      * @param string $name The parameter name
117      *
118      * @return mixed The parameter value
119      *
120      * @throws InvalidArgumentException if the parameter is not defined
121      */
122     public function getParameter($name)
123     {
124         return $this->parameterBag->get($name);
125     }
126
127     /**
128      * Checks if a parameter exists.
129      *
130      * @param string $name The parameter name
131      *
132      * @return bool The presence of parameter in container
133      */
134     public function hasParameter($name)
135     {
136         return $this->parameterBag->has($name);
137     }
138
139     /**
140      * Sets a parameter.
141      *
142      * @param string $name  The parameter name
143      * @param mixed  $value The parameter value
144      */
145     public function setParameter($name, $value)
146     {
147         $this->parameterBag->set($name, $value);
148     }
149
150     /**
151      * Sets a service.
152      *
153      * Setting a service to null resets the service: has() returns false and get()
154      * behaves in the same way as if the service was never created.
155      *
156      * @param string $id      The service identifier
157      * @param object $service The service instance
158      */
159     public function set($id, $service)
160     {
161         $id = strtolower($id);
162
163         if ('service_container' === $id) {
164             throw new InvalidArgumentException('You cannot set service "service_container".');
165         }
166
167         if (isset($this->aliases[$id])) {
168             unset($this->aliases[$id]);
169         }
170
171         $this->services[$id] = $service;
172
173         if (null === $service) {
174             unset($this->services[$id]);
175         }
176
177         if (isset($this->privates[$id])) {
178             if (null === $service) {
179                 @trigger_error(sprintf('Unsetting the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED);
180                 unset($this->privates[$id]);
181             } else {
182                 @trigger_error(sprintf('Setting the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0. A new public service will be created instead.', $id), E_USER_DEPRECATED);
183             }
184         }
185     }
186
187     /**
188      * Returns true if the given service is defined.
189      *
190      * @param string $id The service identifier
191      *
192      * @return bool true if the service is defined, false otherwise
193      */
194     public function has($id)
195     {
196         for ($i = 2;;) {
197             if (isset($this->privates[$id])) {
198                 @trigger_error(sprintf('Checking for the existence of the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED);
199             }
200
201             if ('service_container' === $id
202                 || isset($this->aliases[$id])
203                 || isset($this->services[$id])
204             ) {
205                 return true;
206             }
207
208             if (isset($this->methodMap[$id])) {
209                 return true;
210             }
211
212             if (--$i && $id !== $lcId = strtolower($id)) {
213                 $id = $lcId;
214                 continue;
215             }
216
217             // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
218             // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
219             if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this, 'get'.strtr($id, $this->underscoreMap).'Service')) {
220                 @trigger_error('Generating a dumped container without populating the method map is deprecated since 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED);
221
222                 return true;
223             }
224
225             return false;
226         }
227     }
228
229     /**
230      * Gets a service.
231      *
232      * If a service is defined both through a set() method and
233      * with a get{$id}Service() method, the former has always precedence.
234      *
235      * @param string $id              The service identifier
236      * @param int    $invalidBehavior The behavior when the service does not exist
237      *
238      * @return object The associated service
239      *
240      * @throws ServiceCircularReferenceException When a circular reference is detected
241      * @throws ServiceNotFoundException          When the service is not defined
242      * @throws \Exception                        if an exception has been thrown when the service has been resolved
243      *
244      * @see Reference
245      */
246     public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE)
247     {
248         // Attempt to retrieve the service by checking first aliases then
249         // available services. Service IDs are case insensitive, however since
250         // this method can be called thousands of times during a request, avoid
251         // calling strtolower() unless necessary.
252         for ($i = 2;;) {
253             if (isset($this->privates[$id])) {
254                 @trigger_error(sprintf('Requesting the "%s" private service is deprecated since Symfony 3.2 and won\'t be supported anymore in Symfony 4.0.', $id), E_USER_DEPRECATED);
255             }
256             if (isset($this->aliases[$id])) {
257                 $id = $this->aliases[$id];
258             }
259
260             // Re-use shared service instance if it exists.
261             if (isset($this->services[$id])) {
262                 return $this->services[$id];
263             }
264             if ('service_container' === $id) {
265                 return $this;
266             }
267
268             if (isset($this->loading[$id])) {
269                 throw new ServiceCircularReferenceException($id, array_keys($this->loading));
270             }
271
272             if (isset($this->methodMap[$id])) {
273                 $method = $this->methodMap[$id];
274             } elseif (--$i && $id !== $lcId = strtolower($id)) {
275                 $id = $lcId;
276                 continue;
277             } elseif (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class && method_exists($this, $method = 'get'.strtr($id, $this->underscoreMap).'Service')) {
278                 // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
279                 // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
280                 @trigger_error('Generating a dumped container without populating the method map is deprecated since 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED);
281                 // $method is set to the right value, proceed
282             } else {
283                 if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
284                     if (!$id) {
285                         throw new ServiceNotFoundException($id);
286                     }
287
288                     $alternatives = array();
289                     foreach ($this->getServiceIds() as $knownId) {
290                         $lev = levenshtein($id, $knownId);
291                         if ($lev <= strlen($id) / 3 || false !== strpos($knownId, $id)) {
292                             $alternatives[] = $knownId;
293                         }
294                     }
295
296                     throw new ServiceNotFoundException($id, null, null, $alternatives);
297                 }
298
299                 return;
300             }
301
302             $this->loading[$id] = true;
303
304             try {
305                 $service = $this->$method();
306             } catch (\Exception $e) {
307                 unset($this->services[$id]);
308
309                 throw $e;
310             } finally {
311                 unset($this->loading[$id]);
312             }
313
314             return $service;
315         }
316     }
317
318     /**
319      * Returns true if the given service has actually been initialized.
320      *
321      * @param string $id The service identifier
322      *
323      * @return bool true if service has already been initialized, false otherwise
324      */
325     public function initialized($id)
326     {
327         $id = strtolower($id);
328
329         if (isset($this->aliases[$id])) {
330             $id = $this->aliases[$id];
331         }
332
333         if ('service_container' === $id) {
334             return false;
335         }
336
337         return isset($this->services[$id]);
338     }
339
340     /**
341      * {@inheritdoc}
342      */
343     public function reset()
344     {
345         $this->services = array();
346     }
347
348     /**
349      * Gets all service ids.
350      *
351      * @return array An array of all defined service ids
352      */
353     public function getServiceIds()
354     {
355         $ids = array();
356
357         if (!$this->methodMap && !$this instanceof ContainerBuilder && __CLASS__ !== static::class) {
358             // We only check the convention-based factory in a compiled container (i.e. a child class other than a ContainerBuilder,
359             // and only when the dumper has not generated the method map (otherwise the method map is considered to be fully populated by the dumper)
360             @trigger_error('Generating a dumped container without populating the method map is deprecated since 3.2 and will be unsupported in 4.0. Update your dumper to generate the method map.', E_USER_DEPRECATED);
361
362             foreach (get_class_methods($this) as $method) {
363                 if (preg_match('/^get(.+)Service$/', $method, $match)) {
364                     $ids[] = self::underscore($match[1]);
365                 }
366             }
367         }
368         $ids[] = 'service_container';
369
370         return array_unique(array_merge($ids, array_keys($this->methodMap), array_keys($this->services)));
371     }
372
373     /**
374      * Camelizes a string.
375      *
376      * @param string $id A string to camelize
377      *
378      * @return string The camelized string
379      */
380     public static function camelize($id)
381     {
382         return strtr(ucwords(strtr($id, array('_' => ' ', '.' => '_ ', '\\' => '_ '))), array(' ' => ''));
383     }
384
385     /**
386      * A string to underscore.
387      *
388      * @param string $id The string to underscore
389      *
390      * @return string The underscored string
391      */
392     public static function underscore($id)
393     {
394         return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), str_replace('_', '.', $id)));
395     }
396
397     /**
398      * Fetches a variable from the environment.
399      *
400      * @param string The name of the environment variable
401      *
402      * @return scalar The value to use for the provided environment variable name
403      *
404      * @throws EnvNotFoundException When the environment variable is not found and has no default value
405      */
406     protected function getEnv($name)
407     {
408         if (isset($this->envCache[$name]) || array_key_exists($name, $this->envCache)) {
409             return $this->envCache[$name];
410         }
411         if (isset($_ENV[$name])) {
412             return $this->envCache[$name] = $_ENV[$name];
413         }
414         if (false !== $env = getenv($name)) {
415             return $this->envCache[$name] = $env;
416         }
417         if (!$this->hasParameter("env($name)")) {
418             throw new EnvNotFoundException($name);
419         }
420
421         return $this->envCache[$name] = $this->getParameter("env($name)");
422     }
423
424     private function __clone()
425     {
426     }
427 }