a409c0b821ce83e1382f68c1441f9df258efbe9c
[yaffs-website] / vendor / consolidation / annotated-command / src / CommandFileDiscovery.php
1 <?php
2 namespace Consolidation\AnnotatedCommand;
3
4 use Symfony\Component\Finder\Finder;
5
6 /**
7  * Do discovery presuming that the namespace of the command will
8  * contain the last component of the path.  This is the convention
9  * that should be used when searching for command files that are
10  * bundled with the modules of a framework.  The convention used
11  * is that the namespace for a module in a framework should start with
12  * the framework name followed by the module name.
13  *
14  * For example, if base namespace is "Drupal", then a command file in
15  * modules/default_content/src/CliTools/ExampleCommands.cpp
16  * will be in the namespace Drupal\default_content\CliTools.
17  *
18  * For global locations, the middle component of the namespace is
19  * omitted.  For example, if the base namespace is "Drupal", then
20  * a command file in __DRUPAL_ROOT__/CliTools/ExampleCommands.cpp
21  * will be in the namespace Drupal\CliTools.
22  *
23  * To discover namespaced commands in modules:
24  *
25  * $commandFiles = $discovery->discoverNamespaced($moduleList, '\Drupal');
26  *
27  * To discover global commands:
28  *
29  * $commandFiles = $discovery->discover($drupalRoot, '\Drupal');
30  */
31 class CommandFileDiscovery
32 {
33     /** @var string[] */
34     protected $excludeList;
35     /** @var string[] */
36     protected $searchLocations;
37     /** @var string */
38     protected $searchPattern = '*Commands.php';
39     /** @var boolean */
40     protected $includeFilesAtBase = true;
41     /** @var integer */
42     protected $searchDepth = 2;
43
44     public function __construct()
45     {
46         $this->excludeList = ['Exclude'];
47         $this->searchLocations = [
48             'Command',
49             'CliTools', // TODO: Maybe remove
50         ];
51     }
52
53     /**
54      * Specify whether to search for files at the base directory
55      * ($directoryList parameter to discover and discoverNamespaced
56      * methods), or only in the directories listed in the search paths.
57      *
58      * @param boolean $includeFilesAtBase
59      */
60     public function setIncludeFilesAtBase($includeFilesAtBase)
61     {
62         $this->includeFilesAtBase = $includeFilesAtBase;
63         return $this;
64     }
65
66     /**
67      * Set the list of excludes to add to the finder, replacing
68      * whatever was there before.
69      *
70      * @param array $excludeList The list of directory names to skip when
71      *   searching for command files.
72      */
73     public function setExcludeList($excludeList)
74     {
75         $this->excludeList = $excludeList;
76         return $this;
77     }
78
79     /**
80      * Add one more location to the exclude list.
81      *
82      * @param string $exclude One directory name to skip when searching
83      *   for command files.
84      */
85     public function addExclude($exclude)
86     {
87         $this->excludeList[] = $exclude;
88         return $this;
89     }
90
91     /**
92      * Set the search depth.  By default, fills immediately in the
93      * base directory are searched, plus all of the search locations
94      * to this specified depth.  If the search locations is set to
95      * an empty array, then the base directory is searched to this
96      * depth.
97      */
98     public function setSearchDepth($searchDepth)
99     {
100         $this->searchDepth = $searchDepth;
101         return $this;
102     }
103
104     /**
105      * Set the list of search locations to examine in each directory where
106      * command files may be found.  This replaces whatever was there before.
107      *
108      * @param array $searchLocations The list of locations to search for command files.
109      */
110     public function setSearchLocations($searchLocations)
111     {
112         $this->searchLocations = $searchLocations;
113         return $this;
114     }
115
116     /**
117      * Add one more location to the search location list.
118      *
119      * @param string $location One more relative path to search
120      *   for command files.
121      */
122     public function addSearchLocation($location)
123     {
124         $this->searchLocations[] = $location;
125         return $this;
126     }
127
128     /**
129      * Specify the pattern / regex used by the finder to search for
130      * command files.
131      */
132     public function setSearchPattern($searchPattern)
133     {
134         $this->searchPattern = $searchPattern;
135         return $this;
136     }
137
138     /**
139      * Given a list of directories, e.g. Drupal modules like:
140      *
141      *    core/modules/block
142      *    core/modules/dblog
143      *    modules/default_content
144      *
145      * Discover command files in any of these locations.
146      *
147      * @param string|string[] $directoryList Places to search for commands.
148      *
149      * @return array
150      */
151     public function discoverNamespaced($directoryList, $baseNamespace = '')
152     {
153         return $this->discover($this->convertToNamespacedList((array)$directoryList), $baseNamespace);
154     }
155
156     /**
157      * Given a simple list containing paths to directories, where
158      * the last component of the path should appear in the namespace,
159      * after the base namespace, this function will return an
160      * associative array mapping the path's basename (e.g. the module
161      * name) to the directory path.
162      *
163      * Module names must be unique.
164      *
165      * @param string[] $directoryList A list of module locations
166      *
167      * @return array
168      */
169     public function convertToNamespacedList($directoryList)
170     {
171         $namespacedArray = [];
172         foreach ((array)$directoryList as $directory) {
173             $namespacedArray[basename($directory)] = $directory;
174         }
175         return $namespacedArray;
176     }
177
178     /**
179      * Search for command files in the specified locations. This is the function that
180      * should be used for all locations that are NOT modules of a framework.
181      *
182      * @param string|string[] $directoryList Places to search for commands.
183      * @return array
184      */
185     public function discover($directoryList, $baseNamespace = '')
186     {
187         $commandFiles = [];
188         foreach ((array)$directoryList as $key => $directory) {
189             $itemsNamespace = $this->joinNamespace([$baseNamespace, $key]);
190             $commandFiles = array_merge(
191                 $commandFiles,
192                 $this->discoverCommandFiles($directory, $itemsNamespace),
193                 $this->discoverCommandFiles("$directory/src", $itemsNamespace)
194             );
195         }
196         return $commandFiles;
197     }
198
199     /**
200      * Search for command files in specific locations within a single directory.
201      *
202      * In each location, we will accept only a few places where command files
203      * can be found. This will reduce the need to search through many unrelated
204      * files.
205      *
206      * The default search locations include:
207      *
208      *    .
209      *    CliTools
210      *    src/CliTools
211      *
212      * The pattern we will look for is any file whose name ends in 'Commands.php'.
213      * A list of paths to found files will be returned.
214      */
215     protected function discoverCommandFiles($directory, $baseNamespace)
216     {
217         $commandFiles = [];
218         // In the search location itself, we will search for command files
219         // immediately inside the directory only.
220         if ($this->includeFilesAtBase) {
221             $commandFiles = $this->discoverCommandFilesInLocation(
222                 $directory,
223                 $this->getBaseDirectorySearchDepth(),
224                 $baseNamespace
225             );
226         }
227
228         // In the other search locations,
229         foreach ($this->searchLocations as $location) {
230             $itemsNamespace = $this->joinNamespace([$baseNamespace, $location]);
231             $commandFiles = array_merge(
232                 $commandFiles,
233                 $this->discoverCommandFilesInLocation(
234                     "$directory/$location",
235                     $this->getSearchDepth(),
236                     $itemsNamespace
237                 )
238             );
239         }
240         return $commandFiles;
241     }
242
243     /**
244      * Return a Finder search depth appropriate for our selected search depth.
245      *
246      * @return string
247      */
248     protected function getSearchDepth()
249     {
250         return $this->searchDepth <= 0 ? '== 0' : '<= ' . $this->searchDepth;
251     }
252
253     /**
254      * Return a Finder search depth for the base directory.  If the
255      * searchLocations array has been populated, then we will only search
256      * for files immediately inside the base directory; no traversal into
257      * deeper directories will be done, as that would conflict with the
258      * specification provided by the search locations.  If there is no
259      * search location, then we will search to whatever depth was specified
260      * by the client.
261      *
262      * @return string
263      */
264     protected function getBaseDirectorySearchDepth()
265     {
266         if (!empty($this->searchLocations)) {
267             return '== 0';
268         }
269         return $this->getSearchDepth();
270     }
271
272     /**
273      * Search for command files in just one particular location.  Returns
274      * an associative array mapping from the pathname of the file to the
275      * classname that it contains.  The pathname may be ignored if the search
276      * location is included in the autoloader.
277      *
278      * @param string $directory The location to search
279      * @param string $depth How deep to search (e.g. '== 0' or '< 2')
280      * @param string $baseNamespace Namespace to prepend to each classname
281      *
282      * @return array
283      */
284     protected function discoverCommandFilesInLocation($directory, $depth, $baseNamespace)
285     {
286         if (!is_dir($directory)) {
287             return [];
288         }
289         $finder = $this->createFinder($directory, $depth);
290
291         $commands = [];
292         foreach ($finder as $file) {
293             $relativePathName = $file->getRelativePathname();
294             $relativeNamespaceAndClassname = str_replace(
295                 ['/', '.php'],
296                 ['\\', ''],
297                 $relativePathName
298             );
299             $classname = $this->joinNamespace([$baseNamespace, $relativeNamespaceAndClassname]);
300             $commandFilePath = $this->joinPaths([$directory, $relativePathName]);
301             $commands[$commandFilePath] = $classname;
302         }
303
304         return $commands;
305     }
306
307     /**
308      * Create a Finder object for use in searching a particular directory
309      * location.
310      *
311      * @param string $directory The location to search
312      * @param string $depth The depth limitation
313      *
314      * @return Finder
315      */
316     protected function createFinder($directory, $depth)
317     {
318         $finder = new Finder();
319         $finder->files()
320             ->name($this->searchPattern)
321             ->in($directory)
322             ->depth($depth);
323
324         foreach ($this->excludeList as $item) {
325             $finder->exclude($item);
326         }
327
328         return $finder;
329     }
330
331     /**
332      * Combine the items of the provied array into a backslash-separated
333      * namespace string.  Empty and numeric items are omitted.
334      *
335      * @param array $namespaceParts List of components of a namespace
336      *
337      * @return string
338      */
339     protected function joinNamespace(array $namespaceParts)
340     {
341         return $this->joinParts(
342             '\\',
343             $namespaceParts,
344             function ($item) {
345                 return !is_numeric($item) && !empty($item);
346             }
347         );
348     }
349
350     /**
351      * Combine the items of the provied array into a slash-separated
352      * pathname.  Empty items are omitted.
353      *
354      * @param array $pathParts List of components of a path
355      *
356      * @return string
357      */
358     protected function joinPaths(array $pathParts)
359     {
360         $path = $this->joinParts(
361             '/',
362             $pathParts,
363             function ($item) {
364                 return !empty($item);
365             }
366         );
367         return str_replace(DIRECTORY_SEPARATOR, '/', $path);
368     }
369
370     /**
371      * Simple wrapper around implode and array_filter.
372      *
373      * @param string $delimiter
374      * @param array $parts
375      * @param callable $filterFunction
376      */
377     protected function joinParts($delimiter, $parts, $filterFunction)
378     {
379         $parts = array_map(
380             function ($item) use ($delimiter) {
381                 return rtrim($item, $delimiter);
382             },
383             $parts
384         );
385         return implode(
386             $delimiter,
387             array_filter($parts, $filterFunction)
388         );
389     }
390 }