Completed
Pull Request — master (#148)
by
unknown
03:13
created

Application::doRun()   C

Complexity

Conditions 7
Paths 32

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 3 Features 0
Metric Value
c 5
b 3
f 0
dl 0
loc 27
rs 6.7272
cc 7
eloc 14
nc 32
nop 2
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\Util\ErrorHandler;
16
use Symfony\Component\Console\Application as BaseApplication;
17
use Symfony\Component\Console\Input\ArrayInput;
18
use Symfony\Component\Console\Input\InputInterface;
19
use Symfony\Component\Console\Input\InputOption;
20
use Symfony\Component\Console\Output\OutputInterface;
21
22
/**
23
 * The console application that handles the commands
24
 * Inspired by Composer https://github.com/composer/composer
25
 */
26
class Application extends BaseApplication
0 ignored issues
show
Complexity introduced by
The class Application has a coupling between objects value of 19. Consider to reduce the number of dependencies under 13.
Loading history...
27
{
28
    /**
29
     * @var Bowerphp
30
     */
31
    protected $bowerphp;
32
33
    private static $logo = '    ____                                __
34
   / __ )____ _      _____  _________  / /_  ____
35
  / __  / __ \ | /| / / _ \/ ___/ __ \/ __ \/ __ \
36
 / /_/ / /_/ / |/ |/ /  __/ /  / /_/ / / / / /_/ /
37
/_____/\____/|__/|__/\___/_/  / .___/_/ /_/ .___/
38
                             /_/         /_/
39
';
40
41
    /**
42
     * Constructor
43
     */
44
    public function __construct()
45
    {
46
        ErrorHandler::register();
47
        parent::__construct('Bowerphp', '0.5 Powered by BeeLab (bee-lab.net)');
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function doRun(InputInterface $input, OutputInterface $output)
54
    {
55
        if ($input->hasParameterOption('--profile')) {
56
            $startTime = microtime(true);
57
        }
58
        
59
        if ($input->hasParameterOption('--token')&&($token = $input->getParameterOption(['--token', '-t']))) {
60
            putenv("BOWERPHP_TOKEN=$token");
61
        }
62
63
        if ($newWorkDir = $this->getNewWorkingDir($input)) {
64
            $oldWorkingDir = getcwd();
65
            chdir($newWorkDir);
66
        }
67
68
        $result = $this->symfonyDoRun($input, $output);
69
70
        if (isset($oldWorkingDir)) {
71
            chdir($oldWorkingDir);
72
        }
73
74
        if (isset($startTime)) {
75
            $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');
76
        }
77
78
        return $result;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function getHelp()
85
    {
86
        return self::$logo . parent::getHelp();
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    protected function getDefaultCommands()
93
    {
94
        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...
95
            new Command\HelpCommand(),
96
            new Command\CommandListCommand(),
97
            new Command\HomeCommand(),
98
            new Command\InfoCommand(),
99
            new Command\InitCommand(),
100
            new Command\InstallCommand(),
101
            new Command\ListCommand(),
102
            new Command\LookupCommand(),
103
            new Command\SearchCommand(),
104
            new Command\UpdateCommand(),
105
            new Command\UninstallCommand(),
106
        ];
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112
    protected function getDefaultInputDefinition()
113
    {
114
        $definition = parent::getDefaultInputDefinition();
115
        $definition->addOption(new InputOption('--token', '-t', InputOption::VALUE_OPTIONAL, 'Pass github token as parameter'));
116
        $definition->addOption(new InputOption('--profile', null, InputOption::VALUE_NONE, 'Display timing and memory usage information'));
117
        $definition->addOption(new InputOption('--working-dir', '-d', InputOption::VALUE_REQUIRED, 'If specified, use the given directory as working directory.'));
118
119
        return $definition;
120
    }
121
122
    /**
123
     * {@inheritdoc}
124
     */
125
    protected function getDefaultHelperSet()
126
    {
127
        $helperSet = parent::getDefaultHelperSet();
128
        $helperSet->set(new \Bowerphp\Command\Helper\QuestionHelper());
129
130
        return $helperSet;
131
    }
132
133
    /**
134
     * @param  InputInterface    $input
135
     * @throws \RuntimeException
136
     */
137
    private function getNewWorkingDir(InputInterface $input)
138
    {
139
        $workingDir = $input->getParameterOption(['--working-dir', '-d']);
140
        if (false !== $workingDir && !is_dir($workingDir)) {
141
            throw new \RuntimeException('Invalid working directory specified.');
142
        }
143
144
        return $workingDir;
145
    }
146
147
    /**
148
     * Copy of original Symfony doRun, to allow a default command
149
     *
150
     * @param InputInterface  $input   An Input instance
151
     * @param OutputInterface $output  An Output instance
152
     * @param string          $default Default command to execute
153
     *
154
     * @return int 0 if everything went fine, or an error code
155
     * @codeCoverageIgnore
156
     */
157
    private function symfonyDoRun(InputInterface $input, OutputInterface $output, $default = 'list-commands')
158
    {
159
        if (true === $input->hasParameterOption(['--version', '-V'])) {
160
            $output->writeln($this->getLongVersion());
161
162
            return 0;
163
        }
164
        
165
        $name = $this->getCommandName($input);
166
167
        if (true === $input->hasParameterOption(['--help', '-h'])) {
168
            if (!$name) {
169
                $name = 'help';
170
                $input = new ArrayInput(['command' => 'help']);
171
            } else {
172
                $this->wantHelps = true;
173
            }
174
        }
175
176
        if (!$name) {
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