Passed
Push — master ( 7bd689...ed0e19 )
by butschster
16:50 queued 18s
created

ProxyClassRenderer::renderParameter()   A

Complexity

Conditions 6
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 12
ccs 11
cts 11
cp 1
rs 9.2222
cc 6
nc 1
nop 1
crap 6
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 7
    public static function renderClass(
21
        \ReflectionClass $type,
22
        string $className,
23
        bool $defineOverload = false,
24
        bool $attachContainer = false,
25
    ): string {
26 7
        $traits = $defineOverload ? [
27 7
            MagicCallTrait::class,
28 7
        ] : [];
29
30 7
        if (\str_contains($className, '\\')) {
31 5
            $classShortName = \substr($className, \strrpos($className, '\\') + 1);
32 5
            $classNamespaceStr = 'namespace ' . \substr($className, 0, \strrpos($className, '\\')) . ';';
33
        } else {
34 2
            $classShortName = $className;
35 2
            $classNamespaceStr = '';
36
        }
37
38 7
        $interface = $type->getName();
39 7
        $classBody = [];
40 7
        foreach ($type->getMethods() as $method) {
41 6
            if ($method->isConstructor()) {
42 1
                throw new \LogicException('Constructor is not allowed in a proxy.');
43
            }
44
45 5
            if ($method->isDestructor()) {
46 1
                $classBody[] = self::renderMethod($method);
47 1
                continue;
48
            }
49
50 4
            $hasRefs = false;
51 4
            $return = $method->hasReturnType() && (string)$method->getReturnType() === 'void' ? '' : 'return ';
52 4
            $call = ($method->isStatic() ? '::' : '->') . $method->getName();
53 4
            $context = $method->isStatic() ? 'null' : '$this->__container_proxy_context';
54 4
            $containerStr = match (false) {
55 4
                $attachContainer => 'null',
56
                /** @see \Spiral\Core\Internal\Proxy\ProxyTrait::__container_proxy_container */
57 4
                $method->isStatic() => '$this->__container_proxy_container',
58 4
                default => \sprintf(
59 4
                    'throw new \Spiral\Core\Exception\Container\ContainerException(\'%s\')',
60 4
                    'Static method call is not allowed on a Proxy that was created without dynamic scope.',
61 4
                ),
62 4
            };
63 4
            $resolveStr = <<<PHP
64 4
                \\Spiral\\Core\\Internal\\Proxy\\Resolver::resolve(
65 4
                    '{$interface}',
66 4
                    {$context},
67 4
                    {$containerStr},
68
                )
69 4
                PHP;
70
71 4
            $args = [];
72 4
            foreach ($method->getParameters() as $param) {
73 2
                $hasRefs = $hasRefs || $param->isPassedByReference();
74 2
                $args[] = ($param->isVariadic() ? '...' : '') . '$' . $param->getName();
75
            }
76
77 4
            if (!$hasRefs && !$method->isVariadic()) {
78 4
                $classBody[] = self::renderMethod(
79 4
                    $method,
80 4
                    <<<PHP
81 4
                    {$return}{$resolveStr}{$call}(...\\func_get_args());
82 4
                PHP
83 4
                );
84 4
                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 6
        $bodyStr = \implode("\n\n", $classBody);
108
109 6
        $traitsStr = $traits === [] ? '' : \implode(
110 6
            "\n    ",
111 6
            \array_map(fn (string $trait): string => 'use \\' . \ltrim($trait, '\\') . ';', $traits)
112 6
        );
113 6
        return <<<PHP
114 6
            $classNamespaceStr
115
116 6
            final class $classShortName implements \\$interface {
117
                use \Spiral\Core\Internal\Proxy\ProxyTrait;
118 6
                $traitsStr
119
120 6
            $bodyStr
121
            }
122 6
            PHP;
123
    }
124
125 10
    public static function renderMethod(\ReflectionMethod $m, string $body = ''): string
126
    {
127 10
        return \sprintf(
128 10
            "public%s function %s%s(%s)%s {\n%s\n}",
129 10
            $m->isStatic() ? ' static' : '',
130 10
            $m->returnsReference() ? '&' : '',
131 10
            $m->getName(),
132 10
            \implode(', ', \array_map([self::class, 'renderParameter'], $m->getParameters())),
133 10
            $m->hasReturnType()
134 7
                ? ': ' . self::renderParameterTypes($m->getReturnType(), $m->getDeclaringClass())
135 10
                : '',
136 10
            $body,
137 10
        );
138
    }
139
140 27
    public static function renderParameter(\ReflectionParameter $param): string
141
    {
142 27
        return \ltrim(
143 27
            \sprintf(
144 27
                '%s %s%s%s%s',
145 27
                $param->hasType() ? self::renderParameterTypes($param->getType(), $param->getDeclaringClass()) : '',
146 27
                $param->isPassedByReference() ? '&' : '',
147 27
                $param->isVariadic() ? '...' : '',
148 27
                '$' . $param->getName(),
149 27
                $param->isOptional() && !$param->isVariadic() ? ' = ' . self::renderDefaultValue($param) : '',
150 27
            ),
151 27
            ' '
152 27
        );
153
    }
154
155 28
    public static function renderParameterTypes(\ReflectionType $types, \ReflectionClass $class): string
156
    {
157 28
        if ($types instanceof \ReflectionNamedType) {
158 21
            return ($types->allowsNull() && $types->getName() !== 'mixed' ? '?' : '') . ($types->isBuiltin()
159 18
                    ? $types->getName()
160 21
                    : 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 8
            $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 8
            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 1
    public static function renderDefaultValue(\ReflectionParameter $param): string
180
    {
181 1
        if ($param->isDefaultValueConstant()) {
182
            $result = $param->getDefaultValueConstantName();
183
184
            return \explode('::', $result)[0] === 'self'
185
                ? $result
186
                : '\\' . $result;
187
        }
188
189 1
        $cut = self::cutDefaultValue($param);
190
191 1
        return \str_starts_with($cut, 'new ')
192
            ? $cut
193 1
            : \var_export($param->getDefaultValue(), true);
194
    }
195
196 1
    public static function normalizeClassType(\ReflectionNamedType $type, \ReflectionClass $class): string
197
    {
198 1
        return '\\' . ($type->getName() === 'self' ? $class->getName() : $type->getName());
199
    }
200
201 1
    private static function cutDefaultValue(\ReflectionParameter $param): string
202
    {
203 1
        $string = (string)$param;
204
205 1
        return \trim(\substr($string, \strpos($string, '=') + 1, -1));
206
    }
207
}
208