Completed
Push — symfony-console ( 6549b1...5eb48f )
by Arnaud
02:30
created

Command::getBuilder()   A

Complexity

Conditions 5
Paths 28

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 9.1128
c 0
b 0
f 0
cc 5
nc 28
nop 3
1
<?php
2
3
namespace Cecil\Command;
4
5
use Cecil\Builder;
6
use Symfony\Component\Console\Command\Command as BaseCommand;
7
use Symfony\Component\Console\Helper\ProgressBar;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\Filesystem\Filesystem;
11
use Symfony\Component\Yaml\Exception\ParseException;
12
use Symfony\Component\Yaml\Yaml;
13
14
class Command extends BaseCommand
15
{
16
    const CONFIG_FILE = 'config.yml';
17
18
    /**
19
     * @var Filesystem
20
     */
21
    protected $fs;
22
    /**
23
     * @var string
24
     */
25
    protected $path;
26
    /**
27
     * @var Builder
28
     */
29
    protected $builder;
30
    /**
31
     * @var ProgressBar
32
     */
33
    protected $progressBar = null;
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    protected function initialize(InputInterface $input, OutputInterface $output)
39
    {
40
        $this->fs = new Filesystem();
41
        $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...
42
43
        if (null === $this->getPath()) {
44
            $this->path = getcwd();
45
        }
46
        if (false === realpath($this->getPath())) {
47
            $message = sprintf('"%s" is not valid path.', $this->getPath());
48
            throw new \InvalidArgumentException($message);
49
50
        }
51
        $this->path = realpath($this->getPath());
52
        $this->path = str_replace(DIRECTORY_SEPARATOR, '/', $this->getPath());
53
        if (!file_exists($this->getPath() . '/' . self::CONFIG_FILE)) {
54
            $message = sprintf('Cecil could not find "%s" file in "%s"', self::CONFIG_FILE, $this->getPath());
55
            throw new \InvalidArgumentException($message);
56
        }
57
58
        parent::initialize($input, $output);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    protected function interact(InputInterface $input, OutputInterface $output)
65
    {
66
        parent::interact($input, $output);
67
    }
68
69
    /**
70
     * @return string
71
     */
72
    public function getPath()
73
    {
74
        return $this->path;
75
    }
76
77
    /**
78
     * @param OutputInterface $output
79
     * @param array           $config
80
     * @param array           $options
81
     *
82
     * @return Builder
83
     */
84
    public function getBuilder(
85
        OutputInterface $output,
86
        array $config = ['debug' => false],
87
        array $options = ['verbosity' => Builder::VERBOSITY_NORMAL]
88
    ) {
89
        /*if (!file_exists($this->getPath().'/'.self::CONFIG_FILE)) {
90
            throw new \Exception(sprintf('Config file not found in "%s"!', $this->getPath()));
91
        }*/
92
        // verbosity: verbose
93
        if ($options['verbosity'] == Builder::VERBOSITY_VERBOSE) {
94
            //$this->verbose = true;
95
        }
96
        // verbosity: quiet
97
        if ($options['verbosity'] == Builder::VERBOSITY_QUIET) {
98
            //$this->quiet = true;
99
        }
100
101
        try {
102
            $configFile = Yaml::parse(file_get_contents($this->getPath().'/'.self::CONFIG_FILE));
103
            $config = array_replace_recursive($configFile, $config);
104
            $this->builder = (new Builder($config, $this->messageCallback($output)))
105
                ->setSourceDir($this->getPath())
106
                ->setDestinationDir($this->getPath());
107
        } catch (ParseException $e) {
108
            throw new \Exception(sprintf('Config file parse error: %s', $e->getMessage()));
109
        } catch (\Exception $e) {
110
            throw new \Exception(sprintf($e->getMessage()));
111
        }
112
113
        return $this->builder;
114
    }
115
116
    /**
117
     * @param OutputInterface $output
118
     * @param int             $start
119
     * @param int             $max
120
     *
121
     * @return ProgressBar
0 ignored issues
show
Documentation introduced by
Should the return type not be ProgressBar|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
122
     */
123
    protected function createProgressBar(OutputInterface $output, $start, $max)
0 ignored issues
show
Unused Code introduced by
The parameter $start is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
124
    {
125
        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...
126
            $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...
127
            $this->progressBar = new ProgressBar($output, $max);
128
            $this->progressBar->setOverwrite(true);
129
            $this->progressBar->setFormat(' %percent:3s%% [%bar%] %current%/%max%');
130
            $this->progressBar->setBarCharacter('#');
131
            $this->progressBar->setEmptyBarCharacter(' ');
132
            $this->progressBar->setProgressCharacter('#');
133
            $this->progressBar->setRedrawFrequency(1);
134
            $this->progressBar->start();
135
        }
136
    }
137
138
    /**
139
     * @return ProgressBar
140
     */
141
    protected function getProgressBar()
142
    {
143
        return $this->progressBar;
144
    }
145
146
    /**
147
     * Print progress bar.
148
     *
149
     * @param OutputInterface $output
150
     * @param int             $itemsCount
151
     * @param int             $itemsMax
152
     * @param string          $message
153
     */
154
    protected function printProgressBar(OutputInterface $output, $itemsCount, $itemsMax, $message)
0 ignored issues
show
Unused Code introduced by
The parameter $message is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
155
    {
156
        $this->createProgressBar($output, 0, $itemsMax);
157
        $this->getProgressBar()->clear();
158
        $this->getProgressBar()->setProgress($itemsCount);
159
        $this->getProgressBar()->display();
160
        if ($itemsCount == $itemsMax) {
161
            $this->getProgressBar()->finish();
162
            $output->writeln('');
163
        }
164
    }
165
166
    /**
167
     * Custom message callback function.
168
     *
169
     * @param OutputInterface $output
170
     */
171
    public function messageCallback(OutputInterface $output)
172
    {
173
        return function ($code, $message = '', $itemsCount = 0, $itemsMax = 0) use ($output) {
174
            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...
175
                return;
176
            } else {
177
                if (strpos($code, '_PROGRESS') !== false) {
178
                    if ($output->isVerbose()) {
179
                        if ($itemsCount > 0) {
180
                            $output->writeln(sprintf(' (%u/%u) %s', $itemsCount, $itemsMax, $message));
181
182
                            return;
183
                        }
184
                        $output->writeln("<info>$message</info>");
185 View Code Duplication
                    } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186
                        if (isset($itemsCount) && $itemsMax > 0) {
187
                            $this->printProgressBar($output, $itemsCount, $itemsMax, $message);
188
                        } else {
189
                            $output->writeln("$message");
190
                        }
191
                    }
192
                } elseif (strpos($code, '_ERROR') !== false) {
193
                    $output->writeln("<error>$message</error>");
194
                } elseif ($code == 'TIME') {
195
                    $output->writeln("<comment>$message</comment>");
196
                } else {
197
                    $output->writeln("<info>$message</info>");
198
                }
199
            }
200
        };
201
    }
202
}
203