Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * License: MIT
- *
- */
- /**
- Usage: add to your AppBundle:
- first argument of constructor is an array of namespaces where your services lives.
- $container->addCompilerPass(
- new AutowireAutoAliasPass([
- 'System',
- 'DataSource'
- ]),
- PassConfig::TYPE_BEFORE_OPTIMIZATION
- );
- */
- namespace AppBundle\Compiler;
- use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
- use Symfony\Component\DependencyInjection\ContainerBuilder;
- class AutowireAutoAliasPass implements CompilerPassInterface
- {
- /**
- * @var array
- */
- private $namespaces;
- public function __construct(array $namespaces)
- {
- $this->namespaces = array_map(function ($ns) {
- return preg_match("/\\$/", $ns) ? $ns : $ns . "\\";
- }, $namespaces);
- }
- public function process(ContainerBuilder $container)
- {
- foreach ($container->getDefinitions() as $serviceId => $definition) {
- if ($definition->isAbstract() || !$definition->getClass()) {
- continue;
- }
- if ($container->hasAlias($definition->getClass())) {
- continue;
- }
- $className = $definition->getClass();
- if (class_exists($className) && $this->belongsToDefinedNamespace($className)) {
- $allTypes = array_filter(
- [$className] + class_parents($className) + class_implements($className),
- function ($type) use ($container) {
- return $this->belongsToDefinedNamespace($type) && !$container->hasAlias($type);
- }
- );
- foreach ($allTypes as $type) {
- $container->setAlias($type, $serviceId);
- }
- }
- }
- }
- private function belongsToDefinedNamespace($className)
- {
- foreach ($this->namespaces as $ns) {
- if (substr($className, 0, strlen($ns)) === $ns) return true;
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment