YamlFileLoader.php 14 KB
Newer Older
1
<?php
2
// @codingStandardsIgnoreFile
3 4 5

namespace Drupal\Core\DependencyInjection;

6
use Drupal\Component\FileCache\FileCacheFactory;
7
use Drupal\Component\Serialization\Yaml;
8 9 10 11 12
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Reference;
13
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
14 15 16 17

/**
 * YamlFileLoader loads YAML files service definitions.
 *
18 19 20 21 22 23 24 25 26 27 28
 * Drupal does not use Symfony's Config component, and Symfony's dependency on
 * it cannot be removed easily. Therefore, this is a partial but mostly literal
 * copy of upstream, which does not depend on the Config component.
 *
 * @see \Symfony\Component\DependencyInjection\Loader\YamlFileLoader
 * @see https://github.com/symfony/symfony/pull/10920
 *
 * NOTE: 98% of this code is a literal copy of Symfony's YamlFileLoader.
 *
 * This file does NOT follow Drupal coding standards, so as to simplify future
 * synchronizations.
29
 */
30 31 32 33
class YamlFileLoader
{

    /**
34
     * @var \Drupal\Core\DependencyInjection\ContainerBuilder $container
35
     */
36
    protected $container;
37 38

    /**
39 40 41
     * File cache object.
     *
     * @var \Drupal\Component\FileCache\FileCacheInterface
42
     */
43
    protected $fileCache;
44

45

46
    public function __construct(ContainerBuilder $container)
47
    {
48 49
        $this->container = $container;
        $this->fileCache = FileCacheFactory::get('container_yaml_loader');
50 51
    }

52 53 54 55 56 57 58
    /**
     * Loads a Yaml file.
     *
     * @param mixed  $file The resource
     */
    public function load($file)
    {
59 60 61 62 63 64 65
        // Load from the file cache, fall back to loading the file.
        // @todo Refactor this to cache parsed definition objects in
        //   https://www.drupal.org/node/2464053
        $content = $this->fileCache->get($file);
        if (!$content) {
            $content = $this->loadFile($file);
            $this->fileCache->set($file, $content);
66
        }
67

68 69
        // Not supported.
        //$this->container->addResource(new FileResource($path));
70

71 72 73 74
        // empty file
        if (null === $content) {
            return;
        }
75

76 77 78
        // imports
        // Not supported.
        //$this->parseImports($content, $file);
79

80 81
        // parameters
        if (isset($content['parameters'])) {
82 83 84 85
            if (!is_array($content['parameters'])) {
                throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in %s. Check your YAML syntax.', $file));
            }

86 87 88 89
            foreach ($content['parameters'] as $key => $value) {
                $this->container->setParameter($key, $this->resolveServices($value));
            }
        }
90

91 92 93
        // extensions
        // Not supported.
        //$this->loadFromExtensions($content);
94

95 96
        // services
        $this->parseDefinitions($content, $file);
97 98
    }

99 100 101 102 103 104 105 106 107 108 109
    /**
     * Parses definitions
     *
     * @param array  $content
     * @param string $file
     */
    private function parseDefinitions($content, $file)
    {
        if (!isset($content['services'])) {
            return;
        }
110

111 112 113 114
        if (!is_array($content['services'])) {
            throw new InvalidArgumentException(sprintf('The "services" key should contain an array in %s. Check your YAML syntax.', $file));
        }

115 116 117
        foreach ($content['services'] as $id => $service) {
            $this->parseDefinition($id, $service, $file);
        }
118 119
    }

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    /**
     * Parses a definition.
     *
     * @param string $id
     * @param array  $service
     * @param string $file
     *
     * @throws InvalidArgumentException When tags are invalid
     */
    private function parseDefinition($id, $service, $file)
    {
        if (is_string($service) && 0 === strpos($service, '@')) {
            $this->container->setAlias($id, substr($service, 1));

            return;
135 136 137 138 139 140 141 142
        }

        if (!is_array($service)) {
            throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but %s found for service "%s" in %s. Check your YAML syntax.', gettype($service), $id, $file));
        }

        if (isset($service['alias'])) {
            $public = !array_key_exists('public', $service) || (bool) $service['public'];
143 144 145 146
            $this->container->setAlias($id, new Alias($service['alias'], $public));

            return;
        }
147

148 149 150 151 152
        if (isset($service['parent'])) {
            $definition = new DefinitionDecorator($service['parent']);
        } else {
            $definition = new Definition();
        }
153

154 155 156
        if (isset($service['class'])) {
            $definition->setClass($service['class']);
        }
157

158 159 160 161
        if (isset($service['shared'])) {
            $definition->setShared($service['shared']);
        }

162
        if (isset($service['scope'])) {
163 164 165 166
            if ('request' !== $id) {
                @trigger_error(sprintf('The "scope" key of service "%s" in file "%s" is deprecated since version 2.8 and will be removed in 3.0.', $id, $file), E_USER_DEPRECATED);
            }
            $definition->setScope($service['scope'], false);
167
        }
168

169 170 171
        if (isset($service['synthetic'])) {
            $definition->setSynthetic($service['synthetic']);
        }
172

173
        if (isset($service['synchronized'])) {
174
            $definition->setSynchronized($service['synchronized'], 'request' !== $id);
175
        }
176

177 178
        if (isset($service['lazy'])) {
            $definition->setLazy($service['lazy']);
179 180
        }

181 182 183
        if (isset($service['public'])) {
            $definition->setPublic($service['public']);
        }
184

185 186
        if (isset($service['abstract'])) {
            $definition->setAbstract($service['abstract']);
187 188
        }

189 190 191 192
        if (array_key_exists('deprecated', $service)) {
            $definition->setDeprecated(true, $service['deprecated']);
        }

193 194 195 196 197 198 199 200 201 202 203 204 205
        if (isset($service['factory'])) {
            if (is_string($service['factory'])) {
                if (strpos($service['factory'], ':') !== false && strpos($service['factory'], '::') === false) {
                    $parts = explode(':', $service['factory']);
                    $definition->setFactory(array($this->resolveServices('@'.$parts[0]), $parts[1]));
                } else {
                    $definition->setFactory($service['factory']);
                }
            } else {
                $definition->setFactory(array($this->resolveServices($service['factory'][0]), $service['factory'][1]));
            }
        }

206 207 208
        if (isset($service['factory_class'])) {
            $definition->setFactoryClass($service['factory_class']);
        }
209

210 211 212
        if (isset($service['factory_method'])) {
            $definition->setFactoryMethod($service['factory_method']);
        }
213

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        if (isset($service['factory_service'])) {
            $definition->setFactoryService($service['factory_service']);
        }

        if (isset($service['file'])) {
            $definition->setFile($service['file']);
        }

        if (isset($service['arguments'])) {
            $definition->setArguments($this->resolveServices($service['arguments']));
        }

        if (isset($service['properties'])) {
            $definition->setProperties($this->resolveServices($service['properties']));
        }

        if (isset($service['configurator'])) {
            if (is_string($service['configurator'])) {
                $definition->setConfigurator($service['configurator']);
            } else {
                $definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1]));
            }
        }

        if (isset($service['calls'])) {
239 240 241 242
            if (!is_array($service['calls'])) {
                throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
            }

243
            foreach ($service['calls'] as $call) {
244 245 246 247 248 249 250 251 252
                if (isset($call['method'])) {
                    $method = $call['method'];
                    $args = isset($call['arguments']) ? $this->resolveServices($call['arguments']) : array();
                } else {
                    $method = $call[0];
                    $args = isset($call[1]) ? $this->resolveServices($call[1]) : array();
                }

                $definition->addMethodCall($method, $args);
253 254 255 256 257
            }
        }

        if (isset($service['tags'])) {
            if (!is_array($service['tags'])) {
258
                throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
259 260 261
            }

            foreach ($service['tags'] as $tag) {
262 263 264 265
                if (!is_array($tag)) {
                    throw new InvalidArgumentException(sprintf('A "tags" entry must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
                }

266 267 268 269 270 271 272 273 274
                if (!isset($tag['name'])) {
                    throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file));
                }

                $name = $tag['name'];
                unset($tag['name']);

                foreach ($tag as $attribute => $value) {
                    if (!is_scalar($value) && null !== $value) {
275
                        throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s" in %s. Check your YAML syntax.', $id, $name, $attribute, $file));
276 277 278 279 280 281 282
                    }
                }

                $definition->addTag($name, $tag);
            }
        }

283 284
        if (isset($service['decorates'])) {
            $renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null;
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
            $priority = isset($service['decoration_priority']) ? $service['decoration_priority'] : 0;
            $definition->setDecoratedService($service['decorates'], $renameId, $priority);
        }

        if (isset($service['autowire'])) {
            $definition->setAutowired($service['autowire']);
        }

        if (isset($service['autowiring_types'])) {
            if (is_string($service['autowiring_types'])) {
                $definition->addAutowiringType($service['autowiring_types']);
            } else {
                if (!is_array($service['autowiring_types'])) {
                    throw new InvalidArgumentException(sprintf('Parameter "autowiring_types" must be a string or an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
                }

                foreach ($service['autowiring_types'] as $autowiringType) {
                    if (!is_string($autowiringType)) {
                        throw new InvalidArgumentException(sprintf('A "autowiring_types" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file));
                    }

                    $definition->addAutowiringType($autowiringType);
                }
            }
309 310
        }

311
        $this->container->setDefinition($id, $definition);
312 313
    }

314 315 316 317 318 319
    /**
     * Loads a YAML file.
     *
     * @param string $file
     *
     * @return array The file content
320 321
     *
     * @throws InvalidArgumentException when the given file is not a local file or when it does not exist
322 323 324 325 326 327 328 329 330 331 332 333
     */
    protected function loadFile($file)
    {
        if (!stream_is_local($file)) {
            throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
        }

        if (!file_exists($file)) {
            throw new InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file));
        }

        return $this->validate(Yaml::decode(file_get_contents($file)), $file);
334
    }
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

    /**
     * Validates a YAML file.
     *
     * @param mixed  $content
     * @param string $file
     *
     * @return array
     *
     * @throws InvalidArgumentException When service file is not valid
     */
    private function validate($content, $file)
    {
        if (null === $content) {
            return $content;
        }

        if (!is_array($content)) {
353
            throw new InvalidArgumentException(sprintf('The service file "%s" is not valid. It should contain an array. Check your YAML syntax.', $file));
354 355 356 357 358 359 360
        }

        if ($invalid_keys = array_diff_key($content, array('parameters' => 1, 'services' => 1))) {
            throw new InvalidArgumentException(sprintf('The service file "%s" is not valid: it contains invalid keys %s. Services have to be added under "services" and Parameters under "parameters".', $file, $invalid_keys));
        }

        return $content;
361 362
    }

363 364 365
    /**
     * Resolves services.
     *
366
     * @param string|array $value
367
     *
368
     * @return array|string|Reference
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
     */
    private function resolveServices($value)
    {
        if (is_array($value)) {
            $value = array_map(array($this, 'resolveServices'), $value);
        } elseif (is_string($value) &&  0 === strpos($value, '@=')) {
            // Not supported.
            //return new Expression(substr($value, 2));
            throw new InvalidArgumentException(sprintf("'%s' is an Expression, but expressions are not supported.", $value));
        } elseif (is_string($value) &&  0 === strpos($value, '@')) {
            if (0 === strpos($value, '@@')) {
                $value = substr($value, 1);
                $invalidBehavior = null;
            } elseif (0 === strpos($value, '@?')) {
                $value = substr($value, 2);
                $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
            } else {
                $value = substr($value, 1);
                $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
            }

            if ('=' === substr($value, -1)) {
                $value = substr($value, 0, -1);
                $strict = false;
            } else {
                $strict = true;
            }

            if (null !== $invalidBehavior) {
                $value = new Reference($value, $invalidBehavior, $strict);
            }
        }

        return $value;
    }
404 405

}