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

TraitProxy::injectJoinPoints()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 0
cts 4
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 2
crap 2
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\Intercept\MethodInvocation;
15
use Go\Core\AspectContainer;
16
use Go\Core\AspectKernel;
17
use Go\Core\LazyAdvisorAccessor;
18
use ReflectionMethod;
19
20
/**
21
 * Trait proxy builder that is used to generate a trait from the list of joinpoints
22
 */
23
class TraitProxy extends ClassProxy
24
{
25
26
    /**
27
     * List of advices for traits
28
     *
29
     * @var array
30
     */
31
    protected static $traitAdvices = [];
32
33
    /**
34
     * Inject advices for given trait
35
     *
36
     * NB This method will be used as a callback during source code evaluation to inject joinpoints
37
     *
38
     * @param string $className Aop child proxy class
39
     * @param array|\Go\Aop\Advice[] $traitAdvices List of advices to inject into class
40
     */
41
    public static function injectJoinPoints(string $className, array $traitAdvices = [])
42
    {
43
        self::$traitAdvices[$className] = $traitAdvices;
44
    }
45
46
    /**
47
     * Returns a joinpoint for the specific trait
48
     *
49
     * @param string $traitName Name of the trait
50
     * @param string $className Name of the class
51
     * @param string $joinPointType Type of joinpoint (static or dynamic method)
52
     * @param string $methodName Name of the method
53
     *
54
     * @return MethodInvocation
55
     */
56
    public static function getJoinPoint(
57
        string $traitName,
58
        string $className,
59
        string $joinPointType,
60
        string $methodName
61
    ): MethodInvocation {
62
        /** @var LazyAdvisorAccessor $accessor */
63
        static $accessor = null;
64
65
        if (!isset($accessor)) {
66
            $aspectKernel = AspectKernel::getInstance();
67
            $accessor     = $aspectKernel->getContainer()->get('aspect.advisor.accessor');
68
        }
69
70
        $advices = self::$traitAdvices[$traitName][$joinPointType][$methodName];
71
72
        $filledAdvices = [];
73
        foreach ($advices as $advisorName) {
74
            $filledAdvices[] = $accessor->$advisorName;
75
        }
76
77
        $joinpoint = new self::$invocationClassMap[$joinPointType]($className, $methodName . '➩', $filledAdvices);
78
79
        return $joinpoint;
80
    }
81
82
    /**
83
     * Creates definition for trait method body
84
     *
85
     * @param ReflectionMethod $method Method reflection
86
     *
87
     * @return string new method body
88
     */
89
    protected function getJoinpointInvocationBody(ReflectionMethod $method): string
90
    {
91
        $isStatic = $method->isStatic();
92
        $class    = '\\' . __CLASS__;
93
        $scope    = $isStatic ? self::$staticLsbExpression : '$this';
94
        $prefix   = $isStatic ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
95
96
        $args = $this->prepareArgsLine($method);
97
        $args = $scope . ($args ? ", $args" : '');
98
99
        $return = 'return ';
100
        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...
101
            $returnType = (string) $method->getReturnType();
102
            if ($returnType === 'void') {
103
                // void return types should not return anything
104
                $return = '';
105
            }
106
        }
107
108
        return <<<BODY
109
static \$__joinPoint = null;
110
if (!\$__joinPoint) {
111
    \$__joinPoint = {$class}::getJoinPoint(__TRAIT__, __CLASS__, '{$prefix}', '{$method->name}');
112
}
113
{$return}\$__joinPoint->__invoke($args);
114
BODY;
115
    }
116
117
    /**
118
     * {@inheritDoc}
119
     */
120
    public function __toString()
121
    {
122
        $classCode = (
123
            $this->class->getDocComment() . "\n" . // Original doc-block
124
            'trait ' . // 'trait' keyword
125
            $this->name . "\n" . // Name of the trait
126
            "{\n" . // Start of trait body
127
            $this->indent(
128
                'use ' . join(', ', [-1 => $this->parentClassName] + $this->traits) .
129
                $this->getMethodAliasesCode()
130
            ) . "\n" . // Use traits and aliases section
131
            $this->indent(join("\n", $this->methodsCode)) . "\n" . // Method definitions
132
            "}" // End of trait body
133
        );
134
135
        return $classCode
136
            // Inject advices on call
137
            . PHP_EOL
138
            . '\\' . __CLASS__ . "::injectJoinPoints('"
139
                . $this->class->name . "',"
140
                . var_export($this->advices, true) . ");";
141
    }
142
143
    /**
144
     * Returns prepared aliased code for usage in trait section
145
     *
146
     * @return string
147
     */
148
    private function getMethodAliasesCode(): string
149
    {
150
        $aliasesLines = [];
151
        foreach (array_keys($this->methodsCode) as $methodName) {
152
            $aliasesLines[] = "{$this->parentClassName}::{$methodName} as protected {$methodName}➩;";
153
        }
154
155
        return "{\n " . $this->indent(join("\n", $aliasesLines)) . "\n}";
156
    }
157
}
158