Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 200 | Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of Psy Shell.
5
 *
6
 * (c) 2012-2022 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\CodeCleaner\NoReturnValue;
15
use Psy\Context;
16
use Psy\ContextAware;
17
use Psy\Exception\ErrorException;
18
use Psy\Exception\RuntimeException;
19
use Psy\Exception\UnexpectedTargetException;
20
use Psy\Reflection\ReflectionClassConstant;
21
use Psy\Reflection\ReflectionConstant_;
22
use Psy\Util\Mirror;
23
 
24
/**
25
 * An abstract command with helpers for inspecting the current context.
26
 */
27
abstract class ReflectingCommand extends Command implements ContextAware
28
{
29
    const CLASS_OR_FUNC = '/^[\\\\\w]+$/';
30
    const CLASS_MEMBER = '/^([\\\\\w]+)::(\w+)$/';
31
    const CLASS_STATIC = '/^([\\\\\w]+)::\$(\w+)$/';
32
    const INSTANCE_MEMBER = '/^(\$\w+)(::|->)(\w+)$/';
33
 
34
    /**
35
     * Context instance (for ContextAware interface).
36
     *
37
     * @var Context
38
     */
39
    protected $context;
40
 
41
    /**
42
     * ContextAware interface.
43
     *
44
     * @param Context $context
45
     */
46
    public function setContext(Context $context)
47
    {
48
        $this->context = $context;
49
    }
50
 
51
    /**
52
     * Get the target for a value.
53
     *
54
     * @throws \InvalidArgumentException when the value specified can't be resolved
55
     *
56
     * @param string $valueName Function, class, variable, constant, method or property name
57
     *
58
     * @return array (class or instance name, member name, kind)
59
     */
60
    protected function getTarget(string $valueName): array
61
    {
62
        $valueName = \trim($valueName);
63
        $matches = [];
64
        switch (true) {
65
            case \preg_match(self::CLASS_OR_FUNC, $valueName, $matches):
66
                return [$this->resolveName($matches[0], true), null, 0];
67
 
68
            case \preg_match(self::CLASS_MEMBER, $valueName, $matches):
69
                return [$this->resolveName($matches[1]), $matches[2], Mirror::CONSTANT | Mirror::METHOD];
70
 
71
            case \preg_match(self::CLASS_STATIC, $valueName, $matches):
72
                return [$this->resolveName($matches[1]), $matches[2], Mirror::STATIC_PROPERTY | Mirror::PROPERTY];
73
 
74
            case \preg_match(self::INSTANCE_MEMBER, $valueName, $matches):
75
                if ($matches[2] === '->') {
76
                    $kind = Mirror::METHOD | Mirror::PROPERTY;
77
                } else {
78
                    $kind = Mirror::CONSTANT | Mirror::METHOD;
79
                }
80
 
81
                return [$this->resolveObject($matches[1]), $matches[3], $kind];
82
 
83
            default:
84
                return [$this->resolveObject($valueName), null, 0];
85
        }
86
    }
87
 
88
    /**
89
     * Resolve a class or function name (with the current shell namespace).
90
     *
91
     * @throws ErrorException when `self` or `static` is used in a non-class scope
92
     *
93
     * @param string $name
94
     * @param bool   $includeFunctions (default: false)
95
     *
96
     * @return string
97
     */
98
    protected function resolveName(string $name, bool $includeFunctions = false): string
99
    {
100
        $shell = $this->getApplication();
101
 
102
        // While not *technically* 100% accurate, let's treat `self` and `static` as equivalent.
103
        if (\in_array(\strtolower($name), ['self', 'static'])) {
104
            if ($boundClass = $shell->getBoundClass()) {
105
                return $boundClass;
106
            }
107
 
108
            if ($boundObject = $shell->getBoundObject()) {
109
                return \get_class($boundObject);
110
            }
111
 
112
            $msg = \sprintf('Cannot use "%s" when no class scope is active', \strtolower($name));
113
            throw new ErrorException($msg, 0, \E_USER_ERROR, "eval()'d code", 1);
114
        }
115
 
116
        if (\substr($name, 0, 1) === '\\') {
117
            return $name;
118
        }
119
 
120
        // Check $name against the current namespace and use statements.
121
        if (self::couldBeClassName($name)) {
122
            try {
123
                $name = $this->resolveCode($name.'::class');
124
            } catch (RuntimeException $e) {
125
                // /shrug
126
            }
127
        }
128
 
129
        if ($namespace = $shell->getNamespace()) {
130
            $fullName = $namespace.'\\'.$name;
131
 
132
            if (\class_exists($fullName) || \interface_exists($fullName) || ($includeFunctions && \function_exists($fullName))) {
133
                return $fullName;
134
            }
135
        }
136
 
137
        return $name;
138
    }
139
 
140
    /**
141
     * Check whether a given name could be a class name.
142
     */
143
    protected function couldBeClassName(string $name): bool
144
    {
145
        // Regex based on https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class
146
        return \preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*(\\\\[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)*$/', $name) === 1;
147
    }
148
 
149
    /**
150
     * Get a Reflector and documentation for a function, class or instance, constant, method or property.
151
     *
152
     * @param string $valueName Function, class, variable, constant, method or property name
153
     *
154
     * @return array (value, Reflector)
155
     */
156
    protected function getTargetAndReflector(string $valueName): array
157
    {
158
        list($value, $member, $kind) = $this->getTarget($valueName);
159
 
160
        return [$value, Mirror::get($value, $member, $kind)];
161
    }
162
 
163
    /**
164
     * Resolve code to a value in the current scope.
165
     *
166
     * @throws RuntimeException when the code does not return a value in the current scope
167
     *
168
     * @param string $code
169
     *
170
     * @return mixed Variable value
171
     */
172
    protected function resolveCode(string $code)
173
    {
174
        try {
175
            $value = $this->getApplication()->execute($code, true);
176
        } catch (\Throwable $e) {
177
            // Swallow all exceptions?
178
        }
179
 
180
        if (!isset($value) || $value instanceof NoReturnValue) {
181
            throw new RuntimeException('Unknown target: '.$code);
182
        }
183
 
184
        return $value;
185
    }
186
 
187
    /**
188
     * Resolve code to an object in the current scope.
189
     *
190
     * @throws UnexpectedTargetException when the code resolves to a non-object value
191
     *
192
     * @param string $code
193
     *
194
     * @return object Variable instance
195
     */
196
    private function resolveObject(string $code)
197
    {
198
        $value = $this->resolveCode($code);
199
 
200
        if (!\is_object($value)) {
201
            throw new UnexpectedTargetException($value, 'Unable to inspect a non-object');
202
        }
203
 
204
        return $value;
205
    }
206
 
207
    /**
208
     * @deprecated Use `resolveCode` instead
209
     *
210
     * @param string $name
211
     *
212
     * @return mixed Variable instance
213
     */
214
    protected function resolveInstance(string $name)
215
    {
216
        @\trigger_error('`resolveInstance` is deprecated; use `resolveCode` instead.', \E_USER_DEPRECATED);
217
 
218
        return $this->resolveCode($name);
219
    }
220
 
221
    /**
222
     * Get a variable from the current shell scope.
223
     *
224
     * @param string $name
225
     *
226
     * @return mixed
227
     */
228
    protected function getScopeVariable(string $name)
229
    {
230
        return $this->context->get($name);
231
    }
232
 
233
    /**
234
     * Get all scope variables from the current shell scope.
235
     *
236
     * @return array
237
     */
238
    protected function getScopeVariables(): array
239
    {
240
        return $this->context->getAll();
241
    }
242
 
243
    /**
244
     * Given a Reflector instance, set command-scope variables in the shell
245
     * execution context. This is used to inject magic $__class, $__method and
246
     * $__file variables (as well as a handful of others).
247
     *
248
     * @param \Reflector $reflector
249
     */
250
    protected function setCommandScopeVariables(\Reflector $reflector)
251
    {
252
        $vars = [];
253
 
254
        switch (\get_class($reflector)) {
255
            case \ReflectionClass::class:
256
            case \ReflectionObject::class:
257
                $vars['__class'] = $reflector->name;
258
                if ($reflector->inNamespace()) {
259
                    $vars['__namespace'] = $reflector->getNamespaceName();
260
                }
261
                break;
262
 
263
            case \ReflectionMethod::class:
264
                $vars['__method'] = \sprintf('%s::%s', $reflector->class, $reflector->name);
265
                $vars['__class'] = $reflector->class;
266
                $classReflector = $reflector->getDeclaringClass();
267
                if ($classReflector->inNamespace()) {
268
                    $vars['__namespace'] = $classReflector->getNamespaceName();
269
                }
270
                break;
271
 
272
            case \ReflectionFunction::class:
273
                $vars['__function'] = $reflector->name;
274
                if ($reflector->inNamespace()) {
275
                    $vars['__namespace'] = $reflector->getNamespaceName();
276
                }
277
                break;
278
 
279
            case \ReflectionGenerator::class:
280
                $funcReflector = $reflector->getFunction();
281
                $vars['__function'] = $funcReflector->name;
282
                if ($funcReflector->inNamespace()) {
283
                    $vars['__namespace'] = $funcReflector->getNamespaceName();
284
                }
285
                if ($fileName = $reflector->getExecutingFile()) {
286
                    $vars['__file'] = $fileName;
287
                    $vars['__line'] = $reflector->getExecutingLine();
288
                    $vars['__dir'] = \dirname($fileName);
289
                }
290
                break;
291
 
292
            case \ReflectionProperty::class:
293
            case \ReflectionClassConstant::class:
294
            case ReflectionClassConstant::class:
295
                $classReflector = $reflector->getDeclaringClass();
296
                $vars['__class'] = $classReflector->name;
297
                if ($classReflector->inNamespace()) {
298
                    $vars['__namespace'] = $classReflector->getNamespaceName();
299
                }
300
                // no line for these, but this'll do
301
                if ($fileName = $reflector->getDeclaringClass()->getFileName()) {
302
                    $vars['__file'] = $fileName;
303
                    $vars['__dir'] = \dirname($fileName);
304
                }
305
                break;
306
 
307
            case ReflectionConstant_::class:
308
                if ($reflector->inNamespace()) {
309
                    $vars['__namespace'] = $reflector->getNamespaceName();
310
                }
311
                break;
312
        }
313
 
314
        if ($reflector instanceof \ReflectionClass || $reflector instanceof \ReflectionFunctionAbstract) {
315
            if ($fileName = $reflector->getFileName()) {
316
                $vars['__file'] = $fileName;
317
                $vars['__line'] = $reflector->getStartLine();
318
                $vars['__dir'] = \dirname($fileName);
319
            }
320
        }
321
 
322
        $this->context->setCommandScopeVariables($vars);
323
    }
324
}