ad142d0719dd5fa2ec51ed54241a09357d5d4935
[yaffs-website] / vendor / psy / psysh / src / Psy / Command / ReflectingCommand.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\Context;
15 use Psy\ContextAware;
16 use Psy\Exception\RuntimeException;
17 use Psy\Util\Mirror;
18
19 /**
20  * An abstract command with helpers for inspecting the current context.
21  */
22 abstract class ReflectingCommand extends Command implements ContextAware
23 {
24     const CLASS_OR_FUNC   = '/^[\\\\\w]+$/';
25     const INSTANCE        = '/^\$(\w+)$/';
26     const CLASS_MEMBER    = '/^([\\\\\w]+)::(\w+)$/';
27     const CLASS_STATIC    = '/^([\\\\\w]+)::\$(\w+)$/';
28     const INSTANCE_MEMBER = '/^\$(\w+)(::|->)(\w+)$/';
29     const INSTANCE_STATIC = '/^\$(\w+)::\$(\w+)$/';
30     const SUPERGLOBAL     = '/^\$(GLOBALS|_(?:SERVER|ENV|FILES|COOKIE|POST|GET|SESSION))$/';
31
32     /**
33      * Context instance (for ContextAware interface).
34      *
35      * @var Context
36      */
37     protected $context;
38
39     /**
40      * ContextAware interface.
41      *
42      * @param Context $context
43      */
44     public function setContext(Context $context)
45     {
46         $this->context = $context;
47     }
48
49     /**
50      * Get the target for a value.
51      *
52      * @throws \InvalidArgumentException when the value specified can't be resolved
53      *
54      * @param string $valueName Function, class, variable, constant, method or property name
55      * @param bool   $classOnly True if the name should only refer to a class, function or instance
56      *
57      * @return array (class or instance name, member name, kind)
58      */
59     protected function getTarget($valueName, $classOnly = false)
60     {
61         $valueName = trim($valueName);
62         $matches   = array();
63         switch (true) {
64             case preg_match(self::SUPERGLOBAL, $valueName, $matches):
65                 // @todo maybe do something interesting with these at some point?
66                 if (array_key_exists($matches[1], $GLOBALS)) {
67                     throw new RuntimeException('Unable to inspect a non-object');
68                 }
69
70                 throw new RuntimeException('Unknown target: ' . $valueName);
71             case preg_match(self::CLASS_OR_FUNC, $valueName, $matches):
72                 return array($this->resolveName($matches[0], true), null, 0);
73
74             case preg_match(self::INSTANCE, $valueName, $matches):
75                 return array($this->resolveInstance($matches[1]), null, 0);
76
77             case !$classOnly && preg_match(self::CLASS_MEMBER, $valueName, $matches):
78                 return array($this->resolveName($matches[1]), $matches[2], Mirror::CONSTANT | Mirror::METHOD);
79
80             case !$classOnly && preg_match(self::CLASS_STATIC, $valueName, $matches):
81                 return array($this->resolveName($matches[1]), $matches[2], Mirror::STATIC_PROPERTY | Mirror::PROPERTY);
82
83             case !$classOnly && preg_match(self::INSTANCE_MEMBER, $valueName, $matches):
84                 if ($matches[2] === '->') {
85                     $kind = Mirror::METHOD | Mirror::PROPERTY;
86                 } else {
87                     $kind = Mirror::CONSTANT | Mirror::METHOD;
88                 }
89
90                 return array($this->resolveInstance($matches[1]), $matches[3], $kind);
91
92             case !$classOnly && preg_match(self::INSTANCE_STATIC, $valueName, $matches):
93                 return array($this->resolveInstance($matches[1]), $matches[2], Mirror::STATIC_PROPERTY);
94
95             default:
96                 throw new RuntimeException('Unknown target: ' . $valueName);
97         }
98     }
99
100     /**
101      * Resolve a class or function name (with the current shell namespace).
102      *
103      * @param string $name
104      * @param bool   $includeFunctions (default: false)
105      *
106      * @return string
107      */
108     protected function resolveName($name, $includeFunctions = false)
109     {
110         if (substr($name, 0, 1) === '\\') {
111             return $name;
112         }
113
114         if ($namespace = $this->getApplication()->getNamespace()) {
115             $fullName = $namespace . '\\' . $name;
116
117             if (class_exists($fullName) || interface_exists($fullName) || ($includeFunctions && function_exists($fullName))) {
118                 return $fullName;
119             }
120         }
121
122         return $name;
123     }
124
125     /**
126      * Get a Reflector and documentation for a function, class or instance, constant, method or property.
127      *
128      * @param string $valueName Function, class, variable, constant, method or property name
129      * @param bool   $classOnly True if the name should only refer to a class, function or instance
130      *
131      * @return array (value, Reflector)
132      */
133     protected function getTargetAndReflector($valueName, $classOnly = false)
134     {
135         list($value, $member, $kind) = $this->getTarget($valueName, $classOnly);
136
137         return array($value, Mirror::get($value, $member, $kind));
138     }
139
140     /**
141      * Return a variable instance from the current scope.
142      *
143      * @throws \InvalidArgumentException when the requested variable does not exist in the current scope
144      *
145      * @param string $name
146      *
147      * @return mixed Variable instance
148      */
149     protected function resolveInstance($name)
150     {
151         $value = $this->getScopeVariable($name);
152         if (!is_object($value)) {
153             throw new RuntimeException('Unable to inspect a non-object');
154         }
155
156         return $value;
157     }
158
159     /**
160      * Get a variable from the current shell scope.
161      *
162      * @param string $name
163      *
164      * @return mixed
165      */
166     protected function getScopeVariable($name)
167     {
168         return $this->context->get($name);
169     }
170
171     /**
172      * Get all scope variables from the current shell scope.
173      *
174      * @return array
175      */
176     protected function getScopeVariables()
177     {
178         return $this->context->getAll();
179     }
180
181     /**
182      * Given a Reflector instance, set command-scope variables in the shell
183      * execution context. This is used to inject magic $__class, $__method and
184      * $__file variables (as well as a handful of others).
185      *
186      * @param \Reflector $reflector
187      */
188     protected function setCommandScopeVariables(\Reflector $reflector)
189     {
190         $vars = array();
191
192         switch (get_class($reflector)) {
193             case 'ReflectionClass':
194             case 'ReflectionObject':
195                 $vars['__class'] = $reflector->name;
196                 if ($reflector->inNamespace()) {
197                     $vars['__namespace'] = $reflector->getNamespaceName();
198                 }
199                 break;
200
201             case 'ReflectionMethod':
202                 $vars['__method'] = sprintf('%s::%s', $reflector->class, $reflector->name);
203                 $vars['__class'] = $reflector->class;
204                 $classReflector = $reflector->getDeclaringClass();
205                 if ($classReflector->inNamespace()) {
206                     $vars['__namespace'] = $classReflector->getNamespaceName();
207                 }
208                 break;
209
210             case 'ReflectionFunction':
211                 $vars['__function'] = $reflector->name;
212                 if ($reflector->inNamespace()) {
213                     $vars['__namespace'] = $reflector->getNamespaceName();
214                 }
215                 break;
216
217             case 'ReflectionGenerator':
218                 $funcReflector = $reflector->getFunction();
219                 $vars['__function'] = $funcReflector->name;
220                 if ($funcReflector->inNamespace()) {
221                     $vars['__namespace'] = $funcReflector->getNamespaceName();
222                 }
223                 if ($fileName = $reflector->getExecutingFile()) {
224                     $vars['__file'] = $fileName;
225                     $vars['__line'] = $reflector->getExecutingLine();
226                     $vars['__dir']  = dirname($fileName);
227                 }
228                 break;
229
230             case 'ReflectionProperty':
231             case 'Psy\Reflection\ReflectionConstant':
232                 $classReflector = $reflector->getDeclaringClass();
233                 $vars['__class'] = $classReflector->name;
234                 if ($classReflector->inNamespace()) {
235                     $vars['__namespace'] = $classReflector->getNamespaceName();
236                 }
237                 // no line for these, but this'll do
238                 if ($fileName = $reflector->getDeclaringClass()->getFileName()) {
239                     $vars['__file'] = $fileName;
240                     $vars['__dir']  = dirname($fileName);
241                 }
242                 break;
243         }
244
245         if ($reflector instanceof \ReflectionClass || $reflector instanceof \ReflectionFunctionAbstract) {
246             if ($fileName = $reflector->getFileName()) {
247                 $vars['__file'] = $fileName;
248                 $vars['__line'] = $reflector->getStartLine();
249                 $vars['__dir']  = dirname($fileName);
250             }
251         }
252
253         $this->context->setCommandScopeVariables($vars);
254     }
255 }