Completed
Push — master ( f3f731...f22ae4 )
by Alexander
02:34
created

ClassProxy::injectJoinPoints()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 0
cts 11
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 1
crap 6
1
<?php
2
declare(strict_types = 1);
3
/*
4
 * Go! AOP framework
5
 *
6
 * @copyright Copyright 2012, Lisachenko Alexander <[email protected]>
7
 *
8
 * This source file is subject to the license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Go\Proxy;
13
14
use Go\Aop\Advice;
15
use Go\Aop\Framework\ClassFieldAccess;
16
use Go\Aop\Framework\DynamicClosureMethodInvocation;
17
use Go\Aop\Framework\ReflectionConstructorInvocation;
18
use Go\Aop\Framework\StaticClosureMethodInvocation;
19
use Go\Aop\Framework\StaticInitializationJoinpoint;
20
use Go\Aop\Intercept\Joinpoint;
21
use Go\Aop\IntroductionInfo;
22
use Go\Aop\Proxy;
23
use Go\Core\AspectContainer;
24
use Go\Core\AspectKernel;
25
use Go\Core\LazyAdvisorAccessor;
26
use Reflection;
27
use ReflectionClass;
28
use ReflectionMethod;
29
use ReflectionProperty;
30
31
/**
32
 * Class proxy builder that is used to generate a child class from the list of joinpoints
33
 */
34
class ClassProxy extends AbstractProxy
35
{
36
    /**
37
     * Parent class reflection
38
     *
39
     * @var null|ReflectionClass
40
     */
41
    protected $class;
42
43
    /**
44
     * Parent class name, can be changed manually
45
     *
46
     * @var string
47
     */
48
    protected $parentClassName;
49
50
    /**
51
     * Source code for methods
52
     *
53
     * @var array Name of method => source code for it
54
     */
55
    protected $methodsCode = [];
56
57
    /**
58
     * Static mappings for class name for excluding if..else check
59
     *
60
     * @var null|array
61
     */
62
    protected static $invocationClassMap = [
63
        AspectContainer::METHOD_PREFIX        => DynamicClosureMethodInvocation::class,
64
        AspectContainer::STATIC_METHOD_PREFIX => StaticClosureMethodInvocation::class,
65
        AspectContainer::PROPERTY_PREFIX      => ClassFieldAccess::class,
66
        AspectContainer::STATIC_INIT_PREFIX   => StaticInitializationJoinpoint::class,
67
        AspectContainer::INIT_PREFIX          => ReflectionConstructorInvocation::class
68
    ];
69
70
    /**
71
     * List of additional interfaces to implement
72
     *
73
     * @var array
74
     */
75
    protected $interfaces = [];
76
77
    /**
78
     * List of additional traits for using
79
     *
80
     * @var array
81
     */
82
    protected $traits = [];
83
84
    /**
85
     * Source code for properties
86
     *
87
     * @var array Name of property => source code for it
88
     */
89
    protected $propertiesCode = [];
90
91
    /**
92
     * Name for the current class
93
     *
94
     * @var string
95
     */
96
    protected $name = '';
97
98
    /**
99
     * Flag to determine if we need to add a code for property interceptors
100
     *
101
     * @var bool
102
     */
103
    private $isFieldsIntercepted = false;
104
105
    /**
106
     * List of intercepted properties names
107
     *
108
     * @var array
109
     */
110
    private $interceptedProperties = [];
111
112
    /**
113
     * Generates an child code by parent class reflection and joinpoints for it
114
     *
115
     * @param ReflectionClass $parent Parent class reflection
116
     * @param array|Advice[] $classAdvices List of advices for class
117
     *
118
     * @throws \InvalidArgumentException if there are unknown type of advices
119
     */
120 6
    public function __construct(ReflectionClass $parent, array $classAdvices)
121
    {
122 6
        parent::__construct($classAdvices);
123
124 6
        $this->class           = $parent;
125 6
        $this->name            = $parent->getShortName();
126 6
        $this->parentClassName = $parent->getShortName();
127
128 6
        $this->addInterface(Proxy::class);
129 6
        $this->addJoinpointsProperty();
130
131 6
        foreach ($classAdvices as $type => $typedAdvices) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
132
133
            switch ($type) {
134 6
                case AspectContainer::METHOD_PREFIX:
135
                case AspectContainer::STATIC_METHOD_PREFIX:
136 6
                    foreach ($typedAdvices as $joinPointName => $advice) {
137 6
                        $method = $parent->getMethod($joinPointName);
138 6
                        $this->overrideMethod($method);
139
                    }
140 6
                    break;
141
142
                case AspectContainer::PROPERTY_PREFIX:
143
                    foreach ($typedAdvices as $joinPointName => $advice) {
144
                        $property = $parent->getProperty($joinPointName);
145
                        $this->interceptProperty($property);
146
                    }
147
                    break;
148
149
                case AspectContainer::INTRODUCTION_TRAIT_PREFIX:
150
                    foreach ($typedAdvices as $advice) {
151
                        /** @var $advice IntroductionInfo */
152
                        foreach ($advice->getInterfaces() as $interface) {
153
                            $this->addInterface($interface);
154
                        }
155
                        foreach ($advice->getTraits() as $trait) {
156
                            $this->addTrait($trait);
157
                        }
158
                    }
159
                    break;
160
161
                case AspectContainer::INIT_PREFIX:
162
                case AspectContainer::STATIC_INIT_PREFIX:
163
                    break; // No changes for class
164
165
                default:
166 6
                    throw new \InvalidArgumentException("Unsupported point `$type`");
167
            }
168
        }
169 6
    }
170
171
172
    /**
173
     * Updates parent name for child
174
     *
175
     * @param string $newParentName New class name
176
     */
177 6
    public function setParentName(string $newParentName)
178
    {
179 6
        $this->parentClassName = $newParentName;
180 6
    }
181
182
    /**
183
     * Override parent method with new body
184
     *
185
     * @param string $methodName Method name to override
186
     * @param string $body New body for method
187
     */
188 6
    public function override(string $methodName, string $body)
189
    {
190 6
        $this->methodsCode[$methodName] = $this->getOverriddenFunction($this->class->getMethod($methodName), $body);
191 6
    }
192
193
    /**
194
     * Creates a method
195
     *
196
     * @param int $methodFlags See ReflectionMethod modifiers
197
     * @param string $methodName Name of the method
198
     * @param bool $byReference Is method should return value by reference
199
     * @param string $body Body of method
200
     * @param string $parameters Definition of parameters
201
     */
202
    public function setMethod(int $methodFlags, string $methodName, bool $byReference, string $body, string $parameters)
203
    {
204
        $this->methodsCode[$methodName] = (
205
            "/**\n * Method was created automatically, do not change it manually\n */\n" .
206
            implode(' ', Reflection::getModifierNames($methodFlags)) . // List of method modifiers
207
            ' function ' . // 'function' keyword
208
            ($byReference ? '&' : '') . // Return value by reference
209
            $methodName . // Method name
210
            '(' . // Start of parameter list
211
            $parameters . // List of parameters
212
            ")\n" . // End of parameter list
213
            "{\n" . // Start of method body
214
            $this->indent($body) . "\n" . // Method body
215
            "}\n" // End of method body
216
        );
217
    }
218
219
    /**
220
     * Inject advices into given class
221
     *
222
     * NB This method will be used as a callback during source code evaluation to inject joinpoints
223
     *
224
     * @param string $className Aop child proxy class
225
     */
226
    public static function injectJoinPoints(string $className)
227
    {
228
        $reflectionClass    = new ReflectionClass($className);
229
        $joinPointsProperty = $reflectionClass->getProperty('__joinPoints');
230
231
        $joinPointsProperty->setAccessible(true);
232
        $advices    = $joinPointsProperty->getValue();
233
        $joinPoints = static::wrapWithJoinPoints($advices, $reflectionClass->getParentClass()->name);
234
        $joinPointsProperty->setValue($joinPoints);
235
236
        $staticInit = AspectContainer::STATIC_INIT_PREFIX . ':root';
237
        if (isset($joinPoints[$staticInit])) {
238
            $joinPoints[$staticInit]->__invoke();
239
        }
240
    }
241
242
    /**
243
     * Wrap advices with joinpoint object
244
     *
245
     * @param array|Advice[] $classAdvices Advices for specific class
246
     * @param string $className Name of the original class to use
247
     *
248
     * @throws \UnexpectedValueException If joinPoint type is unknown
249
     *
250
     * NB: Extension should be responsible for wrapping advice with join point.
251
     *
252
     * @return array|Joinpoint[] returns list of joinpoint ready to use
253
     */
254
    protected static function wrapWithJoinPoints(array $classAdvices, string $className): array
255
    {
256
        /** @var LazyAdvisorAccessor $accessor */
257
        static $accessor;
258
259
        if (!isset($accessor)) {
260
            $aspectKernel = AspectKernel::getInstance();
261
            $accessor     = $aspectKernel->getContainer()->get('aspect.advisor.accessor');
262
        }
263
264
        $joinPoints = [];
265
266
        foreach ($classAdvices as $joinPointType => $typedAdvices) {
267
            // if not isset then we don't want to create such invocation for class
268
            if (!isset(self::$invocationClassMap[$joinPointType])) {
269
                continue;
270
            }
271
            foreach ($typedAdvices as $joinPointName => $advices) {
272
                $filledAdvices = [];
273
                foreach ($advices as $advisorName) {
274
                    $filledAdvices[] = $accessor->$advisorName;
275
                }
276
277
                $joinpoint = new self::$invocationClassMap[$joinPointType]($className, $joinPointName, $filledAdvices);
278
                $joinPoints["$joinPointType:$joinPointName"] = $joinpoint;
279
            }
280
        }
281
282
        return $joinPoints;
283
    }
284
285
    /**
286
     * Add an interface for child
287
     *
288
     * @param string $interfaceName Name of the interface to add
289
     */
290 6
    public function addInterface(string $interfaceName)
291
    {
292
        // Use absolute namespace to prevent NS-conflicts
293 6
        $this->interfaces[] = '\\' . ltrim($interfaceName, '\\');
294 6
    }
295
296
    /**
297
     * Add a trait for child
298
     *
299
     * @param string $traitName Name of the trait to add
300
     */
301
    public function addTrait(string $traitName)
302
    {
303
        // Use absolute namespace to prevent NS-conflicts
304
        $this->traits[] = '\\' . ltrim($traitName, '\\');
305
    }
306
307
    /**
308
     * Creates a property
309
     *
310
     * @param int $propFlags See ReflectionProperty modifiers
311
     * @param string $propName Name of the property
312
     * @param null|string $defaultText Default value, should be string text!
313
     */
314 6
    public function setProperty(int $propFlags, string $propName, string $defaultText = null)
315
    {
316 6
        $this->propertiesCode[$propName] = (
317
            "/**\n * Property was created automatically, do not change it manually\n */\n" . // Doc-block
318 6
            implode(' ', Reflection::getModifierNames($propFlags)) . // List of modifiers for property
319 6
            ' $' . // Space and variable symbol
320 6
            $propName . // Name of the property
321 6
            (isset($defaultText) ? " = $defaultText" : '') . // Default value if present
322 6
            ";\n" // End of line with property definition
323
        );
324 6
    }
325
326
    /**
327
     * Adds a definition for joinpoints private property in the class
328
     */
329 6
    protected function addJoinpointsProperty()
330
    {
331 6
        $exportedAdvices = strtr(json_encode($this->advices, JSON_PRETTY_PRINT), [
332 6
            '{' => '[',
333
            '}' => ']',
334
            '"' => '\'',
335
            ':' => ' =>'
336
        ]);
337 6
        $this->setProperty(
338 6
            ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_STATIC,
339 6
            '__joinPoints',
340
            $exportedAdvices
341
        );
342 6
    }
343
344
    /**
345
     * Override parent method with joinpoint invocation
346
     *
347
     * @param ReflectionMethod $method Method reflection
348
     */
349 6
    protected function overrideMethod(ReflectionMethod $method)
350
    {
351
        // temporary disable override of final methods
352 6
        if (!$method->isFinal() && !$method->isAbstract()) {
353 6
            $this->override($method->name, $this->getJoinpointInvocationBody($method));
354
        }
355 6
    }
356
357
    /**
358
     * Creates definition for method body
359
     *
360
     * @param ReflectionMethod $method Method reflection
361
     *
362
     * @return string new method body
363
     */
364 6
    protected function getJoinpointInvocationBody(ReflectionMethod $method): string
365
    {
366 6
        $isStatic = $method->isStatic();
367 6
        $scope    = $isStatic ? self::$staticLsbExpression : '$this';
368 6
        $prefix   = $isStatic ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
369
370 6
        $args   = $this->prepareArgsLine($method);
371 6
        $return = 'return ';
372 6
        if (PHP_VERSION_ID >= 70100 && $method->hasReturnType()) {
1 ignored issue
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ReflectionMethod as the method hasReturnType() does only exist in the following sub-classes of ReflectionMethod: Go\ParserReflection\ReflectionMethod. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
373
            $returnType = (string) $method->getReturnType();
374
            if ($returnType === 'void') {
375
                // void return types should not return anything
376
                $return = '';
377
            }
378
        }
379
380 6
        if (!empty($args)) {
381 3
            $scope = "$scope, $args";
382
        }
383
384 6
        $body = "{$return}self::\$__joinPoints['{$prefix}:{$method->name}']->__invoke($scope);";
385
386 6
        return $body;
387
    }
388
389
    /**
390
     * Makes property intercepted
391
     *
392
     * @param ReflectionProperty $property Reflection of property to intercept
393
     */
394
    protected function interceptProperty(ReflectionProperty $property)
395
    {
396
        $this->interceptedProperties[] = is_object($property) ? $property->name : $property;
397
        $this->isFieldsIntercepted = true;
398
    }
399
400
    /**
401
     * {@inheritDoc}
402
     */
403 6
    public function __toString()
404
    {
405 6
        $ctor = $this->class->getConstructor();
406 6
        if ($this->isFieldsIntercepted && (!$ctor || !$ctor->isPrivate())) {
407
            $this->addFieldInterceptorsCode($ctor);
408
        }
409
410 6
        $prefix = implode(' ', Reflection::getModifierNames($this->class->getModifiers()));
411
412
        $classCode = (
413 6
            $this->class->getDocComment() . "\n" . // Original doc-block
414 6
            ($prefix ? "$prefix " : '') . // List of class modifiers
415 6
            'class ' . // 'class' keyword with one space
416 6
            $this->name . // Name of the class
417 6
            ' extends ' . // 'extends' keyword with
418 6
            $this->parentClassName . // Name of the parent class
419 6
            ($this->interfaces ? ' implements ' . implode(', ', $this->interfaces) : '') . "\n" . // Interfaces list
420 6
            "{\n" . // Start of class definition
421 6
            ($this->traits ? $this->indent('use ' . implode(', ', $this->traits) . ';' . "\n") : '') . "\n" . // Traits list
422 6
            $this->indent(implode("\n", $this->propertiesCode)) . "\n" . // Property definitions
423 6
            $this->indent(implode("\n", $this->methodsCode)) . "\n" . // Method definitions
424 6
            "}" // End of class definition
425
        );
426
427
        return $classCode
428
            // Inject advices on call
429 6
            . PHP_EOL
430 6
            . '\\' . __CLASS__ . "::injectJoinPoints(" . $this->class->getShortName() . "::class);";
431
    }
432
433
    /**
434
     * Add code for intercepting properties
435
     *
436
     * @param null|ReflectionMethod $constructor Constructor reflection or null
437
     */
438
    protected function addFieldInterceptorsCode(ReflectionMethod $constructor = null)
439
    {
440
        $this->addTrait(PropertyInterceptionTrait::class);
441
        $this->isFieldsIntercepted = true;
442
        if ($constructor) {
443
            $this->override('__construct', $this->getConstructorBody($constructor, true));
444
        } else {
445
            $this->setMethod(ReflectionMethod::IS_PUBLIC, '__construct', false, $this->getConstructorBody(), '');
446
        }
447
    }
448
449
    /**
450
     * Returns constructor code
451
     *
452
     * @param ReflectionMethod $constructor Constructor reflection
453
     * @param bool $isCallParent Is there is a need to call parent code
454
     *
455
     * @return string
456
     */
457
    private function getConstructorBody(ReflectionMethod $constructor = null, bool $isCallParent = false): string
458
    {
459
        $assocProperties = [];
460
        $listProperties  = [];
461
        foreach ($this->interceptedProperties as $propertyName) {
462
            $assocProperties[] = "'$propertyName' => &\$this->$propertyName";
463
            $listProperties[]  = "\$this->$propertyName";
464
        }
465
        $assocProperties = $this->indent(implode(',' . PHP_EOL, $assocProperties));
466
        $listProperties  = $this->indent(implode(',' . PHP_EOL, $listProperties));
467
        if (isset($this->methodsCode['__construct'])) {
468
            $parentCall = $this->getJoinpointInvocationBody($constructor);
0 ignored issues
show
Bug introduced by
It seems like $constructor defined by parameter $constructor on line 457 can be null; however, Go\Proxy\ClassProxy::getJoinpointInvocationBody() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
469
        } elseif ($isCallParent) {
470
            $parentCall = '\call_user_func_array(["parent", __FUNCTION__], \func_get_args());';
471
        } else {
472
            $parentCall = '';
473
        }
474
475
        return <<<CTOR
476
\$this->__properties = array(
477
$assocProperties
478
);
479
unset(
480
$listProperties
481
);
482
$parentCall
483
CTOR;
484
    }
485
}
486