CommandFileDiscovery::getSearchDepth()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
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
 * WARNING:
32
 *
33
 * This class is deprecated. Commandfile discovery is complicated, and does
34
 * not work from within phar files. It is recommended to instead use a static
35
 * list of command classes as shown in https://github.com/g1a/starter/blob/master/example
36
 *
37
 * For a better alternative when implementing a plugin mechanism, see
38
 * https://robo.li/extending/#register-command-files-via-psr-4-autoloading
39
 */
40
class CommandFileDiscovery
41
{
42
    /** @var string[] */
43
    protected $excludeList;
44
    /** @var string[] */
45
    protected $searchLocations;
46
    /** @var string */
47
    protected $searchPattern = '*Commands.php';
48
    /** @var boolean */
49
    protected $includeFilesAtBase = true;
50
    /** @var integer */
51
    protected $searchDepth = 2;
52
    /** @var bool */
53
    protected $followLinks = false;
54
    /** @var string[] */
55
    protected $strippedNamespaces;
56
57
    public function __construct()
58
    {
59
        $this->excludeList = ['Exclude'];
60
        $this->searchLocations = [
61
            'Command',
62
            'CliTools', // TODO: Maybe remove
63
        ];
64
    }
65
66
    /**
67
     * Specify whether to search for files at the base directory
68
     * ($directoryList parameter to discover and discoverNamespaced
69
     * methods), or only in the directories listed in the search paths.
70
     *
71
     * @param boolean $includeFilesAtBase
72
     */
73
    public function setIncludeFilesAtBase($includeFilesAtBase)
74
    {
75
        $this->includeFilesAtBase = $includeFilesAtBase;
76
        return $this;
77
    }
78
79
    /**
80
     * Set the list of excludes to add to the finder, replacing
81
     * whatever was there before.
82
     *
83
     * @param array $excludeList The list of directory names to skip when
84
     *   searching for command files.
85
     */
86
    public function setExcludeList($excludeList)
87
    {
88
        $this->excludeList = $excludeList;
89
        return $this;
90
    }
91
92
    /**
93
     * Add one more location to the exclude list.
94
     *
95
     * @param string $exclude One directory name to skip when searching
96
     *   for command files.
97
     */
98
    public function addExclude($exclude)
99
    {
100
        $this->excludeList[] = $exclude;
101
        return $this;
102
    }
103
104
    /**
105
     * Set the search depth.  By default, fills immediately in the
106
     * base directory are searched, plus all of the search locations
107
     * to this specified depth.  If the search locations is set to
108
     * an empty array, then the base directory is searched to this
109
     * depth.
110
     */
111
    public function setSearchDepth($searchDepth)
112
    {
113
        $this->searchDepth = $searchDepth;
114
        return $this;
115
    }
116
117
    /**
118
     * Specify that the discovery object should follow symlinks. By
119
     * default, symlinks are not followed.
120
     */
121
    public function followLinks($followLinks = true)
122
    {
123
        $this->followLinks = $followLinks;
124
        return $this;
125
    }
126
127
    /**
128
     * Set the list of search locations to examine in each directory where
129
     * command files may be found.  This replaces whatever was there before.
130
     *
131
     * @param array $searchLocations The list of locations to search for command files.
132
     */
133
    public function setSearchLocations($searchLocations)
134
    {
135
        $this->searchLocations = $searchLocations;
136
        return $this;
137
    }
138
139
    /**
140
     * Set a particular namespace part to ignore. This is useful in plugin
141
     * mechanisms where the plugin is placed by Composer.
142
     *
143
     * For example, Drush extensions are placed in `./drush/Commands`.
144
     * If the Composer installer path is `"drush/Commands/contrib/{$name}": ["type:drupal-drush"]`,
145
     * then Composer will place the command files in `drush/Commands/contrib`.
146
     * The namespace should not be any different in this instance than if
147
     * the extension were placed in `drush/Commands`, though, so Drush therefore
148
     * calls `ignoreNamespacePart('contrib', 'Commands')`. This causes the
149
     * `contrib` component to be removed from the namespace if it follows
150
     * the namespace `Commands`. If the '$base' parameter is not specified, then
151
     * the ignored portion of the namespace may appear anywhere in the path.
152
     */
153
    public function ignoreNamespacePart($ignore, $base = '')
154
    {
155
        $replacementPart = '\\';
156
        if (!empty($base)) {
157
            $replacementPart .= $base . '\\';
158
        }
159
        $ignoredPart = $replacementPart . $ignore . '\\';
160
        $this->strippedNamespaces[$ignoredPart] = $replacementPart;
161
162
        return $this;
163
    }
164
165
    /**
166
     * Add one more location to the search location list.
167
     *
168
     * @param string $location One more relative path to search
169
     *   for command files.
170
     */
171
    public function addSearchLocation($location)
172
    {
173
        $this->searchLocations[] = $location;
174
        return $this;
175
    }
176
177
    /**
178
     * Specify the pattern / regex used by the finder to search for
179
     * command files.
180
     */
181
    public function setSearchPattern($searchPattern)
182
    {
183
        $this->searchPattern = $searchPattern;
184
        return $this;
185
    }
186
187
    /**
188
     * Given a list of directories, e.g. Drupal modules like:
189
     *
190
     *    core/modules/block
191
     *    core/modules/dblog
192
     *    modules/default_content
193
     *
194
     * Discover command files in any of these locations.
195
     *
196
     * @param string|string[] $directoryList Places to search for commands.
197
     *
198
     * @return array
199
     */
200
    public function discoverNamespaced($directoryList, $baseNamespace = '')
201
    {
202
        return $this->discover($this->convertToNamespacedList((array)$directoryList), $baseNamespace);
203
    }
204
205
    /**
206
     * Given a simple list containing paths to directories, where
207
     * the last component of the path should appear in the namespace,
208
     * after the base namespace, this function will return an
209
     * associative array mapping the path's basename (e.g. the module
210
     * name) to the directory path.
211
     *
212
     * Module names must be unique.
213
     *
214
     * @param string[] $directoryList A list of module locations
215
     *
216
     * @return array
217
     */
218
    public function convertToNamespacedList($directoryList)
219
    {
220
        $namespacedArray = [];
221
        foreach ((array)$directoryList as $directory) {
222
            $namespacedArray[basename($directory)] = $directory;
223
        }
224
        return $namespacedArray;
225
    }
226
227
    /**
228
     * Search for command files in the specified locations. This is the function that
229
     * should be used for all locations that are NOT modules of a framework.
230
     *
231
     * @param string|string[] $directoryList Places to search for commands.
232
     * @return array
233
     */
234
    public function discover($directoryList, $baseNamespace = '')
235
    {
236
        $commandFiles = [];
237
        foreach ((array)$directoryList as $key => $directory) {
238
            $itemsNamespace = $this->joinNamespace([$baseNamespace, $key]);
239
            $commandFiles = array_merge(
240
                $commandFiles,
241
                $this->discoverCommandFiles($directory, $itemsNamespace),
242
                $this->discoverCommandFiles("$directory/src", $itemsNamespace)
243
            );
244
        }
245
        return $this->fixNamespaces($commandFiles);
246
    }
247
248
    /**
249
     * fixNamespaces will alter the namespaces in the commandFiles
250
     * result to remove the Composer placement directory, if any.
251
     */
252
    protected function fixNamespaces($commandFiles)
253
    {
254
        // Do nothing unless the client told us to remove some namespace components.
255
        if (empty($this->strippedNamespaces)) {
256
            return $commandFiles;
257
        }
258
259
        // Strip out any part of the namespace the client did not want.
260
        // @see CommandFileDiscovery::ignoreNamespacePart
261
        return array_map(
262
            function ($fqcn) {
263
                return str_replace(
264
                    array_keys($this->strippedNamespaces),
265
                    array_values($this->strippedNamespaces),
266
                    $fqcn
267
                );
268
            },
269
            $commandFiles
270
        );
271
    }
272
273
    /**
274
     * Search for command files in specific locations within a single directory.
275
     *
276
     * In each location, we will accept only a few places where command files
277
     * can be found. This will reduce the need to search through many unrelated
278
     * files.
279
     *
280
     * The default search locations include:
281
     *
282
     *    .
283
     *    CliTools
284
     *    src/CliTools
285
     *
286
     * The pattern we will look for is any file whose name ends in 'Commands.php'.
287
     * A list of paths to found files will be returned.
288
     */
289
    protected function discoverCommandFiles($directory, $baseNamespace)
290
    {
291
        $commandFiles = [];
292
        // In the search location itself, we will search for command files
293
        // immediately inside the directory only.
294
        if ($this->includeFilesAtBase) {
295
            $commandFiles = $this->discoverCommandFilesInLocation(
296
                $directory,
297
                $this->getBaseDirectorySearchDepth(),
298
                $baseNamespace
299
            );
300
        }
301
302
        // In the other search locations,
303
        foreach ($this->searchLocations as $location) {
304
            $itemsNamespace = $this->joinNamespace([$baseNamespace, $location]);
305
            $commandFiles = array_merge(
306
                $commandFiles,
307
                $this->discoverCommandFilesInLocation(
308
                    "$directory/$location",
309
                    $this->getSearchDepth(),
310
                    $itemsNamespace
311
                )
312
            );
313
        }
314
        return $commandFiles;
315
    }
316
317
    /**
318
     * Return a Finder search depth appropriate for our selected search depth.
319
     *
320
     * @return string
321
     */
322
    protected function getSearchDepth()
323
    {
324
        return $this->searchDepth <= 0 ? '== 0' : '<= ' . $this->searchDepth;
325
    }
326
327
    /**
328
     * Return a Finder search depth for the base directory.  If the
329
     * searchLocations array has been populated, then we will only search
330
     * for files immediately inside the base directory; no traversal into
331
     * deeper directories will be done, as that would conflict with the
332
     * specification provided by the search locations.  If there is no
333
     * search location, then we will search to whatever depth was specified
334
     * by the client.
335
     *
336
     * @return string
337
     */
338
    protected function getBaseDirectorySearchDepth()
339
    {
340
        if (!empty($this->searchLocations)) {
341
            return '== 0';
342
        }
343
        return $this->getSearchDepth();
344
    }
345
346
    /**
347
     * Search for command files in just one particular location.  Returns
348
     * an associative array mapping from the pathname of the file to the
349
     * classname that it contains.  The pathname may be ignored if the search
350
     * location is included in the autoloader.
351
     *
352
     * @param string $directory The location to search
353
     * @param string $depth How deep to search (e.g. '== 0' or '< 2')
354
     * @param string $baseNamespace Namespace to prepend to each classname
355
     *
356
     * @return array
357
     */
358
    protected function discoverCommandFilesInLocation($directory, $depth, $baseNamespace)
359
    {
360
        if (!is_dir($directory)) {
361
            return [];
362
        }
363
        $finder = $this->createFinder($directory, $depth);
364
365
        $commands = [];
366
        foreach ($finder as $file) {
367
            $relativePathName = $file->getRelativePathname();
368
            $relativeNamespaceAndClassname = str_replace(
369
                ['/', '-', '.php'],
370
                ['\\', '_', ''],
371
                $relativePathName
372
            );
373
            $classname = $this->joinNamespace([$baseNamespace, $relativeNamespaceAndClassname]);
374
            $commandFilePath = $this->joinPaths([$directory, $relativePathName]);
375
            $commands[$commandFilePath] = $classname;
376
        }
377
378
        return $commands;
379
    }
380
381
    /**
382
     * Create a Finder object for use in searching a particular directory
383
     * location.
384
     *
385
     * @param string $directory The location to search
386
     * @param string $depth The depth limitation
387
     *
388
     * @return Finder
389
     */
390
    protected function createFinder($directory, $depth)
391
    {
392
        $finder = new Finder();
393
        $finder->files()
394
            ->name($this->searchPattern)
395
            ->in($directory)
396
            ->depth($depth);
397
398
        foreach ($this->excludeList as $item) {
399
            $finder->exclude($item);
400
        }
401
402
        if ($this->followLinks) {
403
            $finder->followLinks();
404
        }
405
406
        return $finder;
407
    }
408
409
    /**
410
     * Combine the items of the provied array into a backslash-separated
411
     * namespace string.  Empty and numeric items are omitted.
412
     *
413
     * @param array $namespaceParts List of components of a namespace
414
     *
415
     * @return string
416
     */
417
    protected function joinNamespace(array $namespaceParts)
418
    {
419
        return $this->joinParts(
420
            '\\',
421
            $namespaceParts,
422
            function ($item) {
423
                return !is_numeric($item) && !empty($item);
424
            }
425
        );
426
    }
427
428
    /**
429
     * Combine the items of the provied array into a slash-separated
430
     * pathname.  Empty items are omitted.
431
     *
432
     * @param array $pathParts List of components of a path
433
     *
434
     * @return string
435
     */
436
    protected function joinPaths(array $pathParts)
437
    {
438
        $path = $this->joinParts(
439
            '/',
440
            $pathParts,
441
            function ($item) {
442
                return !empty($item);
443
            }
444
        );
445
        return str_replace(DIRECTORY_SEPARATOR, '/', $path);
446
    }
447
448
    /**
449
     * Simple wrapper around implode and array_filter.
450
     *
451
     * @param string $delimiter
452
     * @param array $parts
453
     * @param callable $filterFunction
454
     */
455
    protected function joinParts($delimiter, $parts, $filterFunction)
456
    {
457
        $parts = array_map(
458
            function ($item) use ($delimiter) {
459
                return rtrim($item, $delimiter);
460
            },
461
            $parts
462
        );
463
        return implode(
464
            $delimiter,
465
            array_filter($parts, $filterFunction)
466
        );
467
    }
468
}
469