Passed
Push — master ( 62679a...2b0c72 )
by Gerard van
07:11
created

Application::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
/**
3
 * @author Gerard van Helden <[email protected]>
4
 * @copyright Zicht Online <http://zicht.nl>
5
 */
6
namespace Zicht\Tool;
7
8
use Symfony\Component\Console\Application as BaseApplication;
9
use Symfony\Component\Console\Input\ArrayInput;
10
use Symfony\Component\Console\Input\InputArgument;
11
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Input\InputInterface;
13
use Symfony\Component\Console\Input\InputDefinition;
14
use Symfony\Component\Console\Output\OutputInterface;
15
use Zicht\Version\Version;
16
use Zicht\Tool\Command as Cmd;
17
use Zicht\Tool\Configuration\ConfigurationLoader;
18
use Zicht\Tool\Container\Container;
19
use Zicht\Tool\Container\ContainerCompiler;
20
use Zicht\Tool\Container\VerboseException;
21
22
/**
23
 * Z CLI Application
24
 */
25
class Application extends BaseApplication
26
{
27
    public static $HEADER = <<<EOSTR
28
.------------.
29
|    ____    |
30
|   |__  |   |
31
|     / /    |
32
|    / /_    |
33
|   |____|   |
34
|   ------   |
35
'------------'
36
EOSTR;
37
38
    protected $container = null;
39
    protected $loader = null;
40
    protected $plugins = array();
41
42
43
    /**
44
     * Construct the application with the specified name, version and config loader.
45
     *
46
     * @param string $name
47
     * @param Version $version
48
     * @param Configuration\ConfigurationLoader $loader
49
     */
50 1
    public function __construct($name = null, Version $version = null, ConfigurationLoader $loader = null)
51
    {
52 1
        parent::__construct($name, (string)$version);
53 1
        $this->setDefaultCommand('z:list');
54 1
        $this->loader = $loader;
55 1
    }
56
57
58
    /**
59
     * Custom exception rendering, renders only the exception types and messages, hierarchically, but with regular
60
     * formatting if verbosity is higher.
61
     *
62
     * @param \Exception $e
63
     * @param \Symfony\Component\Console\Output\OutputInterface $output
64
     * @return void
65
     */
66
    public function renderException($e, $output)
67
    {
68
        if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
69
            parent::renderException($e, $output);
70
        } else {
71
            /** @var $ancestry \Exception[] */
72
            $ancestry = array();
73
            $maxLength = 0;
74
            do {
75
                $ancestry[] = $e;
76
                $maxLength = max($maxLength, strlen(get_class($e)));
77
                $last = $e;
78
            } while ($e = $e->getPrevious());
79
80
            if ($last instanceof VerboseException) {
81
                $last->output($output);
82
            } else {
83
                $depth = 0;
84
                foreach ($ancestry as $e) {
85
                    $output->writeln(
86
                        sprintf(
87
                            '%s%-40s %s',
88
                            ($depth > 0 ? str_repeat('   ', $depth - 1) . '-> ' : ''),
89
                            '<fg=red;options=bold>' . $e->getMessage() . '</fg=red;options=bold>',
90
                            $depth == count($ancestry) - 1 ? str_pad('[' . get_class($e) . ']', $maxLength + 15, ' ') : ''
91
                        )
92
                    );
93
                    $depth++;
94
                }
95
            }
96
        }
97
        $output->writeln('[' . join('::', Debug::$scope) . ']');
98
    }
99
100
101
    /**
102
     * Set the container instance
103
     *
104
     * @param Container $container
105
     * @return void
106
     */
107 1
    public function setContainer(Container $container)
108
    {
109 1
        $this->container = $container;
110 1
    }
111
112
113
    /**
114
     * Returns the container instance, and initializes it if not yet available.
115
     *
116
     * @param bool $forceRecompile
117
     * @return Container
118
     */
119 1
    public function getContainer($forceRecompile = false)
120
    {
121 1
        if (null === $this->container) {
122
            $config = $this->loader->processConfiguration();
123
            $config['z']['sources'] = $this->loader->getSourceFiles();
124
            $config['z']['cache_file'] = sys_get_temp_dir() . '/z_' . sha1(json_encode($this->loader->getSourceFiles())) . '.php';
125
            if ($forceRecompile && is_file($config['z']['cache_file'])) {
126
                unlink($config['z']['cache_file']);
127
                clearstatcache();
128
            }
129
            $compiler = new ContainerCompiler(
130
                $config,
131
                $this->loader->getPlugins(),
132
                $config['z']['cache_file']
133
            );
134
            $this->container = $compiler->getContainer();
135
        }
136 1
        return $this->container;
137
    }
138
139
140 1
    protected function getDefaultCommands()
141
    {
142
        return array(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array(new \Zicht\...Command\InfoCommand()); (array<Zicht\Tool\Command...ol\Command\InfoCommand>) is 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 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('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...
143 1
            new Cmd\ListCommand(),
144 1
            new Cmd\HelpCommand(),
145 1
            new Cmd\EvalCommand(),
146 1
            new Cmd\DumpCommand(),
147 1
            new Cmd\InfoCommand()
148 1
        );
149
    }
150
151 1
    protected function getDefaultInputDefinition()
152
    {
153 1
        return new InputDefinition(
154
            array(
155 1
                new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
156
157 1
                new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
158 1
                new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'),
159 1
                new InputOption('--no-cache', '-c', InputOption::VALUE_NONE, 'Force recompilation of container code'),
160 1
                new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version.'),
161
            )
162 1
        );
163
    }
164
165
166
    /**
167
     * @{inheritDoc}
168
     */
169
    public function doRun(InputInterface $input, OutputInterface $output)
170
    {
171
        set_error_handler(new ErrorHandler($input, $output), E_USER_WARNING | E_USER_NOTICE | E_USER_DEPRECATED | E_RECOVERABLE_ERROR);
172
173
        $output->setFormatter(new Output\PrefixFormatter($output->getFormatter()));
174
175
        if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
176
            $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
177
        } elseif (true === $input->hasParameterOption(array('--verbose', '-v'))) {
178
            $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
179
        }
180
181
        $this->plugins = array();
182
183
        if ($input->hasParameterOption('--plugin')) {
184
            $value = array_filter(array_map('trim', explode(',', $input->getParameterOption('--plugin'))));
185
186
            foreach ($value as $name) {
187
                $this->loader->addPlugin($name);
188
            }
189
        }
190
191
        Debug::enterScope('init');
192
        $container = $this->getContainer($input->hasParameterOption(array('--no-cache', '-c')));
193
194
        $container->output = $output;
195
196
        $container->set('VERBOSE', $input->hasParameterOption(array('--verbose', '-v')));
197
        $container->set('FORCE', $input->hasParameterOption(array('--force', '-f')));
198
        $container->set('EXPLAIN', $input->hasParameterOption(array('--explain')));
199
        $container->set('DEBUG', $input->hasParameterOption(array('--debug')));
200
201
        foreach ($container->getCommands() as $task) {
202
            $this->add($task);
0 ignored issues
show
Documentation introduced by
$task is of type object<Zicht\Tool\Container\Task>, but the function expects a object<Symfony\Component\Console\Command\Command>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
203
        }
204
205
        Debug::exitScope('init');
206
207
        Debug::enterScope('run');
208
        if (true === $input->hasParameterOption(array('--help', '-h'))) {
209
            if (!$this->getCommandName($input)) {
210
                $input = new ArrayInput(array('command' => 'z:list'));
211
            }
212
        }
213
214
        $ret = parent::doRun($input, $output);
215
        Debug::exitScope('run');
216
217
        return $ret;
218
    }
219
220
    /**
221
     * @{inheritDoc}
222
     */
223
    public function getHelp()
224
    {
225
        $ret = parent::getHelp();
226
        if (self::$HEADER) {
227
            $ret = self::$HEADER . PHP_EOL . PHP_EOL . $ret;
228
        }
229
        return $ret;
230
    }
231
232
    public function get($name)
233
    {
234
        // The 'help' name can not be overridden as it's hard coded in the base class.
235
        if ('help' === $name) {
236
            $name = 'z:help';
237
        }
238
239
        return parent::get($name);
240
    }
241
242
243
244
}
245