Completed
Push — symfony-console ( a82731...c3b3e5 )
by Arnaud
01:57
created

Command::interact()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
/*
3
 * Copyright (c) Arnaud Ligny <[email protected]>
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Cecil\Command;
10
11
use Cecil\Builder;
12
use Symfony\Component\Console\Command\Command as BaseCommand;
13
use Symfony\Component\Console\Helper\ProgressBar;
14
use Symfony\Component\Console\Input\InputInterface;
15
use Symfony\Component\Console\Output\OutputInterface;
16
use Symfony\Component\Console\Question\ConfirmationQuestion;
17
use Symfony\Component\Filesystem\Filesystem;
18
use Symfony\Component\Yaml\Exception\ParseException;
19
use Symfony\Component\Yaml\Yaml;
20
21
class Command extends BaseCommand
22
{
23
    const CONFIG_FILE = 'config.yml';
24
25
    /**
26
     * @var Filesystem
27
     */
28
    protected $fs;
29
    /**
30
     * @var string
31
     */
32
    protected $path;
33
    /**
34
     * @var Builder
35
     */
36
    protected $builder;
37
    /**
38
     * @var ProgressBar
39
     */
40
    protected $progressBar = null;
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    protected function initialize(InputInterface $input, OutputInterface $output)
46
    {
47
        $this->fs = new Filesystem();
48
49
        if (!in_array($this->getName(), ['self-update'])) {
50
            $this->path = $input->getArgument('path');
0 ignored issues
show
Documentation Bug introduced by
It seems like $input->getArgument('path') can also be of type array<integer,string>. However, the property $path is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
51
            if (null === $this->getPath()) {
52
                $this->path = getcwd();
53
            }
54
            if (false === realpath($this->getPath())) {
55
                if (!in_array($this->getName(), ['new:site'])) {
56
                    $message = sprintf('"%s" is not valid path.', $this->getPath());
57
58
                    throw new \InvalidArgumentException($message);
59
                }
60
                $helper = $this->getHelper('question');
61
                $question = new ConfirmationQuestion(sprintf('The provided <path> "%s" doesn\'t exist. Do you want to create it? [y/n]', $this->getpath()), false);
62
                if (!$helper->ask($input, $output, $question)) {
63
                    return;
64
                }
65
66
                $this->fs->mkdir($this->getPath());
67
            }
68
            $this->path = realpath($this->getPath());
69
            $this->path = str_replace(DIRECTORY_SEPARATOR, '/', $this->getPath());
70
71
            if (!in_array($this->getName(), ['new:site'])) {
72
                if (!file_exists($this->getPath().'/'.self::CONFIG_FILE)) {
73
                    $message = sprintf('Cecil could not find "%s" file in "%s"', self::CONFIG_FILE, $this->getPath());
74
75
                    throw new \InvalidArgumentException($message);
76
                }
77
            }
78
        }
79
80
        parent::initialize($input, $output);
81
    }
82
83
    /**
84
     * Return the working directory.
85
     *
86
     * @return string|null
87
     */
88
    public function getPath(): ?string
89
    {
90
        return $this->path;
91
    }
92
93
    /**
94
     * Create or return a Builder instance.
95
     *
96
     * @param OutputInterface $output
97
     * @param array           $config
98
     * @param array           $options
0 ignored issues
show
Bug introduced by
There is no parameter named $options. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
99
     *
100
     * @return Builder
101
     */
102
    public function getBuilder(
103
        OutputInterface $output,
104
        array $config = ['debug' => false]
105
    ): Builder {
106
        if (!file_exists($this->getPath().'/'.self::CONFIG_FILE)) {
107
            throw new \Exception(sprintf('Config file not found in "%s"!', $this->getPath()));
108
        }
109
110
        try {
111
            $configFile = Yaml::parse(file_get_contents($this->getPath().'/'.self::CONFIG_FILE));
112
            $config = array_replace_recursive($configFile, $config);
113
            $this->builder = (new Builder($config, $this->messageCallback($output)))
114
                ->setSourceDir($this->getPath())
115
                ->setDestinationDir($this->getPath());
116
        } catch (ParseException $e) {
117
            throw new \Exception(sprintf('Config file parse error: %s', $e->getMessage()));
118
        } catch (\Exception $e) {
119
            throw new \Exception(sprintf($e->getMessage()));
120
        }
121
122
        return $this->builder;
123
    }
124
125
    /**
126
     * Create the Progress bar.
127
     *
128
     * @param OutputInterface $output
129
     * @param int             $max
130
     */
131
    protected function createProgressBar(OutputInterface $output, $max)
132
    {
133
        if ($this->progressBar === null || $max != $this->progressBarMax) {
0 ignored issues
show
Bug introduced by
The property progressBarMax does not seem to exist. Did you mean progressBar?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
134
            $this->progressBarMax = $max;
0 ignored issues
show
Bug introduced by
The property progressBarMax does not seem to exist. Did you mean progressBar?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
135
            $this->progressBar = new ProgressBar($output, $max);
136
            $this->progressBar->setOverwrite(true);
137
            $this->progressBar->setFormat(' %percent:3s%% [%bar%] %current%/%max%');
138
            $this->progressBar->setBarCharacter('#');
139
            $this->progressBar->setEmptyBarCharacter(' ');
140
            $this->progressBar->setProgressCharacter('#');
141
            $this->progressBar->setRedrawFrequency(1);
142
            $this->progressBar->start();
143
        }
144
    }
145
146
    /**
147
     * Return Progress Bar.
148
     *
149
     * @return ProgressBar
150
     */
151
    protected function getProgressBar()
152
    {
153
        return $this->progressBar;
154
    }
155
156
    /**
157
     * Print the Progress Bar.
158
     *
159
     * @param OutputInterface $output
160
     * @param int             $itemsCount
161
     * @param int             $itemsMax
162
     */
163
    protected function printProgressBar(OutputInterface $output, $itemsCount, $itemsMax)
164
    {
165
        $this->createProgressBar($output, $itemsMax);
166
        $this->getProgressBar()->clear();
167
        $this->getProgressBar()->setProgress($itemsCount);
168
        $this->getProgressBar()->display();
169
        if ($itemsCount == $itemsMax) {
170
            $this->getProgressBar()->finish();
171
            $output->writeln('');
172
        }
173
    }
174
175
    /**
176
     * Custom message callback function.
177
     *
178
     * @param OutputInterface $output
179
     */
180
    public function messageCallback(OutputInterface $output)
181
    {
182
        return function ($code, $message = '', $itemsCount = 0, $itemsMax = 0) use ($output) {
183
            if ($this->quiet) {
0 ignored issues
show
Bug introduced by
The property quiet does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
184
                return;
185
            } else {
186
                if (strpos($code, '_PROGRESS') !== false) {
187
                    if ($output->isVerbose()) {
188
                        if ($itemsCount > 0) {
189
                            $output->writeln(sprintf(' (%u/%u) %s', $itemsCount, $itemsMax, $message));
190
191
                            return;
192
                        }
193
                        $output->writeln("<info>$message</info>");
194
                    } else {
195
                        if (isset($itemsCount) && $itemsMax > 0) {
196
                            $this->printProgressBar($output, $itemsCount, $itemsMax);
197
                        } else {
198
                            $output->writeln("$message");
199
                        }
200
                    }
201
                } elseif (strpos($code, '_ERROR') !== false) {
202
                    $output->writeln("<error>$message</error>");
203
                } elseif ($code == 'TIME') {
204
                    $output->writeln("<comment>$message</comment>");
205
                } else {
206
                    $output->writeln("<info>$message</info>");
207
                }
208
            }
209
        };
210
    }
211
}
212