Passed
Pull Request — master (#58)
by Dmitriy
13:13 queued 10:22
created

CodeFileWriter::write()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 27
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 20
c 0
b 0
f 0
dl 0
loc 27
ccs 0
cts 19
cp 0
rs 8.9777
cc 6
nc 6
nop 4
crap 42
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Gii;
6
7
use Exception;
8
use ReflectionException;
9
use Yiisoft\Yii\Gii\Exception\InvalidConfigException;
10
use Yiisoft\Yii\Gii\Generator\AbstractGeneratorCommand;
11
12
final class CodeFileWriter
13
{
14
    /**
15
     * Saves the generated code into files.
16
     *
17
     * @param CodeFile[] $files the code files to be saved
18
     * @param string[] $results this parameter receives a value from this method indicating the log messages
19
     * generated while saving the code files.
20
     *
21
     * @throws InvalidConfigException
22
     * @throws ReflectionException
23
     *
24
     * @return bool whether files are successfully saved without any error.
25
     */
26
    public function write(AbstractGeneratorCommand $command, array $files, array $answers, array &$results): bool
27
    {
28
        $results = ['Generating code using template "' . $command->getTemplate() . '"...'];
29
        $hasError = false;
30
        foreach ($files as $file) {
31
            $relativePath = $file->getRelativePath();
32
            if (!empty($answers[$file->getId()]) && $file->getOperation() !== CodeFile::OP_SKIP) {
33
                try {
34
                    $file->save();
35
                    $results[] = $file->getOperation() === CodeFile::OP_CREATE
36
                        ? " generated  $relativePath"
37
                        : " overwrote  $relativePath";
38
                } catch (Exception $e) {
39
                    $hasError = true;
40
                    $results[] = sprintf(
41
                        "   generating %s\n    - <span class=\"error\">%s</span>",
42
                        $relativePath,
43
                        $e->getMessage()
44
                    );
45
                }
46
            } else {
47
                $results[] = "   skipped    $relativePath";
48
            }
49
        }
50
        $results[] = 'done!';
51
52
        return !$hasError;
53
    }
54
}
55