Application::getDefaultHelperSet()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of Bowerphp.
5
 *
6
 * (c) Massimiliano Arione <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Bowerphp\Console;
13
14
use Bowerphp\Command;
15
use Bowerphp\Command\Helper\QuestionHelper;
16
use Bowerphp\Util\ErrorHandler;
17
use PackageVersions\Versions;
18
use Symfony\Component\Console\Application as BaseApplication;
19
use Symfony\Component\Console\Input\ArrayInput;
20
use Symfony\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Input\InputOption;
22
use Symfony\Component\Console\Output\OutputInterface;
23
24
/**
25
 * The console application that handles the commands
26
 * Inspired by Composer https://github.com/composer/composer
27
 */
28
class Application extends BaseApplication
0 ignored issues
show
Complexity introduced by
The class Application has a coupling between objects value of 20. Consider to reduce the number of dependencies under 13.
Loading history...
29
{
30
    /**
31
     * @var \Bowerphp\Bowerphp
32
     */
33
    protected $bowerphp;
34
35
    private static $logo = '    ____                                __
36
   / __ )____ _      _____  _________  / /_  ____
37
  / __  / __ \ | /| / / _ \/ ___/ __ \/ __ \/ __ \
38
 / /_/ / /_/ / |/ |/ /  __/ /  / /_/ / / / / /_/ /
39
/_____/\____/|__/|__/\___/_/  / .___/_/ /_/ .___/
40
                             /_/         /_/
41
';
42
43
    /**
44
     * Constructor
45
     */
46
    public function __construct()
47
    {
48
        ErrorHandler::register();
49
        $version = Versions::getVersion('beelab/bowerphp');
50
        parent::__construct('Bowerphp', $version . ' Powered by BeeLab (github.com/bee-lab)');
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function doRun(InputInterface $input, OutputInterface $output)
57
    {
58
        if ($input->hasParameterOption('--profile')) {
59
            $startTime = microtime(true);
60
        }
61
62
        if ($newWorkDir = $this->getNewWorkingDir($input)) {
63
            $oldWorkingDir = getcwd();
64
            chdir($newWorkDir);
65
        }
66
67
        $result = $this->symfonyDoRun($input, $output);
68
69
        if (isset($oldWorkingDir)) {
70
            chdir($oldWorkingDir);
71
        }
72
73
        if (isset($startTime)) {
74
            $output->writeln('<info>Memory usage: ' . round(memory_get_usage() / 1024 / 1024, 2) . 'MB (peak: ' . round(memory_get_peak_usage() / 1024 / 1024, 2) . 'MB), time: ' . round(microtime(true) - $startTime, 2) . 's');
75
        }
76
77
        return $result;
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    public function getHelp()
84
    {
85
        return self::$logo . parent::getHelp();
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    protected function getDefaultCommands()
92
    {
93
        return [
0 ignored issues
show
Best Practice introduced by
The expression return array(new \Bowerp...nd\UninstallCommand()); seems to be an array, but some of its elements' types (Bowerphp\Command\HomeCom...ommand\UninstallCommand) are incompatible with the return type of the parent method Symfony\Component\Consol...ion::getDefaultCommands of type array<Symfony\Component\...le\Command\ListCommand>.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
94
            new Command\HelpCommand(),
95
            new Command\CommandListCommand(),
96
            new Command\HomeCommand(),
97
            new Command\InfoCommand(),
98
            new Command\InitCommand(),
99
            new Command\InstallCommand(),
100
            new Command\ListCommand(),
101
            new Command\LookupCommand(),
102
            new Command\SearchCommand(),
103
            new Command\UpdateCommand(),
104
            new Command\UninstallCommand(),
105
        ];
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    protected function getDefaultInputDefinition()
112
    {
113
        $definition = parent::getDefaultInputDefinition();
114
        $definition->addOption(new InputOption('--profile', null, InputOption::VALUE_NONE, 'Display timing and memory usage information'));
115
        $definition->addOption(new InputOption('--working-dir', '-d', InputOption::VALUE_REQUIRED, 'If specified, use the given directory as working directory.'));
116
117
        return $definition;
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    protected function getDefaultHelperSet()
124
    {
125
        $helperSet = parent::getDefaultHelperSet();
126
        $helperSet->set(new QuestionHelper());
127
128
        return $helperSet;
129
    }
130
131
    /**
132
     * @param  InputInterface    $input
133
     * @return string
134
     * @throws \RuntimeException
135
     */
136
    private function getNewWorkingDir(InputInterface $input)
137
    {
138
        $workingDir = $input->getParameterOption(['--working-dir', '-d']);
139
        if (false !== $workingDir && !is_dir($workingDir)) {
140
            throw new \RuntimeException('Invalid working directory specified.');
141
        }
142
143
        return $workingDir;
144
    }
145
146
    /**
147
     * Copy of original Symfony doRun, to allow a default command
148
     *
149
     * @param InputInterface  $input   An Input instance
150
     * @param OutputInterface $output  An Output instance
151
     * @param string          $default Default command to execute
152
     *
153
     * @return int 0 if everything went fine, or an error code
154
     * @codeCoverageIgnore
155
     */
156
    private function symfonyDoRun(InputInterface $input, OutputInterface $output, $default = 'list-commands')
157
    {
158
        if (true === $input->hasParameterOption(['--version', '-V'])) {
159
            $output->writeln($this->getLongVersion());
160
161
            return 0;
162
        }
163
164
        $name = $this->getCommandName($input);
165
166
        if (true === $input->hasParameterOption(['--help', '-h'])) {
167
            if (!$name) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $name of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
168
                $name = 'help';
169
                $input = new ArrayInput(['command' => 'help']);
170
            } else {
171
                // TODO $wantHelps is private in parent class
172
                $this->wantHelps = true;
173
            }
174
        }
175
176
        if (!$name) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $name of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
177
            $name = $default;
178
            $input = new ArrayInput(['command' => $default]);
179
        }
180
181
        // the command name MUST be the first element of the input
182
        $command = $this->find($name);
183
184
        $this->runningCommand = $command;
185
        $exitCode = $this->doRunCommand($command, $input, $output);
186
        $this->runningCommand = null;
187
188
        return $exitCode;
189
    }
190
}
191