Completed
Pull Request — master (#310)
by Alexander
03:00
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
/*
3
 * Go! AOP framework
4
 *
5
 * @copyright Copyright 2012, Lisachenko Alexander <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace Go\Proxy;
12
13
use Go\Core\AspectContainer;
14
use Go\Core\AspectKernel;
15
use Go\Core\LazyAdvisorAccessor;
16
use ReflectionMethod;
17
18
/**
19
 * Trait proxy builder that is used to generate a trait from the list of joinpoints
20
 */
21
class TraitProxy extends ClassProxy
22
{
23
24
    /**
25
     * List of advices for traits
26
     *
27
     * @var array
28
     */
29
    protected static $traitAdvices = [];
30
31
    /**
32
     * Overridden static property for TraitProxy
33
     *
34
     * {@inheritDoc}
35
     */
36
    protected static $invocationClassMap = [];
37
38
    /**
39
     * Inject advices for given trait
40
     *
41
     * NB This method will be used as a callback during source code evaluation to inject joinpoints
42
     *
43
     * @param string $className Aop child proxy class
44
     * @param array|\Go\Aop\Advice[] $traitAdvices List of advices to inject into class
45
     *
46
     * @return void
47
     */
48
    public static function injectJoinPoints($className, array $traitAdvices = [])
49
    {
50
        self::$traitAdvices[$className] = $traitAdvices;
51
    }
52
53
    public static function getJoinPoint($traitName, $className, $joinPointType, $pointName)
54
    {
55
        /** @var LazyAdvisorAccessor $accessor */
56
        static $accessor = null;
57
58
        if (!isset($accessor)) {
59
            $aspectKernel = AspectKernel::getInstance();
60
            $accessor     = $aspectKernel->getContainer()->get('aspect.advisor.accessor');
61
        }
62
63
        $advices = self::$traitAdvices[$traitName][$joinPointType][$pointName];
64
65
        $filledAdvices = [];
66
        foreach ($advices as $advisorName) {
67
            $filledAdvices[] = $accessor->$advisorName;
68
        }
69
70
        $joinpoint = new self::$invocationClassMap[$joinPointType]($className, $pointName . '➩', $filledAdvices);
71
72
        return $joinpoint;
73
    }
74
75
    /**
76
     * Creates definition for trait method body
77
     *
78
     * @param ReflectionMethod $method Method reflection
79
     *
80
     * @return string new method body
81
     */
82
    protected function getJoinpointInvocationBody(ReflectionMethod $method)
83
    {
84
        $isStatic = $method->isStatic();
85
        $class    = '\\' . __CLASS__;
86
        $scope    = $isStatic ? self::$staticLsbExpression : '$this';
87
        $prefix   = $isStatic ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
88
89
        $args = $this->prepareArgsLine($method);
90
        $args = $scope . ($args ? ", $args" : '');
91
92
        $return = 'return ';
93
        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...
94
            $returnType = (string) $method->getReturnType();
95
            if ($returnType === 'void') {
96
                // void return types should not return anything
97
                $return = '';
98
            }
99
        }
100
101
        return <<<BODY
102
static \$__joinPoint = null;
103
if (!\$__joinPoint) {
104
    \$__joinPoint = {$class}::getJoinPoint(__TRAIT__, __CLASS__, '{$prefix}', '{$method->name}');
105
}
106
{$return}\$__joinPoint->__invoke($args);
107
BODY;
108
    }
109
110
    /**
111
     * {@inheritDoc}
112
     */
113
    public function __toString()
114
    {
115
        $classCode = (
116
            $this->class->getDocComment() . "\n" . // Original doc-block
117
            'trait ' . // 'trait' keyword
118
            $this->name . "\n" . // Name of the trait
119
            "{\n" . // Start of trait body
120
            $this->indent(
121
                'use ' . join(', ', array(-1 => $this->parentClassName) + $this->traits) .
122
                $this->getMethodAliasesCode()
123
            ) . "\n" . // Use traits and aliases section
124
            $this->indent(join("\n", $this->methodsCode)) . "\n" . // Method definitions
125
            "}" // End of trait body
126
        );
127
128
        return $classCode
129
            // Inject advices on call
130
            . PHP_EOL
131
            . '\\' . __CLASS__ . "::injectJoinPoints('"
132
                . $this->class->name . "',"
133
                . var_export($this->advices, true) . ");";
134
    }
135
136
    private function getMethodAliasesCode()
137
    {
138
        $aliasesLines = [];
139
        foreach (array_keys($this->methodsCode) as $methodName) {
140
            $aliasesLines[] = "{$this->parentClassName}::{$methodName} as protected {$methodName}➩;";
141
        }
142
143
        return "{\n " . $this->indent(join("\n", $aliasesLines)) . "\n}";
144
    }
145
}
146