Completed
Pull Request — master (#256)
by Alexander
06:46
created

AbstractProxy   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 215
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 91.86%

Importance

Changes 9
Bugs 2 Features 3
Metric Value
wmc 36
c 9
b 2
f 3
lcom 1
cbo 0
dl 0
loc 215
ccs 79
cts 86
cp 0.9186
rs 8.8

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
__toString() 0 1 ?
A indent() 0 9 1
A getParameters() 0 9 2
F getParameterCode() 0 36 13
A flattenAdvices() 0 13 4
C prepareArgsLine() 0 28 8
C getOverriddenFunction() 0 30 7
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 Reflection;
14
use ReflectionFunctionAbstract;
15
use ReflectionMethod;
16
use ReflectionParameter;
17
18
/**
19
 * Abstract class for building different proxies
20
 */
21
abstract class AbstractProxy
22
{
23
24
    /**
25
     * Indent for source code
26
     *
27
     * @var int
28
     */
29
    protected $indent = 4;
30
31
    /**
32
     * List of advices that are used for generation of child
33
     *
34
     * @var array
35
     */
36
    protected $advices = [];
37
38
    /**
39
     * PHP expression string for accessing LSB information
40
     *
41
     * @var string
42
     */
43
    protected static $staticLsbExpression = 'static::class';
44
45
    /**
46
     * Constructs an abstract proxy class
47
     *
48
     * @param array $advices List of advices
49
     */
50 6
    public function __construct(array $advices = [])
51
    {
52 6
        $this->advices = $this->flattenAdvices($advices);
53 6
    }
54
55
    /**
56
     * Returns text representation of class
57
     *
58
     * @return string
59
     */
60
    abstract public function __toString();
61
62
    /**
63
     * Indent block of code
64
     *
65
     * @param string $text Non-indented text
66
     *
67
     * @return string Indented text
68
     */
69 6
    protected function indent($text)
70
    {
71 6
        $pad   = str_pad('', $this->indent, ' ');
72 6
        $lines = array_map(function($line) use ($pad) {
73 6
            return $pad . $line;
74 6
        }, explode("\n", $text));
75
76 6
        return join("\n", $lines);
77
    }
78
79
    /**
80
     * Returns list of string representation of parameters
81
     *
82
     * @param array|ReflectionParameter[] $parameters List of parameters
83
     *
84
     * @return array
85
     */
86 6
    protected function getParameters(array $parameters)
87
    {
88 6
        $parameterDefinitions = [];
89 6
        foreach ($parameters as $parameter) {
90 3
            $parameterDefinitions[] = $this->getParameterCode($parameter);
91
        }
92
93 6
        return $parameterDefinitions;
94
    }
95
96
    /**
97
     * Return string representation of parameter
98
     *
99
     * @param ReflectionParameter $parameter Reflection parameter
100
     *
101
     * @return string
102
     */
103 3
    protected function getParameterCode(ReflectionParameter $parameter)
104
    {
105 3
        $type = '';
106 3
        if (PHP_VERSION_ID >= 50700) {
107 3
            $reflectionType = $parameter->getType();
108 3
            if ($reflectionType) {
109 1
                $nsPrefix = $reflectionType->isBuiltin() ? '' : '\\';
110 3
                $type     = $nsPrefix . (string) $reflectionType;
111
            }
112
        } else {
113
            if ($parameter->isArray()) {
114
                $type = 'array';
115
            } elseif ($parameter->isCallable()) {
116
                $type = 'callable';
117
            } elseif ($parameter->getClass()) {
118
                $type = '\\' . $parameter->getClass()->name;
119
            }
120
        }
121 3
        $defaultValue = null;
122 3
        $isDefaultValueAvailable = $parameter->isDefaultValueAvailable();
123 3
        if ($isDefaultValueAvailable) {
124 2
            $defaultValue = var_export($parameter->getDefaultValue(), true);
125 3
        } elseif ($parameter->isOptional()) {
126
            $defaultValue = 'null';
127
        }
128
        $code = (
129 3
            ($type ? "$type " : '') . // Typehint
130 3
            ($parameter->isPassedByReference() ? '&' : '') . // By reference sign
131 3
            ($parameter->isVariadic() ? '...' : '') . // Variadic symbol
132 3
            '$' . // Variable symbol
133 3
            ($parameter->name) . // Name of the argument
134 3
            ($defaultValue !== null ? (" = " . $defaultValue) : '') // Default value if present
135
        );
136
137 3
        return $code;
138
    }
139
140
    /**
141
     * Replace concrete advices with list of ids
142
     *
143
     * @param $advices
144
     *
145
     * @return array flatten list of advices
146
     */
147 6
    private function flattenAdvices($advices)
148
    {
149 6
        $flattenAdvices = [];
150 6
        foreach ($advices as $type => $typedAdvices) {
151 6
            foreach ($typedAdvices as $name => $concreteAdvices) {
152 6
                if (is_array($concreteAdvices)) {
153 6
                    $flattenAdvices[$type][$name] = array_keys($concreteAdvices);
154
                }
155
            }
156
        }
157
158 6
        return $flattenAdvices;
159
    }
160
161
    /**
162
     * Prepares a line with args from the method definition
163
     *
164
     * @param ReflectionFunctionAbstract $functionLike
165
     *
166
     * @return string
167
     */
168 6
    protected function prepareArgsLine(ReflectionFunctionAbstract $functionLike)
169
    {
170 6
        $argumentsPart = [];
171 6
        $arguments     = [];
172 6
        $hasOptionals  = false;
173
174 6
        foreach ($functionLike->getParameters() as $parameter) {
175 3
            $byReference  = ($parameter->isPassedByReference() && !$parameter->isVariadic()) ? '&' : '';
176 3
            $hasOptionals = $hasOptionals || $parameter->isOptional();
177
178 3
            $arguments[] = $byReference . '$' . $parameter->name;
179
        }
180
181 6
        $isVariadic = $functionLike->isVariadic();
182 6
        if ($isVariadic) {
183 1
            $argumentsPart[] = array_pop($arguments);
184
        }
185 6
        if (!empty($arguments)) {
186
            // Unshifting to keep correct order
187 3
            $argumentLine = '[' . join(', ', $arguments) . ']';
188 3
            if ($hasOptionals) {
189 2
                $argumentLine = "\\array_slice($argumentLine, 0, \\func_num_args())";
190
            }
191 3
            array_unshift($argumentsPart, $argumentLine);
192
        }
193
194 6
        return join(', ', $argumentsPart);
195
    }
196
197
    /**
198
     * Creates a function code from Reflection
199
     *
200
     * @param ReflectionFunctionAbstract $functionLike Reflection for method
201
     * @param string $body Body of method
202
     *
203
     * @return string
204
     */
205 6
    protected function getOverriddenFunction(ReflectionFunctionAbstract $functionLike, $body)
206
    {
207 6
        $reflectionReturnType = PHP_VERSION_ID >= 50700 ? $functionLike->getReturnType() : '';
1 ignored issue
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ReflectionFunctionAbstract as the method getReturnType() does only exist in the following sub-classes of ReflectionFunctionAbstract: Go\ParserReflection\ReflectionFunction, 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...
208 6
        $modifiersLine        = '';
209 6
        if ($reflectionReturnType) {
210 1
            $nsPrefix             = $reflectionReturnType->isBuiltin() ? '' : '\\';
211 1
            $reflectionReturnType = $nsPrefix . (string)$reflectionReturnType;
212
        }
213 6
        if ($functionLike instanceof ReflectionMethod) {
214 6
            $modifiersLine = join(' ', Reflection::getModifierNames($functionLike->getModifiers()));
215
        }
216
217
        $code = (
218 6
            preg_replace('/ {4}|\t/', '', $functionLike->getDocComment()) . "\n" . // Original Doc-block
219 6
            $modifiersLine . // List of modifiers (for methods)
220 6
            ' function ' . // 'function' keyword
221 6
            ($functionLike->returnsReference() ? '&' : '') . // By reference symbol
222 6
            $functionLike->name . // Name of the function
223 6
            '(' . // Start of parameters list
224 6
            join(', ', $this->getParameters($functionLike->getParameters())) . // List of parameters
225 6
            ")" . // End of parameters list
226 6
            ($reflectionReturnType ? " : $reflectionReturnType" : '') . // Return type, if present
227 6
            "\n" .
228 6
            "{\n" . // Start of method body
229 6
            $this->indent($body) . "\n" . // Method body
230 6
            "}\n" // End of method body
231
        );
232
233 6
        return $code;
234
    }
235
}
236