31a907ab08ee02988252985c5cc3a12f30a18544
[yaffs-website] / src / GeneratorDiscovery.php
1 <?php
2
3 namespace DrupalCodeGenerator;
4
5 use RecursiveDirectoryIterator;
6 use RecursiveIteratorIterator;
7 use ReflectionClass;
8 use Symfony\Component\Filesystem\Filesystem;
9
10 /**
11  * Discovery of generator commands.
12  */
13 class GeneratorDiscovery {
14
15   const COMMAND_INTERFACE = '\DrupalCodeGenerator\Command\GeneratorInterface';
16
17   /**
18    * The file system utility.
19    *
20    * @var \Symfony\Component\Filesystem\Filesystem
21    */
22   protected $filesystem;
23
24   /**
25    * Constructs discovery object.
26    *
27    * @param \Symfony\Component\Filesystem\Filesystem $filesystem
28    *   The file system utility.
29    */
30   public function __construct(Filesystem $filesystem) {
31     $this->filesystem = $filesystem;
32   }
33
34   /**
35    * Finds and instantiates generator commands.
36    *
37    * @param array $command_directories
38    *   Directories to look up for commands.
39    * @param string $namespace
40    *   (Optional) The namespace to filter out commands.
41    *
42    * @return \Symfony\Component\Console\Command\Command[]
43    *   Array of generators.
44    */
45   public function getGenerators(array $command_directories, $namespace = '\DrupalCodeGenerator\Command') {
46     $commands = [];
47
48     foreach ($command_directories as $directory) {
49       $iterator = new RecursiveIteratorIterator(
50         new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS)
51       );
52       foreach ($iterator as $path => $file) {
53         if ($file->getExtension() == 'php') {
54           $relative_path = $this->filesystem->makePathRelative($path, $directory);
55           $class = $namespace . '\\' . str_replace('/', '\\', preg_replace('#\.php/$#', '', $relative_path));
56           if (class_exists($class)) {
57             $reflected_class = new ReflectionClass($class);
58             if (!$reflected_class->isInterface() && !$reflected_class->isAbstract() && $reflected_class->implementsInterface(self::COMMAND_INTERFACE)) {
59               $commands[] = new $class();
60             }
61           }
62         }
63       }
64     }
65
66     return $commands;
67   }
68
69 }