Completed
Pull Request — master (#339)
by Alexander
01:44
created

ClassProxy::__toString()   C

Complexity

Conditions 7
Paths 16

Size

Total Lines 31
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 7.0052

Importance

Changes 0
Metric Value
dl 0
loc 31
c 0
b 0
f 0
ccs 20
cts 21
cp 0.9524
rs 6.7272
cc 7
eloc 23
nc 16
nop 0
crap 7.0052
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 = null;
42
43
    /**
44
     * Parent class name, can be changed manually
45
     *
46
     * @var string
47
     */
48
    protected $parentClassName = null;
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
            join(' ', 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
     * @param array|Advice[] $advices List of advices to inject into class
226
     */
227
    public static function injectJoinPoints(string $className, array $advices = [])
228
    {
229
        $reflectionClass  = new ReflectionClass($className);
230
        $joinPoints       = static::wrapWithJoinPoints($advices, $reflectionClass->getParentClass()->name);
231
232
        $prop = $reflectionClass->getProperty('__joinPoints');
233
        $prop->setAccessible(true);
234
        $prop->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 = null;
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
            join(' ', 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
        $this->setProperty(
332 6
            ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_STATIC,
333 6
            '__joinPoints',
334 6
            '[]'
335
        );
336 6
    }
337
338
    /**
339
     * Override parent method with joinpoint invocation
340
     *
341
     * @param ReflectionMethod $method Method reflection
342
     */
343 6
    protected function overrideMethod(ReflectionMethod $method)
344
    {
345
        // temporary disable override of final methods
346 6
        if (!$method->isFinal() && !$method->isAbstract()) {
347 6
            $this->override($method->name, $this->getJoinpointInvocationBody($method));
348
        }
349 6
    }
350
351
    /**
352
     * Creates definition for method body
353
     *
354
     * @param ReflectionMethod $method Method reflection
355
     *
356
     * @return string new method body
357
     */
358 6
    protected function getJoinpointInvocationBody(ReflectionMethod $method): string
359
    {
360 6
        $isStatic = $method->isStatic();
361 6
        $scope    = $isStatic ? self::$staticLsbExpression : '$this';
362 6
        $prefix   = $isStatic ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
363
364 6
        $args   = $this->prepareArgsLine($method);
365 6
        $return = 'return ';
366 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...
367
            $returnType = (string) $method->getReturnType();
368
            if ($returnType === 'void') {
369
                // void return types should not return anything
370
                $return = '';
371
            }
372
        }
373
374 6
        if (!empty($args)) {
375 3
            $scope = "$scope, $args";
376
        }
377
378 6
        $body = "{$return}self::\$__joinPoints['{$prefix}:{$method->name}']->__invoke($scope);";
379
380 6
        return $body;
381
    }
382
383
    /**
384
     * Makes property intercepted
385
     *
386
     * @param ReflectionProperty $property Reflection of property to intercept
387
     */
388
    protected function interceptProperty(ReflectionProperty $property)
389
    {
390
        $this->interceptedProperties[] = is_object($property) ? $property->name : $property;
391
        $this->isFieldsIntercepted = true;
392
    }
393
394
    /**
395
     * {@inheritDoc}
396
     */
397 6
    public function __toString()
398
    {
399 6
        $ctor = $this->class->getConstructor();
400 6
        if ($this->isFieldsIntercepted && (!$ctor || !$ctor->isPrivate())) {
401
            $this->addFieldInterceptorsCode($ctor);
402
        }
403
404 6
        $prefix = join(' ', Reflection::getModifierNames($this->class->getModifiers()));
405
406
        $classCode = (
407 6
            $this->class->getDocComment() . "\n" . // Original doc-block
408 6
            ($prefix ? "$prefix " : '') . // List of class modifiers
409 6
            'class ' . // 'class' keyword with one space
410 6
            $this->name . // Name of the class
411 6
            ' extends ' . // 'extends' keyword with
412 6
            $this->parentClassName . // Name of the parent class
413 6
            ($this->interfaces ? ' implements ' . join(', ', $this->interfaces) : '') . "\n" . // Interfaces list
414 6
            "{\n" . // Start of class definition
415 6
            ($this->traits ? $this->indent('use ' . join(', ', $this->traits) . ';' . "\n") : '') . "\n" . // Traits list
416 6
            $this->indent(join("\n", $this->propertiesCode)) . "\n" . // Property definitions
417 6
            $this->indent(join("\n", $this->methodsCode)) . "\n" . // Method definitions
418 6
            "}" // End of class definition
419
        );
420
421
        return $classCode
422
            // Inject advices on call
423 6
            . PHP_EOL
424 6
            . '\\' . __CLASS__ . "::injectJoinPoints('"
425 6
                . $this->class->name . "',"
426 6
                . var_export($this->advices, true) . ");";
427
    }
428
429
    /**
430
     * Add code for intercepting properties
431
     *
432
     * @param null|ReflectionMethod $constructor Constructor reflection or null
433
     */
434
    protected function addFieldInterceptorsCode(ReflectionMethod $constructor = null)
435
    {
436
        $this->addTrait(PropertyInterceptionTrait::class);
437
        $this->isFieldsIntercepted = true;
438
        if ($constructor) {
439
            $this->override('__construct', $this->getConstructorBody($constructor, true));
440
        } else {
441
            $this->setMethod(ReflectionMethod::IS_PUBLIC, '__construct', false, $this->getConstructorBody(), '');
442
        }
443
    }
444
445
    /**
446
     * Returns constructor code
447
     *
448
     * @param ReflectionMethod $constructor Constructor reflection
449
     * @param bool $isCallParent Is there is a need to call parent code
450
     *
451
     * @return string
452
     */
453
    private function getConstructorBody(ReflectionMethod $constructor = null, bool $isCallParent = false): string
454
    {
455
        $assocProperties = [];
456
        $listProperties  = [];
457
        foreach ($this->interceptedProperties as $propertyName) {
458
            $assocProperties[] = "'$propertyName' => &\$this->$propertyName";
459
            $listProperties[]  = "\$this->$propertyName";
460
        }
461
        $assocProperties = $this->indent(join(',' . PHP_EOL, $assocProperties));
462
        $listProperties  = $this->indent(join(',' . PHP_EOL, $listProperties));
463
        if (isset($this->methodsCode['__construct'])) {
464
            $parentCall = $this->getJoinpointInvocationBody($constructor);
0 ignored issues
show
Bug introduced by
It seems like $constructor defined by parameter $constructor on line 453 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...
465
        } elseif ($isCallParent) {
466
            $parentCall = '\call_user_func_array(["parent", __FUNCTION__], \func_get_args());';
467
        } else {
468
            $parentCall = '';
469
        }
470
471
        return <<<CTOR
472
\$this->__properties = array(
473
$assocProperties
474
);
475
unset(
476
$listProperties
477
);
478
$parentCall
479
CTOR;
480
    }
481
}
482