Passed
Pull Request — master (#58)
by Dmitriy
02:50
created

DefaultController::createErrorResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 3
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Gii\Controller;
6
7
use Psr\Http\Message\ResponseInterface;
8
use Yiisoft\DataResponse\DataResponse;
9
use Yiisoft\DataResponse\DataResponseFactoryInterface;
10
use Yiisoft\Http\Status;
11
use Yiisoft\RequestModel\Attribute\Query;
12
use Yiisoft\Yii\Gii\CodeFile;
13
use Yiisoft\Yii\Gii\CodeFileSaver;
14
use Yiisoft\Yii\Gii\Exception\InvalidGeneratorCommandException;
15
use Yiisoft\Yii\Gii\Generator\CommandHydrator;
16
use Yiisoft\Yii\Gii\GeneratorCommandInterface;
17
use Yiisoft\Yii\Gii\Request\GeneratorRequest;
18
19
final class DefaultController
20
{
21
    public function __construct(private DataResponseFactoryInterface $responseFactory)
22
    {
23
    }
24
25
    public function get(GeneratorRequest $request): ResponseInterface
26
    {
27
        $generator = $request->getGenerator();
28
        /**
29
         * @psalm-var class-string<GeneratorCommandInterface> $commandClass
30
         */
31
        $commandClass = $generator::getCommandClass();
32
        $params = [
33
            'id' => $generator::getId(),
34
            'name' => $generator::getName(),
35
            'description' => $generator::getDescription(),
36
            'commandClass' => $commandClass,
37
            'hints' => $commandClass::getHints(),
38
            'attributeLabels' => $commandClass::getAttributeLabels(),
39
            //            'templatePath' => $generator->getTemplatePath(),
40
            //            'templates' => $generator->getTemplates(),
41
            'directory' => $generator->getDirectory(),
0 ignored issues
show
Bug introduced by
The method getDirectory() does not exist on Yiisoft\Yii\Gii\GeneratorInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Yiisoft\Yii\Gii\GeneratorInterface. ( Ignorable by Annotation )

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

41
            'directory' => $generator->/** @scrutinizer ignore-call */ getDirectory(),
Loading history...
42
        ];
43
44
        return $this->responseFactory->createResponse($params);
45
    }
46
47
    public function generate(
48
        GeneratorRequest $request,
49
        CodeFileSaver $codeFileSaver,
50
        CommandHydrator $commandHydrator
51
    ): ResponseInterface {
52
        $generator = $request->getGenerator();
53
        $command = $commandHydrator->hydrate($generator::getCommandClass(), $request->getData());
54
        $answers = $request->getAnswers();
55
        try {
56
            $files = $generator->generate($command);
57
        } catch (InvalidGeneratorCommandException $e) {
58
            return $this->createErrorResponse($e);
59
        }
60
        $params = [];
61
        $results = [];
62
        $params['hasError'] = !$codeFileSaver->save($command, $files, (array) $answers, $results);
63
        $params['results'] = $results;
64
        return $this->responseFactory->createResponse($params);
65
    }
66
67
    public function preview(
68
        GeneratorRequest $request,
69
        CommandHydrator $commandHydrator,
70
        #[Query('file')] ?string $file = null
71
    ): ResponseInterface {
72
        $generator = $request->getGenerator();
73
        $command = $commandHydrator->hydrate($generator::getCommandClass(), $request->getData());
74
75
        try {
76
            $files = $generator->generate($command);
77
        } catch (InvalidGeneratorCommandException $e) {
78
            return $this->createErrorResponse($e);
79
        }
80
        if ($file !== null) {
81
            foreach ($files as $generatedFile) {
82
                if ($generatedFile->getId() === $file) {
83
                    $content = $generatedFile->preview();
84
                    return $this->responseFactory->createResponse(
85
                        ['content' => $content ?: 'Preview is not available for this file type.']
86
                    );
87
                }
88
            }
89
            return $this->responseFactory->createResponse(
90
                ['message' => "Code file not found: $file"],
91
                Status::UNPROCESSABLE_ENTITY
92
            );
93
        }
94
        return $this->responseFactory->createResponse(['files' => $files, 'operations' => CodeFile::OPERATIONS_MAP]);
95
    }
96
97
    public function diff(
98
        GeneratorRequest $request,
99
        CommandHydrator $commandHydrator,
100
        #[Query('file')] string $file
101
    ): ResponseInterface {
102
        $generator = $request->getGenerator();
103
        $command = $commandHydrator->hydrate($generator::getCommandClass(), $request->getData());
104
105
        try {
106
            $files = $generator->generate($command);
107
        } catch (InvalidGeneratorCommandException $e) {
108
            return $this->createErrorResponse($e);
109
        }
110
111
        foreach ($files as $generatedFile) {
112
            if ($generatedFile->getId() === $file) {
113
                return $this->responseFactory->createResponse(['diff' => $generatedFile->diff()]);
114
            }
115
        }
116
        return $this->responseFactory->createResponse(
117
            ['message' => "Code file not found: $file"],
118
            Status::UNPROCESSABLE_ENTITY
119
        );
120
    }
121
122
    private function createErrorResponse(InvalidGeneratorCommandException $e): DataResponse
123
    {
124
        return $this->responseFactory->createResponse(
125
        // TODO: fix
126
            ['errors' => $e->getResult()->getErrorMessagesIndexedByAttribute()],
127
            Status::UNPROCESSABLE_ENTITY
128
        );
129
    }
130
}
131