Passed
Push — master ( 57a6ca...7ee914 )
by Aleksei
02:24
created

SchemaPhpCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Command\Schema;
6
7
use Symfony\Component\Console\Command\Command;
8
use Symfony\Component\Console\Input\InputArgument;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Yiisoft\Aliases\Aliases;
12
use Yiisoft\Yii\Console\ExitCode;
13
use Yiisoft\Yii\Cycle\Command\CycleDependencyProxy;
14
use Yiisoft\Yii\Cycle\Schema\Converter\SchemaToPHP;
15
16
final class SchemaPhpCommand extends Command
17
{
18
    protected static $defaultName = 'cycle/schema/php';
19
20
    private CycleDependencyProxy $promise;
21
    private Aliases $aliases;
22
23
    public function __construct(Aliases $aliases, CycleDependencyProxy $promise)
24
    {
25
        $this->aliases = $aliases;
26
        $this->promise = $promise;
27
        parent::__construct();
28
    }
29
30
    public function configure(): void
31
    {
32
        $this->setDescription('Save current schema in a PHP file')
33
             ->addArgument('file', InputArgument::OPTIONAL, 'file')
34
        ;
35
    }
36
37
    protected function execute(InputInterface $input, OutputInterface $output): int
38
    {
39
        /** @var string|null $file */
40
        $file = $input->getArgument('file');
41
42
        $content = (new SchemaToPHP($this->promise->getSchema()))->convert();
43
        if ($file !== null) {
44
            $file = $this->aliases->get($file);
45
            $output->writeln("Destination: <fg=cyan>{$file}</>");
46
            // Dir exists
47
            $dir = dirname($file);
48
            if (!is_dir($dir)) {
49
                throw new \RuntimeException("Directory {$dir} not found");
50
            }
51
            if (file_put_contents($file, $content) === false) {
52
                return ExitCode::UNSPECIFIED_ERROR;
53
            }
54
        } else {
55
            echo $content;
56
        }
57
        return ExitCode::OK;
58
    }
59
}
60