Passed
Pull Request — master (#59)
by Dmitriy
02:45
created

InspectController::config()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 7
c 2
b 0
f 0
dl 0
loc 12
ccs 0
cts 8
cp 0
rs 10
cc 1
nc 1
nop 2
crap 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
            foreach ($locales as $locale) {
67
                $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

67
                /** @scrutinizer ignore-call */ 
68
                $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...
68
            }
69
        }
70
71
        $response = VarDumper::create($messages)->asPrimitives(255);
72
        return $this->responseFactory->createResponse($response);
73
    }
74
75
    public function params(): ResponseInterface
76
    {
77
        $params = ApplicationState::$params;
78
        ksort($params);
79
80
        return $this->responseFactory->createResponse($params);
81
    }
82
83
    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

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