Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Zur aktuellen Revision | Details | Vergleich mit vorheriger | 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
 *
200 lars 6
 * (c) 2012-2023 Justin Hileman
148 lars 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
    protected function resolveName(string $name, bool $includeFunctions = false): string
97
    {
98
        $shell = $this->getApplication();
99
 
100
        // While not *technically* 100% accurate, let's treat `self` and `static` as equivalent.
101
        if (\in_array(\strtolower($name), ['self', 'static'])) {
102
            if ($boundClass = $shell->getBoundClass()) {
103
                return $boundClass;
104
            }
105
 
106
            if ($boundObject = $shell->getBoundObject()) {
107
                return \get_class($boundObject);
108
            }
109
 
110
            $msg = \sprintf('Cannot use "%s" when no class scope is active', \strtolower($name));
111
            throw new ErrorException($msg, 0, \E_USER_ERROR, "eval()'d code", 1);
112
        }
113
 
114
        if (\substr($name, 0, 1) === '\\') {
115
            return $name;
116
        }
117
 
118
        // Check $name against the current namespace and use statements.
119
        if (self::couldBeClassName($name)) {
120
            try {
121
                $name = $this->resolveCode($name.'::class');
122
            } catch (RuntimeException $e) {
123
                // /shrug
124
            }
125
        }
126
 
127
        if ($namespace = $shell->getNamespace()) {
128
            $fullName = $namespace.'\\'.$name;
129
 
130
            if (\class_exists($fullName) || \interface_exists($fullName) || ($includeFunctions && \function_exists($fullName))) {
131
                return $fullName;
132
            }
133
        }
134
 
135
        return $name;
136
    }
137
 
138
    /**
139
     * Check whether a given name could be a class name.
140
     */
141
    protected function couldBeClassName(string $name): bool
142
    {
143
        // Regex based on https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class
144
        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;
145
    }
146
 
147
    /**
148
     * Get a Reflector and documentation for a function, class or instance, constant, method or property.
149
     *
150
     * @param string $valueName Function, class, variable, constant, method or property name
151
     *
152
     * @return array (value, Reflector)
153
     */
154
    protected function getTargetAndReflector(string $valueName): array
155
    {
156
        list($value, $member, $kind) = $this->getTarget($valueName);
157
 
158
        return [$value, Mirror::get($value, $member, $kind)];
159
    }
160
 
161
    /**
162
     * Resolve code to a value in the current scope.
163
     *
164
     * @throws RuntimeException when the code does not return a value in the current scope
165
     *
166
     * @param string $code
167
     *
168
     * @return mixed Variable value
169
     */
170
    protected function resolveCode(string $code)
171
    {
172
        try {
173
            $value = $this->getApplication()->execute($code, true);
174
        } catch (\Throwable $e) {
175
            // Swallow all exceptions?
176
        }
177
 
178
        if (!isset($value) || $value instanceof NoReturnValue) {
179
            throw new RuntimeException('Unknown target: '.$code);
180
        }
181
 
182
        return $value;
183
    }
184
 
185
    /**
186
     * Resolve code to an object in the current scope.
187
     *
188
     * @throws UnexpectedTargetException when the code resolves to a non-object value
189
     *
190
     * @param string $code
191
     *
192
     * @return object Variable instance
193
     */
194
    private function resolveObject(string $code)
195
    {
196
        $value = $this->resolveCode($code);
197
 
198
        if (!\is_object($value)) {
199
            throw new UnexpectedTargetException($value, 'Unable to inspect a non-object');
200
        }
201
 
202
        return $value;
203
    }
204
 
205
    /**
206
     * @deprecated Use `resolveCode` instead
207
     *
208
     * @param string $name
209
     *
210
     * @return mixed Variable instance
211
     */
212
    protected function resolveInstance(string $name)
213
    {
214
        @\trigger_error('`resolveInstance` is deprecated; use `resolveCode` instead.', \E_USER_DEPRECATED);
215
 
216
        return $this->resolveCode($name);
217
    }
218
 
219
    /**
220
     * Get a variable from the current shell scope.
221
     *
222
     * @param string $name
223
     *
224
     * @return mixed
225
     */
226
    protected function getScopeVariable(string $name)
227
    {
228
        return $this->context->get($name);
229
    }
230
 
231
    /**
232
     * Get all scope variables from the current shell scope.
233
     *
234
     * @return array
235
     */
236
    protected function getScopeVariables(): array
237
    {
238
        return $this->context->getAll();
239
    }
240
 
241
    /**
242
     * Given a Reflector instance, set command-scope variables in the shell
243
     * execution context. This is used to inject magic $__class, $__method and
244
     * $__file variables (as well as a handful of others).
245
     *
246
     * @param \Reflector $reflector
247
     */
248
    protected function setCommandScopeVariables(\Reflector $reflector)
249
    {
250
        $vars = [];
251
 
252
        switch (\get_class($reflector)) {
253
            case \ReflectionClass::class:
254
            case \ReflectionObject::class:
255
                $vars['__class'] = $reflector->name;
256
                if ($reflector->inNamespace()) {
257
                    $vars['__namespace'] = $reflector->getNamespaceName();
258
                }
259
                break;
260
 
261
            case \ReflectionMethod::class:
262
                $vars['__method'] = \sprintf('%s::%s', $reflector->class, $reflector->name);
263
                $vars['__class'] = $reflector->class;
264
                $classReflector = $reflector->getDeclaringClass();
265
                if ($classReflector->inNamespace()) {
266
                    $vars['__namespace'] = $classReflector->getNamespaceName();
267
                }
268
                break;
269
 
270
            case \ReflectionFunction::class:
271
                $vars['__function'] = $reflector->name;
272
                if ($reflector->inNamespace()) {
273
                    $vars['__namespace'] = $reflector->getNamespaceName();
274
                }
275
                break;
276
 
277
            case \ReflectionGenerator::class:
278
                $funcReflector = $reflector->getFunction();
279
                $vars['__function'] = $funcReflector->name;
280
                if ($funcReflector->inNamespace()) {
281
                    $vars['__namespace'] = $funcReflector->getNamespaceName();
282
                }
283
                if ($fileName = $reflector->getExecutingFile()) {
284
                    $vars['__file'] = $fileName;
285
                    $vars['__line'] = $reflector->getExecutingLine();
286
                    $vars['__dir'] = \dirname($fileName);
287
                }
288
                break;
289
 
290
            case \ReflectionProperty::class:
291
            case \ReflectionClassConstant::class:
292
            case ReflectionClassConstant::class:
293
                $classReflector = $reflector->getDeclaringClass();
294
                $vars['__class'] = $classReflector->name;
295
                if ($classReflector->inNamespace()) {
296
                    $vars['__namespace'] = $classReflector->getNamespaceName();
297
                }
298
                // no line for these, but this'll do
299
                if ($fileName = $reflector->getDeclaringClass()->getFileName()) {
300
                    $vars['__file'] = $fileName;
301
                    $vars['__dir'] = \dirname($fileName);
302
                }
303
                break;
304
 
305
            case ReflectionConstant_::class:
306
                if ($reflector->inNamespace()) {
307
                    $vars['__namespace'] = $reflector->getNamespaceName();
308
                }
309
                break;
310
        }
311
 
312
        if ($reflector instanceof \ReflectionClass || $reflector instanceof \ReflectionFunctionAbstract) {
313
            if ($fileName = $reflector->getFileName()) {
314
                $vars['__file'] = $fileName;
315
                $vars['__line'] = $reflector->getStartLine();
316
                $vars['__dir'] = \dirname($fileName);
317
            }
318
        }
319
 
320
        $this->context->setCommandScopeVariables($vars);
321
    }
322
}