a4084083ef3f367bd5675784b0c2bf16c4ca757a
[yaffs-website] / vendor / drush / drush / src / Preflight / ArgsRemapper.php
1 <?php
2 namespace Drush\Preflight;
3
4 /**
5  * Map commandline arguments from one value to anohter during preflight.
6  */
7 class ArgsRemapper
8 {
9     protected $remapOptions;
10     protected $remapCommandAliases;
11
12     /**
13      * ArgsRemapper constructor
14      */
15     public function __construct($remapOptions, $remapCommandAliases)
16     {
17         $this->remapOptions = $remapOptions;
18         $this->remapCommandAliases = $remapCommandAliases;
19     }
20
21     /**
22      * Given an $argv array, apply all remap operations on each item
23      * within it.
24      *
25      * @param string[] $argv
26      */
27     public function remap($argv)
28     {
29         $result = [];
30         $sawCommand = false;
31         foreach ($argv as $arg) {
32             $arg = $this->checkRemap($arg, $sawCommand);
33             if (isset($arg)) {
34                 $result[] = $arg;
35             }
36         }
37         return $result;
38     }
39
40     /**
41      * Check to see if the provided single arg needs to be remapped. If
42      * it does, then the remapping is performed.
43      *
44      * @param string $arg One argument to inspect
45      * @param string $sawCommand True if drush command was found
46      * @return string The altered argument
47      */
48     protected function checkRemap($arg, &$sawCommand)
49     {
50         if (!$sawCommand && ctype_alpha($arg[0])) {
51             $sawCommand = true;
52             return $this->remapCommandAlias($arg);
53         }
54         return $this->remapOptions($arg);
55     }
56
57     protected function remapOptions($arg)
58     {
59         foreach ($this->remapOptions as $from => $to) {
60             if ($this->matches($arg, $from)) {
61                 return $to . substr($arg, strlen($from));
62             }
63         }
64         return $arg;
65     }
66
67     protected function remapCommandAlias($arg)
68     {
69         foreach ($this->remapCommandAliases as $from => $to) {
70             if ($arg == $from) {
71                 return $to;
72             }
73         }
74         return $arg;
75     }
76
77     /**
78      * Check to see if the provided single arg matches the candidate.
79      * If the candidate is `--foo`, then we will match the exact string
80      * `--foo`, or the leading substring `--foo=`, and nothing else.
81      * @param string $arg
82      * @param string $candidate
83      * @return bool
84      */
85     protected function matches($arg, $candidate)
86     {
87         if (strpos($arg, $candidate) !== 0) {
88             return false;
89         }
90
91         if (strlen($arg) == strlen($candidate)) {
92             return true;
93         }
94
95         return $arg[strlen($candidate)] == '=';
96     }
97 }