Completed
Push — master ( aa295b...7990d7 )
by Greg
01:52
created

CommandFileDiscovery::ignoreNamespacePart()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
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('Commands', 'contrib')`. This causes the
149
     * `contrib` component to be removed from the namespace if it follows
150
     * the namespace `Commands`.
151
     */
152
    public function ignoreNamespacePart($base, $ignore)
153
    {
154
        $replacementPart = '\\' . $base . '\\';
155
        $ignoredPart = $replacementPart . $ignore . '\\';
156
        $this->strippedNamespaces[$ignoredPart] = $replacementPart;
157
158
        return $this;
159
    }
160
161
    /**
162
     * Add one more location to the search location list.
163
     *
164
     * @param string $location One more relative path to search
165
     *   for command files.
166
     */
167
    public function addSearchLocation($location)
168
    {
169
        $this->searchLocations[] = $location;
170
        return $this;
171
    }
172
173
    /**
174
     * Specify the pattern / regex used by the finder to search for
175
     * command files.
176
     */
177
    public function setSearchPattern($searchPattern)
178
    {
179
        $this->searchPattern = $searchPattern;
180
        return $this;
181
    }
182
183
    /**
184
     * Given a list of directories, e.g. Drupal modules like:
185
     *
186
     *    core/modules/block
187
     *    core/modules/dblog
188
     *    modules/default_content
189
     *
190
     * Discover command files in any of these locations.
191
     *
192
     * @param string|string[] $directoryList Places to search for commands.
193
     *
194
     * @return array
195
     */
196
    public function discoverNamespaced($directoryList, $baseNamespace = '')
197
    {
198
        return $this->discover($this->convertToNamespacedList((array)$directoryList), $baseNamespace);
199
    }
200
201
    /**
202
     * Given a simple list containing paths to directories, where
203
     * the last component of the path should appear in the namespace,
204
     * after the base namespace, this function will return an
205
     * associative array mapping the path's basename (e.g. the module
206
     * name) to the directory path.
207
     *
208
     * Module names must be unique.
209
     *
210
     * @param string[] $directoryList A list of module locations
211
     *
212
     * @return array
213
     */
214
    public function convertToNamespacedList($directoryList)
215
    {
216
        $namespacedArray = [];
217
        foreach ((array)$directoryList as $directory) {
218
            $namespacedArray[basename($directory)] = $directory;
219
        }
220
        return $namespacedArray;
221
    }
222
223
    /**
224
     * Search for command files in the specified locations. This is the function that
225
     * should be used for all locations that are NOT modules of a framework.
226
     *
227
     * @param string|string[] $directoryList Places to search for commands.
228
     * @return array
229
     */
230
    public function discover($directoryList, $baseNamespace = '')
231
    {
232
        $commandFiles = [];
233
        foreach ((array)$directoryList as $key => $directory) {
234
            $itemsNamespace = $this->joinNamespace([$baseNamespace, $key]);
235
            $commandFiles = array_merge(
236
                $commandFiles,
237
                $this->discoverCommandFiles($directory, $itemsNamespace),
238
                $this->discoverCommandFiles("$directory/src", $itemsNamespace)
239
            );
240
        }
241
        return $this->fixNamespaces($commandFiles);
242
    }
243
244
    /**
245
     * fixNamespaces will alter the namespaces in the commandFiles
246
     * result to remove the Composer placement directory, if any.
247
     */
248
    protected function fixNamespaces($commandFiles)
249
    {
250
        // Do nothing unless the client told us to remove some namespace components.
251
        if (empty($this->strippedNamespaces)) {
252
            return $commandFiles;
253
        }
254
255
        // Strip out any part of the namespace the client did not want.
256
        // @see CommandFileDiscovery::ignoreNamespacePart
257
        return array_map(
258
            function ($fqcn) {
259
                return str_replace(
260
                    array_keys($this->strippedNamespaces),
261
                    array_values($this->strippedNamespaces),
262
                    $fqcn
263
                );
264
            },
265
            $commandFiles
266
        );
267
    }
268
269
    /**
270
     * Search for command files in specific locations within a single directory.
271
     *
272
     * In each location, we will accept only a few places where command files
273
     * can be found. This will reduce the need to search through many unrelated
274
     * files.
275
     *
276
     * The default search locations include:
277
     *
278
     *    .
279
     *    CliTools
280
     *    src/CliTools
281
     *
282
     * The pattern we will look for is any file whose name ends in 'Commands.php'.
283
     * A list of paths to found files will be returned.
284
     */
285
    protected function discoverCommandFiles($directory, $baseNamespace)
286
    {
287
        $commandFiles = [];
288
        // In the search location itself, we will search for command files
289
        // immediately inside the directory only.
290
        if ($this->includeFilesAtBase) {
291
            $commandFiles = $this->discoverCommandFilesInLocation(
292
                $directory,
293
                $this->getBaseDirectorySearchDepth(),
294
                $baseNamespace
295
            );
296
        }
297
298
        // In the other search locations,
299
        foreach ($this->searchLocations as $location) {
300
            $itemsNamespace = $this->joinNamespace([$baseNamespace, $location]);
301
            $commandFiles = array_merge(
302
                $commandFiles,
303
                $this->discoverCommandFilesInLocation(
304
                    "$directory/$location",
305
                    $this->getSearchDepth(),
306
                    $itemsNamespace
307
                )
308
            );
309
        }
310
        return $commandFiles;
311
    }
312
313
    /**
314
     * Return a Finder search depth appropriate for our selected search depth.
315
     *
316
     * @return string
317
     */
318
    protected function getSearchDepth()
319
    {
320
        return $this->searchDepth <= 0 ? '== 0' : '<= ' . $this->searchDepth;
321
    }
322
323
    /**
324
     * Return a Finder search depth for the base directory.  If the
325
     * searchLocations array has been populated, then we will only search
326
     * for files immediately inside the base directory; no traversal into
327
     * deeper directories will be done, as that would conflict with the
328
     * specification provided by the search locations.  If there is no
329
     * search location, then we will search to whatever depth was specified
330
     * by the client.
331
     *
332
     * @return string
333
     */
334
    protected function getBaseDirectorySearchDepth()
335
    {
336
        if (!empty($this->searchLocations)) {
337
            return '== 0';
338
        }
339
        return $this->getSearchDepth();
340
    }
341
342
    /**
343
     * Search for command files in just one particular location.  Returns
344
     * an associative array mapping from the pathname of the file to the
345
     * classname that it contains.  The pathname may be ignored if the search
346
     * location is included in the autoloader.
347
     *
348
     * @param string $directory The location to search
349
     * @param string $depth How deep to search (e.g. '== 0' or '< 2')
350
     * @param string $baseNamespace Namespace to prepend to each classname
351
     *
352
     * @return array
353
     */
354
    protected function discoverCommandFilesInLocation($directory, $depth, $baseNamespace)
355
    {
356
        if (!is_dir($directory)) {
357
            return [];
358
        }
359
        $finder = $this->createFinder($directory, $depth);
360
361
        $commands = [];
362
        foreach ($finder as $file) {
363
            $relativePathName = $file->getRelativePathname();
364
            $relativeNamespaceAndClassname = str_replace(
365
                ['/', '-', '.php'],
366
                ['\\', '_', ''],
367
                $relativePathName
368
            );
369
            $classname = $this->joinNamespace([$baseNamespace, $relativeNamespaceAndClassname]);
370
            $commandFilePath = $this->joinPaths([$directory, $relativePathName]);
371
            $commands[$commandFilePath] = $classname;
372
        }
373
374
        return $commands;
375
    }
376
377
    /**
378
     * Create a Finder object for use in searching a particular directory
379
     * location.
380
     *
381
     * @param string $directory The location to search
382
     * @param string $depth The depth limitation
383
     *
384
     * @return Finder
385
     */
386
    protected function createFinder($directory, $depth)
387
    {
388
        $finder = new Finder();
389
        $finder->files()
390
            ->name($this->searchPattern)
391
            ->in($directory)
392
            ->depth($depth);
393
394
        foreach ($this->excludeList as $item) {
395
            $finder->exclude($item);
396
        }
397
398
        if ($this->followLinks) {
399
            $finder->followLinks();
400
        }
401
402
        return $finder;
403
    }
404
405
    /**
406
     * Combine the items of the provied array into a backslash-separated
407
     * namespace string.  Empty and numeric items are omitted.
408
     *
409
     * @param array $namespaceParts List of components of a namespace
410
     *
411
     * @return string
412
     */
413
    protected function joinNamespace(array $namespaceParts)
414
    {
415
        return $this->joinParts(
416
            '\\',
417
            $namespaceParts,
418
            function ($item) {
419
                return !is_numeric($item) && !empty($item);
420
            }
421
        );
422
    }
423
424
    /**
425
     * Combine the items of the provied array into a slash-separated
426
     * pathname.  Empty items are omitted.
427
     *
428
     * @param array $pathParts List of components of a path
429
     *
430
     * @return string
431
     */
432
    protected function joinPaths(array $pathParts)
433
    {
434
        $path = $this->joinParts(
435
            '/',
436
            $pathParts,
437
            function ($item) {
438
                return !empty($item);
439
            }
440
        );
441
        return str_replace(DIRECTORY_SEPARATOR, '/', $path);
442
    }
443
444
    /**
445
     * Simple wrapper around implode and array_filter.
446
     *
447
     * @param string $delimiter
448
     * @param array $parts
449
     * @param callable $filterFunction
450
     */
451
    protected function joinParts($delimiter, $parts, $filterFunction)
452
    {
453
        $parts = array_map(
454
            function ($item) use ($delimiter) {
455
                return rtrim($item, $delimiter);
456
            },
457
            $parts
458
        );
459
        return implode(
460
            $delimiter,
461
            array_filter($parts, $filterFunction)
462
        );
463
    }
464
}
465