Passed
Pull Request — master (#59)
by Alexander
03:53 queued 01:15
created

InspectController   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 132
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 8
Bugs 0 Features 0
Metric Value
wmc 16
eloc 64
c 8
b 0
f 0
dl 0
loc 132
ccs 0
cts 63
cp 0
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A config() 0 12 1
A command() 0 19 2
A classes() 0 31 4
A params() 0 6 1
A translations() 0 32 5
A object() 0 15 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Debug\Api\Controller;
6
7
use InvalidArgumentException;
8
use Psr\Container\ContainerInterface;
9
use Psr\Http\Message\ResponseInterface;
10
use Psr\Http\Message\ServerRequestInterface;
11
use ReflectionClass;
12
use RuntimeException;
13
use Throwable;
14
use Yiisoft\Config\ConfigInterface;
15
use Yiisoft\DataResponse\DataResponseFactoryInterface;
16
use Yiisoft\Translator\CategorySource;
17
use Yiisoft\VarDumper\VarDumper;
18
use Yiisoft\Yii\Debug\Api\Inspector\ApplicationState;
19
use Yiisoft\Yii\Debug\Api\Inspector\Command\CodeceptionCommand;
20
use Yiisoft\Yii\Debug\Api\Inspector\Command\PHPUnitCommand;
21
use Yiisoft\Yii\Debug\Api\Inspector\Command\PsalmCommand;
22
23
class InspectController
24
{
25
    public function __construct(
26
        private DataResponseFactoryInterface $responseFactory,
27
    ) {
28
    }
29
30
    public function config(ContainerInterface $container, ServerRequestInterface $request): ResponseInterface
31
    {
32
        $config = $container->get(ConfigInterface::class);
33
34
        $request = $request->getQueryParams();
35
        $group = $request['group'] ?? 'web';
36
37
        $data = $config->get($group);
38
        ksort($data);
39
40
        $response = VarDumper::create($data)->asJson(false, 255);
41
        return $this->responseFactory->createResponse(json_decode($response, null, 512, JSON_THROW_ON_ERROR));
42
    }
43
44
    public function translations(ContainerInterface $container, ServerRequestInterface $request): ResponseInterface
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

44
    public function translations(ContainerInterface $container, /** @scrutinizer ignore-unused */ ServerRequestInterface $request): ResponseInterface

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
45
    {
46
        /**
47
         * @var $categorySources CategorySource[]
48
         */
49
        $categorySources = $container->get('[email protected]');
50
51
        $params = ApplicationState::$params;
52
53
        $locales = array_keys($params['locale']['locales']);
54
        if ($locales === []) {
55
            throw new RuntimeException(
56
                'Unable to determine list of available locales. ' .
57
                'Make sure that "$params[\'locale\'][\'locales\']" contains all available locales.'
58
            );
59
        }
60
        $messages = [];
61
        foreach ($categorySources as $categorySource) {
62
            $messages[$categorySource->getName()] = [
63
                'messages' => [],
64
            ];
65
66
            try {
67
                foreach ($locales as $locale) {
68
                    $messages[$categorySource->getName()]['messages'][$locale] = $categorySource->getMessages($locale);
0 ignored issues
show
Bug introduced by
The method getMessages() does not exist on Yiisoft\Translator\CategorySource. Did you maybe mean getMessage()? ( Ignorable by Annotation )

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

68
                    /** @scrutinizer ignore-call */ 
69
                    $messages[$categorySource->getName()]['messages'][$locale] = $categorySource->getMessages($locale);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
69
                }
70
            } catch (Throwable) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
71
            }
72
        }
73
74
        $response = VarDumper::create($messages)->asPrimitives(255);
75
        return $this->responseFactory->createResponse($response);
76
    }
77
78
    public function params(): ResponseInterface
79
    {
80
        $params = ApplicationState::$params;
81
        ksort($params);
82
83
        return $this->responseFactory->createResponse($params);
84
    }
85
86
    public function classes(ContainerInterface $container): ResponseInterface
0 ignored issues
show
Unused Code introduced by
The parameter $container is not used and could be removed. ( Ignorable by Annotation )

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

86
    public function classes(/** @scrutinizer ignore-unused */ ContainerInterface $container): ResponseInterface

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
87
    {
88
        // TODO: how to get params for console or other param groups?
89
        $classes = [];
90
91
        $inspected = [...get_declared_classes(), ...get_declared_interfaces()];
92
        // TODO: think how to ignore heavy objects
93
        $patterns = [
94
            fn (string $class) => !str_starts_with($class, 'ComposerAutoloaderInit'),
95
            fn (string $class) => !str_starts_with($class, 'Composer\\'),
96
            fn (string $class) => !str_starts_with($class, 'Yiisoft\\Yii\\Debug\\'),
97
            fn (string $class) => !str_starts_with($class, 'Yiisoft\\ErrorHandler\\ErrorHandler'),
98
            fn (string $class) => !str_contains($class, '@anonymous'),
99
            fn (string $class) => !is_subclass_of($class, Throwable::class),
100
        ];
101
        foreach ($patterns as $patternFunction) {
102
            $inspected = array_filter($inspected, $patternFunction);
103
        }
104
105
        foreach ($inspected as $className) {
106
            $class = new ReflectionClass($className);
107
108
            if ($class->isInternal()) {
109
                continue;
110
            }
111
112
            $classes[] = $className;
113
        }
114
        sort($classes);
115
116
        return $this->responseFactory->createResponse($classes);
117
    }
118
119
    public function object(ContainerInterface $container, ServerRequestInterface $request): ResponseInterface
120
    {
121
        $request = $request->getQueryParams();
122
        $className = $request['classname'];
123
124
        $class = new ReflectionClass($className);
125
126
        if ($class->isInternal()) {
127
            throw new InvalidArgumentException('error');
128
        }
129
130
        $variable = $container->get($className);
131
        $result = VarDumper::create($variable)->asJson();
132
133
        return $this->responseFactory->createResponse(json_decode($result, null, 512, JSON_THROW_ON_ERROR));
134
    }
135
136
    public function command(ServerRequestInterface $request, ContainerInterface $container): ResponseInterface
137
    {
138
        // TODO: would be great to recognise test engine automatically
139
        $map = [
140
            'test/phpunit' => PHPUnitCommand::class,
141
            'test/codeception' => CodeceptionCommand::class,
142
            'analyse/psalm' => PsalmCommand::class,
143
        ];
144
145
        $request = $request->getQueryParams();
146
        $commandName = $request['command'] ?? 'test/codeception';
147
148
        if (!array_key_exists($commandName, $map)) {
149
            throw new InvalidArgumentException('Unknown command');
150
        }
151
152
        $result = $container->get($map[$commandName])->run();
153
154
        return $this->responseFactory->createResponse($result);
155
    }
156
}
157