This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/DependencyInjection/Loader/FileLoader.php

181 lines
7.1 KiB
PHP
Raw Normal View History

2010-01-04 14:26:20 +00:00
<?php
/*
* This file is part of the Symfony package.
2010-01-04 14:26:20 +00:00
*
* (c) Fabien Potencier <fabien@symfony.com>
2010-01-04 14:26:20 +00:00
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
2010-01-04 14:26:20 +00:00
*/
namespace Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\Config\Loader\FileLoader as BaseFileLoader;
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Config\Resource\GlobResource;
2010-01-04 14:26:20 +00:00
/**
* FileLoader is the abstract class used by all built-in loaders that are file based.
*
* @author Fabien Potencier <fabien@symfony.com>
2010-01-04 14:26:20 +00:00
*/
abstract class FileLoader extends BaseFileLoader
2010-01-04 14:26:20 +00:00
{
protected $container;
protected $isLoadingInstanceof = false;
protected $instanceof = array();
2010-01-04 14:26:20 +00:00
public function __construct(ContainerBuilder $container, FileLocatorInterface $locator)
2010-01-04 14:26:20 +00:00
{
$this->container = $container;
parent::__construct($locator);
}
/**
* Registers a set of classes as services using PSR-4 for discovery.
*
* @param Definition $prototype A definition to use as template
* @param string $namespace The namespace prefix of classes in the scanned directory
* @param string $resource The directory to look for classes, glob-patterns allowed
* @param string $exclude A globed path of files to exclude
*/
public function registerClasses(Definition $prototype, $namespace, $resource, $exclude = null)
{
if ('\\' !== substr($namespace, -1)) {
throw new InvalidArgumentException(sprintf('Namespace prefix must end with a "\\": %s.', $namespace));
}
if (!preg_match('/^(?:[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+\\\\)++$/', $namespace)) {
throw new InvalidArgumentException(sprintf('Namespace is not a valid PSR-4 prefix: %s.', $namespace));
}
$classes = $this->findClasses($namespace, $resource, $exclude);
// prepare for deep cloning
$serializedPrototype = serialize($prototype);
$interfaces = array();
$singlyImplemented = array();
foreach ($classes as $class => $errorMessage) {
if (interface_exists($class, false)) {
$interfaces[] = $class;
} else {
$this->setDefinition($class, $definition = unserialize($serializedPrototype));
if (null !== $errorMessage) {
$definition->addError($errorMessage);
continue;
}
foreach (class_implements($class, false) as $interface) {
$singlyImplemented[$interface] = isset($singlyImplemented[$interface]) ? false : $class;
}
}
}
foreach ($interfaces as $interface) {
if (!empty($singlyImplemented[$interface])) {
$this->container->setAlias($interface, $singlyImplemented[$interface])
->setPublic(false);
}
}
}
/**
* Registers a definition in the container with its instanceof-conditionals.
*
* @param string $id
* @param Definition $definition
*/
protected function setDefinition($id, Definition $definition)
{
if ($this->isLoadingInstanceof) {
if (!$definition instanceof ChildDefinition) {
throw new InvalidArgumentException(sprintf('Invalid type definition "%s": ChildDefinition expected, "%s" given.', $id, get_class($definition)));
}
$this->instanceof[$id] = $definition;
} else {
Not allowing autoconfigure, instanceofConditionals or defaults for ChildDefinition Also, not allowing arguments or method calls for autoconfigure. This is a safety mechanism, since we don't have merging logic. It will allow us to add this in the future if we want to. The reason is that parent-child definitions are a different mechanism for "inheritance" than instanceofConditionas and defaults... creating some edge cases when trying to figure out which settings "win". For example: Suppose a child and parent definitions are defined in different YAML files. The child receives public: false from its _defaults, and the parent receives public: true from its _defaults. Should the final child definition be public: true (so the parent overrides the child, even though it only came from _defaults) or public: false (where the child wins... even though it was only set from its _defaults). Or, if the parent is explicitly set to public: true, should that override the public: false of the child (which it got from its _defaults)? On one hand, the parent is being explicitly set. On the other hand, the child is explicitly in a file settings _defaults public to false. There's no correct answer. There are also problems with instanceof. The importance goes: defaults < instanceof < service definition But how does parent-child relationships fit into that? If a child has public: false from an _instanceof, but the parent explicitly sets public: true, which wins? Should we assume the parent definition wins because it's explicitly set? Or would the _instanceof win, because that's being explicitly applied to the child definition's class by an _instanceof that lives in the same file as that class (whereas the parent definition may live in a different file). Because of this, @nicolas-grekas and I (we also talked a bit to Fabien) decided that the complexity was growing too much. The solution is to not allow any of these new feature to be used by ChildDefinition objects. In other words, when you want some sort of "inheritance" for your service, you should *either* giving your service a parent *or* using defaults and instanceof. And instead of silently not applying defaults and instanceof to child definitions, I think it's better to scream that it's not supported.
2017-04-27 16:48:07 +01:00
$this->container->setDefinition($id, $definition instanceof ChildDefinition ? $definition : $definition->setInstanceofConditionals($this->instanceof));
}
}
private function findClasses($namespace, $pattern, $excludePattern)
{
$parameterBag = $this->container->getParameterBag();
$excludePaths = array();
$excludePrefix = null;
if ($excludePattern) {
$excludePattern = $parameterBag->unescapeValue($parameterBag->resolveValue($excludePattern));
foreach ($this->glob($excludePattern, true, $resource) as $path => $info) {
if (null === $excludePrefix) {
$excludePrefix = $resource->getPrefix();
}
// normalize Windows slashes
$excludePaths[str_replace('\\', '/', $path)] = true;
}
}
$pattern = $parameterBag->unescapeValue($parameterBag->resolveValue($pattern));
$classes = array();
$extRegexp = defined('HHVM_VERSION') ? '/\\.(?:php|hh)$/' : '/\\.php$/';
$prefixLen = null;
foreach ($this->glob($pattern, true, $resource) as $path => $info) {
if (null === $prefixLen) {
$prefixLen = strlen($resource->getPrefix());
if ($excludePrefix && 0 !== strpos($excludePrefix, $resource->getPrefix())) {
throw new InvalidArgumentException(sprintf('Invalid "exclude" pattern when importing classes for "%s": make sure your "exclude" pattern (%s) is a subset of the "resource" pattern (%s)', $namespace, $excludePattern, $pattern));
}
}
if (isset($excludePaths[str_replace('\\', '/', $path)])) {
continue;
}
2017-01-17 13:46:23 +00:00
if (!preg_match($extRegexp, $path, $m) || !$info->isReadable()) {
continue;
}
$class = $namespace.ltrim(str_replace('/', '\\', substr($path, $prefixLen, -strlen($m[0]))), '\\');
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+$/', $class)) {
continue;
}
try {
$r = $this->container->getReflectionClass($class);
} catch (\ReflectionException $e) {
$classes[$class] = sprintf(
'While discovering services from namespace "%s", an error was thrown when processing the class "%s": "%s".',
$namespace,
$class,
$e->getMessage()
);
continue;
}
// check to make sure the expected class exists
if (!$r) {
throw new InvalidArgumentException(sprintf('Expected to find class "%s" in file "%s" while importing services from resource "%s", but it was not found! Check the namespace prefix used with the resource.', $class, $path, $pattern));
}
if ($r->isInstantiable() || $r->isInterface()) {
$classes[$class] = null;
}
}
// track only for new & removed files
if ($resource instanceof GlobResource) {
$this->container->addResource($resource);
} else {
foreach ($resource as $path) {
$this->container->fileExists($path, false);
}
}
return $classes;
}
2010-01-04 14:26:20 +00:00
}