Passed
Pull Request — master (#1115)
by Maxim
22:29
created

ProxyClassRenderer::renderClass()   F

Complexity

Conditions 17
Paths 1940

Size

Total Lines 101
Code Lines 67

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 68
CRAP Score 17.0928

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 67
dl 0
loc 101
ccs 68
cts 73
cp 0.9315
rs 1.0499
c 1
b 0
f 0
cc 17
nc 1940
nop 4
crap 17.0928

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
    /**
13
     * @param \ReflectionClass $type Interface reflection.
14
     * @param string $className Class name to use in the generated code.
15
     * @param bool $defineOverload Define __call() and __callStatic() methods.
16
     * @param bool $attachContainer Attach container to the proxy.
17
     *
18
     * @return non-empty-string PHP code
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
19
     */
20 13
    public static function renderClass(
21
        \ReflectionClass $type,
22
        string $className,
23
        bool $defineOverload = false,
24
        bool $attachContainer = false,
25
    ): string {
26 13
        $traits = $defineOverload ? [
27 13
            MagicCallTrait::class,
28 13
        ] : [];
29
30 13
        if (\str_contains($className, '\\')) {
31 11
            $classShortName = \substr($className, \strrpos($className, '\\') + 1);
32 11
            $classNamespaceStr = 'namespace ' . \substr($className, 0, \strrpos($className, '\\')) . ';';
33
        } else {
34 2
            $classShortName = $className;
35 2
            $classNamespaceStr = '';
36
        }
37
38 13
        $interface = $type->getName();
39 13
        $classBody = [];
40 13
        foreach ($type->getMethods() as $method) {
41 12
            if ($method->isConstructor()) {
42 1
                throw new \LogicException('Constructor is not allowed in a proxy.');
43
            }
44
45 11
            if ($method->isDestructor()) {
46 1
                $classBody[] = self::renderMethod($method);
47 1
                continue;
48
            }
49
50 10
            $hasRefs = false;
51 10
            $return = $method->hasReturnType() && (string)$method->getReturnType() === 'void' ? '' : 'return ';
52 10
            $call = ($method->isStatic() ? '::' : '->') . $method->getName();
53 10
            $context = $method->isStatic() ? 'null' : '$this->__container_proxy_context';
54 10
            $containerStr = match (false) {
55 10
                $attachContainer => 'null',
56
                /** @see \Spiral\Core\Internal\Proxy\ProxyTrait::__container_proxy_container */
57
                $method->isStatic() => '$this->__container_proxy_container',
58
                default => \sprintf(
59
                    'throw new \Spiral\Core\Exception\Container\ContainerException(\'%s\')',
60
                    'Static method call is not allowed on a Proxy that was created without dynamic scope.',
61
                ),
62 10
            };
63 10
            $resolveStr = <<<PHP
64 10
                \\Spiral\\Core\\Internal\\Proxy\\Resolver::resolve(
65 10
                    '{$interface}',
66 10
                    {$context},
67 10
                    {$containerStr},
68
                )
69 10
                PHP;
70
71 10
            $args = [];
72 10
            foreach ($method->getParameters() as $param) {
73 8
                $hasRefs = $hasRefs || $param->isPassedByReference();
74 8
                $args[] = ($param->isVariadic() ? '...' : '') . '$' . $param->getName();
75
            }
76
77 10
            if (!$hasRefs && !$method->isVariadic()) {
78 10
                $classBody[] = self::renderMethod(
79 10
                    $method,
80 10
                    <<<PHP
81 10
                    {$return}{$resolveStr}{$call}(...\\func_get_args());
82 10
                PHP
83 10
                );
84 10
                continue;
85
            }
86
87 1
            $argsStr = \implode(', ', $args);
88
89 1
            if ($method->isVariadic()) {
90 1
                $classBody[] = self::renderMethod(
91 1
                    $method,
92 1
                    <<<PHP
93 1
                    {$return}{$resolveStr}{$call}($argsStr);
94 1
                PHP
95 1
                );
96 1
                continue;
97
            }
98
99 1
            $countParams = $method->getNumberOfParameters();
100 1
            $classBody[] = self::renderMethod(
101 1
                $method,
102 1
                <<<PHP
103 1
                {$return}{$resolveStr}{$call}($argsStr, ...\\array_slice(\\func_get_args(), {$countParams}));
104 1
            PHP
105 1
            );
106
        }
107 12
        $bodyStr = \implode("\n\n", $classBody);
108
109 12
        $traitsStr = $traits === [] ? '' : \implode(
110 12
            "\n    ",
111 12
            \array_map(fn (string $trait): string => 'use \\' . \ltrim($trait, '\\') . ';', $traits)
112 12
        );
113 12
        return <<<PHP
114 12
            $classNamespaceStr
115
116 12
            final class $classShortName implements \\$interface {
117
                use \Spiral\Core\Internal\Proxy\ProxyTrait;
118 12
                $traitsStr
119
120 12
            $bodyStr
121
            }
122 12
            PHP;
123
    }
124
125 16
    public static function renderMethod(\ReflectionMethod $m, string $body = ''): string
126
    {
127 16
        return \sprintf(
128 16
            "public%s function %s%s(%s)%s {\n%s\n}",
129 16
            $m->isStatic() ? ' static' : '',
130 16
            $m->returnsReference() ? '&' : '',
131 16
            $m->getName(),
132 16
            \implode(', ', \array_map([self::class, 'renderParameter'], $m->getParameters())),
133 16
            $m->hasReturnType()
134 13
                ? ': ' . self::renderParameterTypes($m->getReturnType(), $m->getDeclaringClass())
135 16
                : '',
136 16
            $body,
137 16
        );
138
    }
139
140 33
    public static function renderParameter(\ReflectionParameter $param): string
141
    {
142 33
        return \ltrim(
143 33
            \sprintf(
144 33
                '%s %s%s%s%s',
145 33
                $param->hasType() ? 'mixed' : '',
146 33
                $param->isPassedByReference() ? '&' : '',
147 33
                $param->isVariadic() ? '...' : '',
148 33
                '$' . $param->getName(),
149 33
                $param->isOptional() && !$param->isVariadic() ? ' = ' . self::renderDefaultValue($param) : '',
150 33
            ),
151 33
            ' '
152 33
        );
153
    }
154
155 30
    public static function renderParameterTypes(\ReflectionType $types, \ReflectionClass $class): string
156
    {
157 30
        if ($types instanceof \ReflectionNamedType) {
158 23
            return ($types->allowsNull() && $types->getName() !== 'mixed' ? '?' : '') . ($types->isBuiltin()
159 18
                    ? $types->getName()
160 23
                    : self::normalizeClassType($types, $class));
161
        }
162
163 8
        [$separator, $types] = match (true) {
164 8
            $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

164
            $types instanceof \ReflectionUnionType => ['|', $types->/** @scrutinizer ignore-call */ getTypes()],
Loading history...
165 1
            $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...
166
            default => throw new \Exception('Unknown type.'),
167 8
        };
168
169 8
        $result = [];
170 8
        foreach ($types as $type) {
171 8
            $result[] = $type->isBuiltin()
172 7
                ? $type->getName()
173 3
                : self::normalizeClassType($type, $class);
174
        }
175
176 8
        return \implode($separator, $result);
177
    }
178
179 7
    public static function renderDefaultValue(\ReflectionParameter $param): string
180
    {
181 7
        if ($param->isDefaultValueConstant()) {
182
            $result = $param->getDefaultValueConstantName();
183
184
            return \explode('::', $result)[0] === 'self'
185
                ? $result
186
                : '\\' . $result;
187
        }
188
189 7
        $cut = self::cutDefaultValue($param);
190
191 7
        return \str_starts_with($cut, 'new ')
192
            ? $cut
193 7
            : \var_export($param->getDefaultValue(), true);
194
    }
195
196 9
    public static function normalizeClassType(\ReflectionNamedType $type, \ReflectionClass $class): string
197
    {
198 9
        return '\\' . ($type->getName() === 'self' ? $class->getName() : $type->getName());
199
    }
200
201 7
    private static function cutDefaultValue(\ReflectionParameter $param): string
202
    {
203 7
        $string = (string)$param;
204
205 7
        return \trim(\substr($string, \strpos($string, '=') + 1, -1));
206
    }
207
}
208