0a9849ca3fee375f26b28a60c8ad8ef6037bed8a
[GitHub/WoltLab/WCF.git] /
1 <?php
2 /**
3 * PHP-DI
4 *
5 * @link http://mnapoli.github.com/PHP-DI/
6 * @copyright Matthieu Napoli (http://mnapoli.fr/)
7 * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
8 */
9
10 namespace DI\Definition\Resolver;
11
12 use DI\Definition\Definition;
13 use DI\Definition\EnvironmentVariableDefinition;
14 use DI\Definition\Exception\DefinitionException;
15 use DI\Definition\Helper\DefinitionHelper;
16
17 /**
18 * Resolves a environment variable definition to a value.
19 *
20 * @author James Harris <james.harris@icecave.com.au>
21 */
22 class EnvironmentVariableResolver implements DefinitionResolver
23 {
24 /**
25 * @var DefinitionResolver
26 */
27 private $definitionResolver;
28
29 /**
30 * @var callable
31 */
32 private $variableReader;
33
34 public function __construct(DefinitionResolver $definitionResolver, $variableReader = 'getenv')
35 {
36 $this->definitionResolver = $definitionResolver;
37 $this->variableReader = $variableReader;
38 }
39
40 /**
41 * Resolve an environment variable definition to a value.
42 *
43 * @param EnvironmentVariableDefinition $definition
44 *
45 * {@inheritdoc}
46 */
47 public function resolve(Definition $definition, array $parameters = [])
48 {
49 $value = call_user_func($this->variableReader, $definition->getVariableName());
50
51 if (false !== $value) {
52 return $value;
53 }
54
55 if (!$definition->isOptional()) {
56 throw new DefinitionException(sprintf(
57 "The environment variable '%s' has not been defined",
58 $definition->getVariableName()
59 ));
60 }
61
62 $value = $definition->getDefaultValue();
63
64 // Nested definition
65 if ($value instanceof DefinitionHelper) {
66 return $this->definitionResolver->resolve($value->getDefinition(''));
67 }
68
69 return $value;
70 }
71
72 /**
73 * @param EnvironmentVariableDefinition $definition
74 *
75 * {@inheritdoc}
76 */
77 public function isResolvable(Definition $definition, array $parameters = [])
78 {
79 return true;
80 }
81 }