Completed
Push — symfony-console ( 6ee300...dd10c4 )
by Arnaud
06:09 queued 04:12
created

Command::getProgressBar()   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 0
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\Yaml\Exception\ParseException;
11
use Symfony\Component\Yaml\Yaml;
12
13
class Command extends BaseCommand
14
{
15
    const CONFIG_FILE = 'config.yml';
16
17
    /**
18
     * @var string
19
     */
20
    protected $path;
21
    /**
22
     * @var Builder
23
     */
24
    protected $builder;
25
    /**
26
     * @var ProgressBar
27
     */
28
    protected $progressBar = null;
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    protected function initialize(InputInterface $input, OutputInterface $output)
34
    {
35
        $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...
36
        $this->path = realpath($this->path);
37
        $this->path = str_replace(DIRECTORY_SEPARATOR, '/', $this->path);
38
39
        parent::initialize($input, $output);
40
    }
41
42
    /**
43
     * {@inheritDoc}
44
     */
45
    protected function interact(InputInterface $input, OutputInterface $output)
46
    {
47
        parent::interact($input, $output);
48
    }
49
50
    /**
51
     * @return string
52
     */
53
    public function getPath()
54
    {
55
        return $this->path;
56
    }
57
58
    /**
59
     * @param OutputInterface $output
60
     * @param array           $config
61
     * @param array           $options
62
     *
63
     * @return Builder
64
     */
65 View Code Duplication
    public function getBuilder(
66
        OutputInterface $output,
67
        array $config = ['debug' => false],
68
        array $options = ['verbosity' => Builder::VERBOSITY_NORMAL]
69
    ) {
70
        if (!file_exists($this->getPath().'/'.self::CONFIG_FILE)) {
71
            throw new \Exception(sprintf('Config file not found in "%s"!', $this->getPath()));
72
        }
73
        // verbosity: verbose
74
        if ($options['verbosity'] == Builder::VERBOSITY_VERBOSE) {
75
            $this->verbose = true;
0 ignored issues
show
Bug introduced by
The property verbose 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...
76
        }
77
        // verbosity: quiet
78
        if ($options['verbosity'] == Builder::VERBOSITY_QUIET) {
79
            $this->quiet = true;
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...
80
        }
81
82
        try {
83
            $configFile = Yaml::parse(file_get_contents($this->getPath().'/'.self::CONFIG_FILE));
84
            $config = array_replace_recursive($configFile, $config);
85
            $this->builder = (new Builder($config, $this->messageCallback($output)))
86
                ->setSourceDir($this->getPath())
87
                ->setDestinationDir($this->getPath());
88
        } catch (ParseException $e) {
89
            throw new \Exception(sprintf('Config file parse error: %s', $e->getMessage()));
90
        } catch (\Exception $e) {
91
            throw new \Exception(sprintf($e->getMessage()));
92
        }
93
94
        return $this->builder;
95
    }
96
97
    /**
98
     * @param OutputInterface $output
99
     * @param int             $start
100
     * @param int             $max
101
     *
102
     * @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...
103
     */
104
    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...
105
    {
106
        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...
107
            $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...
108
            $this->progressBar = new ProgressBar($output, $max);
109
            $this->progressBar->start();
110
        }
111
    }
112
113
    /**
114
     * @return ProgressBar
115
     */
116
    protected function getProgressBar()
117
    {
118
        return $this->progressBar;
119
    }
120
121
    /**
122
     * Print progress bar.
123
     *
124
     * @param OutputInterface $output
125
     * @param int             $itemsCount
126
     * @param int             $itemsMax
127
     * @param string          $message
128
     */
129
    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...
130
    {
131
        $this->createProgressBar($output, 0, $itemsMax);
132
        $this->getProgressBar()->clear();
133
        $this->getProgressBar()->setProgress($itemsCount);
134
        $this->getProgressBar()->display();
135
        if ($itemsCount == $itemsMax) {
136
            $this->getProgressBar()->finish();
137
            $output->writeln('');
138
        }
139
    }
140
141
    /**
142
     * Custom message callback function.
143
     *
144
     * @param OutputInterface $output
145
     */
146
    public function messageCallback(OutputInterface $output)
147
    {
148
        return function ($code, $message = '', $itemsCount = 0, $itemsMax = 0) use ($output) {
149
            if ($this->quiet) {
150
                return;
151
            } else {
152
                if (strpos($code, '_PROGRESS') !== false) {
153
                    if ($this->verbose) {
154
                        if ($itemsCount > 0) {
155
                            $output->writeln(sprintf('(%u/%u) %s', $itemsCount, $itemsMax, $message));
156
157
                            return;
158
                        }
159
                        $output->writeln("<info>$message</info>");
160 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...
161
                        if (isset($itemsCount) && $itemsMax > 0) {
162
                            $this->printProgressBar($output, $itemsCount, $itemsMax, $message);
163
                        } else {
164
                            $output->writeln("$message");
165
                        }
166
                    }
167
                } elseif (strpos($code, '_ERROR') !== false) {
168
                    $output->writeln("<error>$message</error>");
169
                } elseif ($code == 'TIME') {
170
                    $output->writeln("<comment>$message</comment>");
171
                } else {
172
                    $output->writeln("<info>$message</info>");
173
                }
174
            }
175
        };
176
    }
177
}
178