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

namespace Drupal\Core\DependencyInjection;

6
use Drupal\Component\FileCache\FileCacheFactory;
7
use Drupal\Core\Serialization\Yaml;
8 9 10
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
11
use Symfony\Component\DependencyInjection\ChildDefinition;
12
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
    /**
     * Loads a Yaml file.
     *
55 56
     * @param mixed $file
     *   The resource
57 58 59
     */
    public function load($file)
    {
60 61 62 63 64
        // Load from the file cache, fall back to loading the file.
        $content = $this->fileCache->get($file);
        if (!$content) {
            $content = $this->loadFile($file);
            $this->fileCache->set($file, $content);
65
        }
66

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

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

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

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

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

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

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

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

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

114 115 116 117 118 119 120 121
        // Some extensions split up their dependencies into multiple files.
        if (isset($content['_provider'])) {
            $provider = $content['_provider'];
        }
        else {
            $basename = basename($file);
            list($provider, ) = explode('.', $basename, 2);
        }
122
        foreach ($content['services'] as $id => $service) {
123
            $service['tags'][] = ['name' => '_provider', 'provider' => $provider];
124 125
            $this->parseDefinition($id, $service, $file);
        }
126 127
    }

128 129 130 131
    /**
     * Parses a definition.
     *
     * @param string $id
132
     * @param array $service
133 134
     * @param string $file
     *
135 136
     * @throws InvalidArgumentException
     *   When tags are invalid.
137 138 139 140 141 142 143
     */
    private function parseDefinition($id, $service, $file)
    {
        if (is_string($service) && 0 === strpos($service, '@')) {
            $this->container->setAlias($id, substr($service, 1));

            return;
144 145 146 147 148 149 150 151
        }

        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'];
152 153 154 155
            $this->container->setAlias($id, new Alias($service['alias'], $public));

            return;
        }
156

157
        if (isset($service['parent'])) {
158
            $definition = new ChildDefinition($service['parent']);
159 160 161
        } else {
            $definition = new Definition();
        }
162

163 164 165
        if (isset($service['class'])) {
            $definition->setClass($service['class']);
        }
166

167 168 169 170
        if (isset($service['shared'])) {
            $definition->setShared($service['shared']);
        }

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

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

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

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

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

191 192 193 194 195 196 197 198 199 200 201 202 203
        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]));
            }
        }

204
        if (isset($service['factory_class'])) {
205
            $definition->setFactory($service['factory_class']);
206
        }
207

208
        if (isset($service['factory_method'])) {
209
            $definition->setFactory($service['factory_method']);
210
        }
211

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

        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'])) {
237 238 239 240
            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));
            }

241
            foreach ($service['calls'] as $call) {
242 243 244 245 246 247 248 249 250
                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);
251 252 253 254 255
            }
        }

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

            foreach ($service['tags'] as $tag) {
260 261 262 263
                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));
                }

264 265 266 267 268 269 270 271 272
                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) {
273
                        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));
274 275 276 277 278 279 280
                    }
                }

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

281 282
        if (isset($service['decorates'])) {
            $renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null;
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
            $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);
                }
            }
307 308
        }

309
        $this->container->setDefinition($id, $definition);
310 311
    }

312 313 314 315 316 317
    /**
     * Loads a YAML file.
     *
     * @param string $file
     *
     * @return array The file content
318
     *
319 320
     * @throws InvalidArgumentException
     *   When the given file is not a local file or when it does not exist.
321 322 323 324 325 326 327 328 329 330 331
     */
    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));
        }

332
        return $this->validate(Yaml::decode(file_get_contents($file)), $file);
333
    }
334 335 336 337

    /**
     * Validates a YAML file.
     *
338
     * @param mixed $content
339 340 341 342
     * @param string $file
     *
     * @return array
     *
343 344
     * @throws InvalidArgumentException
     *   When service file is not valid.
345 346 347 348 349 350 351 352
     */
    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

}