Thanks to visit codestin.com
Credit goes to pastebin.com

Guest User

Untitled

a guest
Apr 11th, 2017
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.11 KB | None | 0 0
  1. <?php
  2. /**
  3.  * License: MIT
  4.  *
  5.  */
  6.  
  7. /**
  8. Usage:  add to your AppBundle:
  9.  
  10. first argument of constructor is an array of namespaces where your services lives.
  11.  
  12.         $container->addCompilerPass(
  13.             new AutowireAutoAliasPass([
  14.                 'System',
  15.                 'DataSource'
  16.             ]),
  17.             PassConfig::TYPE_BEFORE_OPTIMIZATION
  18.         );
  19.  
  20. */
  21.  
  22.  
  23. namespace AppBundle\Compiler;
  24.  
  25.  
  26. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  27. use Symfony\Component\DependencyInjection\ContainerBuilder;
  28.  
  29. class AutowireAutoAliasPass implements CompilerPassInterface
  30. {
  31.     /**
  32.      * @var array
  33.      */
  34.     private $namespaces;
  35.  
  36.     public function __construct(array $namespaces)
  37.     {
  38.         $this->namespaces = array_map(function ($ns) {
  39.             return preg_match("/\\$/", $ns) ? $ns : $ns . "\\";
  40.         }, $namespaces);
  41.     }
  42.  
  43.     public function process(ContainerBuilder $container)
  44.     {
  45.         foreach ($container->getDefinitions() as $serviceId => $definition) {
  46.             if ($definition->isAbstract() || !$definition->getClass()) {
  47.                 continue;
  48.             }
  49.  
  50.             if ($container->hasAlias($definition->getClass())) {
  51.                 continue;
  52.             }
  53.  
  54.             $className = $definition->getClass();
  55.  
  56.             if (class_exists($className) && $this->belongsToDefinedNamespace($className)) {
  57.  
  58.                 $allTypes = array_filter(
  59.                     [$className] + class_parents($className) + class_implements($className),
  60.                     function ($type) use ($container) {
  61.                         return $this->belongsToDefinedNamespace($type) && !$container->hasAlias($type);
  62.                     }
  63.                 );
  64.  
  65.                 foreach ($allTypes as $type) {
  66.                     $container->setAlias($type, $serviceId);
  67.                 }
  68.             }
  69.         }
  70.     }
  71.  
  72.     private function belongsToDefinedNamespace($className)
  73.     {
  74.         foreach ($this->namespaces as $ns) {
  75.             if (substr($className, 0, strlen($ns)) === $ns) return true;
  76.         }
  77.         return false;
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment