Test Failed
Pull Request — master (#1045)
by Aleksei
07:42
created

ProxyClassRenderer   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 140
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 36
eloc 83
dl 0
loc 140
rs 9.52
c 1
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
C renderClass() 0 56 12
A cutDefaultValue() 0 5 1
A renderParameter() 0 10 6
A renderMethod() 0 12 4
B renderParameterTypes() 0 22 7
A normalizeClassType() 0 3 2
A renderDefaultValue() 0 15 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Core\Internal\Proxy;
6
7
/**
8
 * @internal
9
 */
10
final class ProxyClassRenderer
11
{
12
    public static function renderClass(\ReflectionClass $type, $className): string
13
    {
14
        $classShortName = \substr($className, \strrpos($className, '\\') + 1);
15
        $classNamespace = \substr($className, 0, \strrpos($className, '\\'));
16
17
        $interface = $type->getName();
18
        $classBody = [];
19
        foreach ($type->getMethods() as $method) {
20
            if ($method->isConstructor()) {
21
                continue;
22
            }
23
24
            $hasRefs = false;
25
            $return = $method->hasReturnType() && (string)$method->getReturnType() === 'void' ? '' : 'return ';
26
            $call = ($method->isStatic() ? '::' : '->') . $method->getName();
27
28
            $args = [];
29
            foreach ($method->getParameters() as $param) {
30
                $hasRefs = $hasRefs || $param->isPassedByReference();
31
                $args[] = ($param->isVariadic() ? '...' : '') . '$'. $param->getName();
32
            }
33
34
            if (!$hasRefs && !$method->isVariadic()) {
35
                $classBody[] = self::renderMethod($method, <<<PHP
36
                    {$return}\\Spiral\\Core\\Internal\\Proxy\\Resolver::resolve('{$interface}')
37
                        {$call}(...\\func_get_args());
38
                PHP);
39
                continue;
40
            }
41
42
            $argsStr = \implode(', ', $args);
43
44
            if ($method->isVariadic()) {
45
                $classBody[] = self::renderMethod($method, <<<PHP
46
                    {$return}\\Spiral\\Core\\Internal\\Proxy\\Resolver::resolve('{$interface}')
47
                        {$call}($argsStr);
48
                PHP);
49
                continue;
50
            }
51
52
            $classBody[] = self::renderMethod($method, <<<PHP
53
                {$return}\\Spiral\\Core\\Internal\\Proxy\\Resolver::resolve('{$interface}')
54
                    {$call}($argsStr, ...\\array_slice(\\func_get_args(), {$method->getNumberOfParameters()}));
55
            PHP);
56
        }
57
        $bodyStr = \implode("\n\n", $classBody);
58
59
        echo $bodyStr;
60
61
        return <<<PHP
62
            namespace $classNamespace;
63
64
            final class $classShortName implements \\$interface {
65
                use \Spiral\Core\Internal\Proxy\ProxyTrait;
66
67
            $bodyStr
68
            }
69
            PHP;
70
    }
71
72
    public static function renderMethod(\ReflectionMethod $m, string $body = ''): string
73
    {
74
        return \sprintf(
75
            "public%s function %s%s(%s)%s {\n%s\n}",
76
            $m->isStatic() ? ' static' : '',
77
            $m->returnsReference() ? '&' : '',
78
            $m->getName(),
79
            \implode(', ', \array_map([self::class, 'renderParameter'], $m->getParameters())),
80
            $m->hasReturnType()
81
                ? ': ' . self::renderParameterTypes($m->getReturnType(), $m->getDeclaringClass())
82
                : '',
83
            $body,
84
        );
85
    }
86
87
    public static function renderParameter(\ReflectionParameter $param): string
88
    {
89
        return \ltrim(\sprintf(
90
            '%s %s%s%s%s',
91
            $param->hasType() ? self::renderParameterTypes($param->getType(), $param->getDeclaringClass()) : '',
92
            $param->isPassedByReference() ? '&' : '',
93
            $param->isVariadic() ? '...' : '',
94
            '$' . $param->getName(),
95
            $param->isOptional() && !$param->isVariadic() ? ' = ' . self::renderDefaultValue($param) : '',
96
        ), ' ');
97
    }
98
99
    public static function renderParameterTypes(\ReflectionType $types, \ReflectionClass $class): string
100
    {
101
        if ($types instanceof \ReflectionNamedType) {
102
            return ($types->allowsNull() && $types->getName() !== 'mixed' ? '?' : '') . ($types->isBuiltin()
103
                ? $types->getName()
104
                : self::normalizeClassType($types, $class));
105
        }
106
107
        [$separator, $types] = match (true) {
108
            $types instanceof \ReflectionUnionType => ['|', $types->getTypes()],
0 ignored issues
show
Bug introduced by
The method getTypes() does not exist on ReflectionType. It seems like you code against a sub-type of ReflectionType such as ReflectionUnionType. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

108
            $types instanceof \ReflectionUnionType => ['|', $types->/** @scrutinizer ignore-call */ getTypes()],
Loading history...
109
            $types instanceof \ReflectionIntersectionType => ['&', $types->getTypes()],
0 ignored issues
show
Bug introduced by
The type ReflectionIntersectionType was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
110
            default => throw new \Exception('Unknown type.'),
111
        };
112
113
        $result = [];
114
        foreach ($types as $type) {
115
            $result[] = $type->isBuiltin()
116
                ? $type->getName()
117
                : self::normalizeClassType($type, $class);
118
        }
119
120
        return \implode($separator, $result);
121
    }
122
123
    public static function renderDefaultValue(\ReflectionParameter $param): string
124
    {
125
        if ($param->isDefaultValueConstant()) {
126
            $result = $param->getDefaultValueConstantName();
127
128
            return \explode('::', $result)[0] === 'self'
129
                ? $result
130
                : '\\' . $result;
131
        }
132
133
        $cut = self::cutDefaultValue($param);
134
135
        return \str_starts_with($cut, 'new ')
136
            ? $cut
137
            : \var_export($param->getDefaultValue(), true);
138
    }
139
140
    public static function normalizeClassType(\ReflectionNamedType $type, \ReflectionClass $class): string
141
    {
142
        return '\\' . ($type->getName() === 'self' ? $class->getName() : $type->getName());
143
    }
144
145
    private static function cutDefaultValue(\ReflectionParameter $param): string
146
    {
147
        $string = (string)$param;
148
149
        return \trim(\substr($string, \strpos($string, '=') + 1, -1));
150
    }
151
}
152