Version 1
[yaffs-website] / vendor / psy / psysh / src / Psy / Command / ListCommand.php
1 <?php
2
3 /*
4  * This file is part of Psy Shell.
5  *
6  * (c) 2012-2017 Justin Hileman
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Psy\Command;
13
14 use Psy\Command\ListCommand\ClassConstantEnumerator;
15 use Psy\Command\ListCommand\ClassEnumerator;
16 use Psy\Command\ListCommand\ConstantEnumerator;
17 use Psy\Command\ListCommand\FunctionEnumerator;
18 use Psy\Command\ListCommand\GlobalVariableEnumerator;
19 use Psy\Command\ListCommand\InterfaceEnumerator;
20 use Psy\Command\ListCommand\MethodEnumerator;
21 use Psy\Command\ListCommand\PropertyEnumerator;
22 use Psy\Command\ListCommand\TraitEnumerator;
23 use Psy\Command\ListCommand\VariableEnumerator;
24 use Psy\Exception\RuntimeException;
25 use Psy\VarDumper\Presenter;
26 use Psy\VarDumper\PresenterAware;
27 use Symfony\Component\Console\Formatter\OutputFormatter;
28 use Symfony\Component\Console\Helper\TableHelper;
29 use Symfony\Component\Console\Input\InputArgument;
30 use Symfony\Component\Console\Input\InputInterface;
31 use Symfony\Component\Console\Input\InputOption;
32 use Symfony\Component\Console\Output\OutputInterface;
33
34 /**
35  * List available local variables, object properties, etc.
36  */
37 class ListCommand extends ReflectingCommand implements PresenterAware
38 {
39     protected $presenter;
40     protected $enumerators;
41
42     /**
43      * PresenterAware interface.
44      *
45      * @param Presenter $manager
46      */
47     public function setPresenter(Presenter $presenter)
48     {
49         $this->presenter = $presenter;
50     }
51
52     /**
53      * {@inheritdoc}
54      */
55     protected function configure()
56     {
57         $this
58             ->setName('ls')
59             ->setAliases(array('list', 'dir'))
60             ->setDefinition(array(
61                 new InputArgument('target', InputArgument::OPTIONAL, 'A target class or object to list.', null),
62
63                 new InputOption('vars',        '',  InputOption::VALUE_NONE,     'Display variables.'),
64                 new InputOption('constants',   'c', InputOption::VALUE_NONE,     'Display defined constants.'),
65                 new InputOption('functions',   'f', InputOption::VALUE_NONE,     'Display defined functions.'),
66                 new InputOption('classes',     'k', InputOption::VALUE_NONE,     'Display declared classes.'),
67                 new InputOption('interfaces',  'I', InputOption::VALUE_NONE,     'Display declared interfaces.'),
68                 new InputOption('traits',      't', InputOption::VALUE_NONE,     'Display declared traits.'),
69
70                 new InputOption('no-inherit',  '',  InputOption::VALUE_NONE,     'Exclude inherited methods, properties and constants.'),
71
72                 new InputOption('properties',  'p', InputOption::VALUE_NONE,     'Display class or object properties (public properties by default).'),
73                 new InputOption('methods',     'm', InputOption::VALUE_NONE,     'Display class or object methods (public methods by default).'),
74
75                 new InputOption('grep',        'G', InputOption::VALUE_REQUIRED, 'Limit to items matching the given pattern (string or regex).'),
76                 new InputOption('insensitive', 'i', InputOption::VALUE_NONE,     'Case-insensitive search (requires --grep).'),
77                 new InputOption('invert',      'v', InputOption::VALUE_NONE,     'Inverted search (requires --grep).'),
78
79                 new InputOption('globals',     'g', InputOption::VALUE_NONE,     'Include global variables.'),
80                 new InputOption('internal',    'n', InputOption::VALUE_NONE,     'Limit to internal functions and classes.'),
81                 new InputOption('user',        'u', InputOption::VALUE_NONE,     'Limit to user-defined constants, functions and classes.'),
82                 new InputOption('category',    'C', InputOption::VALUE_REQUIRED, 'Limit to constants in a specific category (e.g. "date").'),
83
84                 new InputOption('all',         'a', InputOption::VALUE_NONE,     'Include private and protected methods and properties.'),
85                 new InputOption('long',        'l', InputOption::VALUE_NONE,     'List in long format: includes class names and method signatures.'),
86             ))
87             ->setDescription('List local, instance or class variables, methods and constants.')
88             ->setHelp(
89                 <<<'HELP'
90 List variables, constants, classes, interfaces, traits, functions, methods,
91 and properties.
92
93 Called without options, this will return a list of variables currently in scope.
94
95 If a target object is provided, list properties, constants and methods of that
96 target. If a class, interface or trait name is passed instead, list constants
97 and methods on that class.
98
99 e.g.
100 <return>>>> ls</return>
101 <return>>>> ls $foo</return>
102 <return>>>> ls -k --grep mongo -i</return>
103 <return>>>> ls -al ReflectionClass</return>
104 <return>>>> ls --constants --category date</return>
105 <return>>>> ls -l --functions --grep /^array_.*/</return>
106 HELP
107             );
108     }
109
110     /**
111      * {@inheritdoc}
112      */
113     protected function execute(InputInterface $input, OutputInterface $output)
114     {
115         $this->validateInput($input);
116         $this->initEnumerators();
117
118         $method = $input->getOption('long') ? 'writeLong' : 'write';
119
120         if ($target = $input->getArgument('target')) {
121             list($target, $reflector) = $this->getTargetAndReflector($target, true);
122         } else {
123             $reflector = null;
124         }
125
126         // TODO: something cleaner than this :-/
127         if ($input->getOption('long')) {
128             $output->startPaging();
129         }
130
131         foreach ($this->enumerators as $enumerator) {
132             $this->$method($output, $enumerator->enumerate($input, $reflector, $target));
133         }
134
135         if ($input->getOption('long')) {
136             $output->stopPaging();
137         }
138
139         // Set some magic local variables
140         if ($reflector !== null) {
141             $this->setCommandScopeVariables($reflector);
142         }
143     }
144
145     /**
146      * Initialize Enumerators.
147      */
148     protected function initEnumerators()
149     {
150         if (!isset($this->enumerators)) {
151             $mgr = $this->presenter;
152
153             $this->enumerators = array(
154                 new ClassConstantEnumerator($mgr),
155                 new ClassEnumerator($mgr),
156                 new ConstantEnumerator($mgr),
157                 new FunctionEnumerator($mgr),
158                 new GlobalVariableEnumerator($mgr),
159                 new InterfaceEnumerator($mgr),
160                 new PropertyEnumerator($mgr),
161                 new MethodEnumerator($mgr),
162                 new TraitEnumerator($mgr),
163                 new VariableEnumerator($mgr, $this->context),
164             );
165         }
166     }
167
168     /**
169      * Write the list items to $output.
170      *
171      * @param OutputInterface $output
172      * @param null|array      $result List of enumerated items
173      */
174     protected function write(OutputInterface $output, array $result = null)
175     {
176         if ($result === null) {
177             return;
178         }
179
180         foreach ($result as $label => $items) {
181             $names = array_map(array($this, 'formatItemName'), $items);
182             $output->writeln(sprintf('<strong>%s</strong>: %s', $label, implode(', ', $names)));
183         }
184     }
185
186     /**
187      * Write the list items to $output.
188      *
189      * Items are listed one per line, and include the item signature.
190      *
191      * @param OutputInterface $output
192      * @param null|array      $result List of enumerated items
193      */
194     protected function writeLong(OutputInterface $output, array $result = null)
195     {
196         if ($result === null) {
197             return;
198         }
199
200         $table = $this->getTable($output);
201
202         foreach ($result as $label => $items) {
203             $output->writeln('');
204             $output->writeln(sprintf('<strong>%s:</strong>', $label));
205
206             $table->setRows(array());
207             foreach ($items as $item) {
208                 $table->addRow(array($this->formatItemName($item), $item['value']));
209             }
210
211             if ($table instanceof TableHelper) {
212                 $table->render($output);
213             } else {
214                 $table->render();
215             }
216         }
217     }
218
219     /**
220      * Format an item name given its visibility.
221      *
222      * @param array $item
223      *
224      * @return string
225      */
226     private function formatItemName($item)
227     {
228         return sprintf('<%s>%s</%s>', $item['style'], OutputFormatter::escape($item['name']), $item['style']);
229     }
230
231     /**
232      * Validate that input options make sense, provide defaults when called without options.
233      *
234      * @throws RuntimeException if options are inconsistent
235      *
236      * @param InputInterface $input
237      */
238     private function validateInput(InputInterface $input)
239     {
240         // grep, invert and insensitive
241         if (!$input->getOption('grep')) {
242             foreach (array('invert', 'insensitive') as $option) {
243                 if ($input->getOption($option)) {
244                     throw new RuntimeException('--' . $option . ' does not make sense without --grep');
245                 }
246             }
247         }
248
249         if (!$input->getArgument('target')) {
250             // if no target is passed, there can be no properties or methods
251             foreach (array('properties', 'methods', 'no-inherit') as $option) {
252                 if ($input->getOption($option)) {
253                     throw new RuntimeException('--' . $option . ' does not make sense without a specified target.');
254                 }
255             }
256
257             foreach (array('globals', 'vars', 'constants', 'functions', 'classes', 'interfaces', 'traits') as $option) {
258                 if ($input->getOption($option)) {
259                     return;
260                 }
261             }
262
263             // default to --vars if no other options are passed
264             $input->setOption('vars', true);
265         } else {
266             // if a target is passed, classes, functions, etc don't make sense
267             foreach (array('vars', 'globals', 'functions', 'classes', 'interfaces', 'traits') as $option) {
268                 if ($input->getOption($option)) {
269                     throw new RuntimeException('--' . $option . ' does not make sense with a specified target.');
270                 }
271             }
272
273             foreach (array('constants', 'properties', 'methods') as $option) {
274                 if ($input->getOption($option)) {
275                     return;
276                 }
277             }
278
279             // default to --constants --properties --methods if no other options are passed
280             $input->setOption('constants',  true);
281             $input->setOption('properties', true);
282             $input->setOption('methods',    true);
283         }
284     }
285 }