Completed
Push — symfony-console ( bab453...575c8e )
by Arnaud
02:04
created

Command::initialize()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.8497
c 0
b 0
f 0
cc 6
nc 9
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\Filesystem\Filesystem;
17
use Symfony\Component\Yaml\Exception\ParseException;
18
use Symfony\Component\Yaml\Yaml;
19
20
class Command extends BaseCommand
21
{
22
    const CONFIG_FILE = 'config.yml';
23
24
    /**
25
     * @var Filesystem
26
     */
27
    protected $fs;
28
    /**
29
     * @var string
30
     */
31
    protected $path;
32
    /**
33
     * @var Builder
34
     */
35
    protected $builder;
36
    /**
37
     * @var ProgressBar
38
     */
39
    protected $progressBar = null;
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    protected function initialize(InputInterface $input, OutputInterface $output)
45
    {
46
        $this->fs = new Filesystem();
47
48
        if (!in_array($this->getName(), ['self-update'])) {
49
            $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...
50
            if (null === $this->getPath()) {
51
                $this->path = getcwd();
52
            }
53
            if (false === realpath($this->getPath())) {
54
                $message = sprintf('"%s" is not valid path.', $this->getPath());
55
56
                throw new \InvalidArgumentException($message);
57
            }
58
            $this->path = realpath($this->getPath());
59
            $this->path = str_replace(DIRECTORY_SEPARATOR, '/', $this->getPath());
60
61
            if (!in_array($this->getName(), ['new:site'])) {
62
                if (!file_exists($this->getPath().'/'.self::CONFIG_FILE)) {
63
                    $message = sprintf('Cecil could not find "%s" file in "%s"', self::CONFIG_FILE, $this->getPath());
64
65
                    throw new \InvalidArgumentException($message);
66
                }
67
            }
68
        }
69
70
        parent::initialize($input, $output);
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    protected function interact(InputInterface $input, OutputInterface $output)
77
    {
78
        parent::interact($input, $output);
79
    }
80
81
    /**
82
     * Return the working directory.
83
     *
84
     * @return string
85
     */
86
    public function getPath()
87
    {
88
        return $this->path;
89
    }
90
91
    /**
92
     * Create or return a Builder instance.
93
     *
94
     * @param OutputInterface $output
95
     * @param array           $config
96
     * @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...
97
     *
98
     * @return Builder
99
     */
100
    public function getBuilder(
101
        OutputInterface $output,
102
        array $config = ['debug' => false]
103
    ) {
104 View Code Duplication
        if (!file_exists($this->getPath().'/'.self::CONFIG_FILE)) {
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...
105
            throw new \Exception(sprintf('Config file not found in "%s"!', $this->getPath()));
106
        }
107
108
        try {
109
            $configFile = Yaml::parse(file_get_contents($this->getPath().'/'.self::CONFIG_FILE));
110
            $config = array_replace_recursive($configFile, $config);
111
            $this->builder = (new Builder($config, $this->messageCallback($output)))
112
                ->setSourceDir($this->getPath())
113
                ->setDestinationDir($this->getPath());
114
        } catch (ParseException $e) {
115
            throw new \Exception(sprintf('Config file parse error: %s', $e->getMessage()));
116
        } catch (\Exception $e) {
117
            throw new \Exception(sprintf($e->getMessage()));
118
        }
119
120
        return $this->builder;
121
    }
122
123
    /**
124
     * Create the Progress bar.
125
     *
126
     * @param OutputInterface $output
127
     * @param int             $start
128
     * @param int             $max
129
     *
130
     * @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...
131
     */
132
    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...
133
    {
134
        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...
135
            $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...
136
            $this->progressBar = new ProgressBar($output, $max);
137
            $this->progressBar->setOverwrite(true);
138
            $this->progressBar->setFormat(' %percent:3s%% [%bar%] %current%/%max%');
139
            $this->progressBar->setBarCharacter('#');
140
            $this->progressBar->setEmptyBarCharacter(' ');
141
            $this->progressBar->setProgressCharacter('#');
142
            $this->progressBar->setRedrawFrequency(1);
143
            $this->progressBar->start();
144
        }
145
    }
146
147
    /**
148
     * Return Progress Bar.
149
     *
150
     * @return ProgressBar
151
     */
152
    protected function getProgressBar()
153
    {
154
        return $this->progressBar;
155
    }
156
157
    /**
158
     * Print the Progress Bar.
159
     *
160
     * @param OutputInterface $output
161
     * @param int             $itemsCount
162
     * @param int             $itemsMax
163
     * @param string          $message
164
     */
165
    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...
166
    {
167
        $this->createProgressBar($output, 0, $itemsMax);
168
        $this->getProgressBar()->clear();
169
        $this->getProgressBar()->setProgress($itemsCount);
170
        $this->getProgressBar()->display();
171
        if ($itemsCount == $itemsMax) {
172
            $this->getProgressBar()->finish();
173
            $output->writeln('');
174
        }
175
    }
176
177
    /**
178
     * Custom message callback function.
179
     *
180
     * @param OutputInterface $output
181
     */
182
    public function messageCallback(OutputInterface $output)
183
    {
184
        return function ($code, $message = '', $itemsCount = 0, $itemsMax = 0) use ($output) {
185
            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...
186
                return;
187
            } else {
188
                if (strpos($code, '_PROGRESS') !== false) {
189
                    if ($output->isVerbose()) {
190
                        if ($itemsCount > 0) {
191
                            $output->writeln(sprintf(' (%u/%u) %s', $itemsCount, $itemsMax, $message));
192
193
                            return;
194
                        }
195
                        $output->writeln("<info>$message</info>");
196 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...
197
                        if (isset($itemsCount) && $itemsMax > 0) {
198
                            $this->printProgressBar($output, $itemsCount, $itemsMax, $message);
199
                        } else {
200
                            $output->writeln("$message");
201
                        }
202
                    }
203
                } elseif (strpos($code, '_ERROR') !== false) {
204
                    $output->writeln("<error>$message</error>");
205
                } elseif ($code == 'TIME') {
206
                    $output->writeln("<comment>$message</comment>");
207
                } else {
208
                    $output->writeln("<info>$message</info>");
209
                }
210
            }
211
        };
212
    }
213
}
214