Completed
Push — master ( 09ed12...283542 )
by Changwan
03:07
created

CommandAdapter::__construct()   C

Complexity

Conditions 7
Paths 16

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 7
eloc 19
c 1
b 0
f 1
nc 16
nop 2
dl 0
loc 30
ccs 0
cts 25
cp 0
crap 56
rs 6.7272
1
<?php
2
namespace Wandu\Console\Symfony;
3
4
use Symfony\Component\Console\Command\Command as SymfonyCommand;
5
use Symfony\Component\Console\Input\InputArgument;
6
use Symfony\Component\Console\Input\InputInterface;
7
use Symfony\Component\Console\Input\InputOption;
8
use Symfony\Component\Console\Output\OutputInterface;
9
use Wandu\Console\Command;
10
use Wandu\Console\Exception\ConsoleException;
11
12
class CommandAdapter extends SymfonyCommand
13
{
14
    /** @var \Wandu\Console\Command */
15
    protected $command;
16
    
17
    /**
18
     * @param string $name
19
     * @param \Wandu\Console\Command $command
20
     */
21
    public function __construct($name, Command $command)
22
    {
23
        parent::__construct($name);
24
25
        $this->command = $command;
26
27
        $this->setDescription($command->getDescription());
28
        $this->setHelp($command->getHelp());
29
30
        // arguments
31
        foreach ($command->getArguments() as $argument => $description) {
32
            if (substr($argument, -1) === '?') {
33
                $this->addArgument(substr($argument, 0, -1), InputArgument::OPTIONAL, $description);
34
            } elseif (substr($argument, -2) === '[]') {
35
                $this->addArgument(substr($argument, 0, -2), InputArgument::IS_ARRAY, $description);
36
            } else {
37
                $this->addArgument($argument, InputArgument::REQUIRED, $description);
38
            }
39
        }
40
41
        foreach ($command->getOptions() as $option => $description) {
42
            if (substr($option, -1) === '?') {
43
                $this->addOption(substr($option, 0, -1), null, InputOption::VALUE_OPTIONAL, $description);
44
            } elseif (substr($option, -2) === '[]') {
45
                $this->addOption(substr($option, 0, -2), null, InputOption::VALUE_IS_ARRAY, $description);
46
            } else {
47
                $this->addOption($option, null, InputOption::VALUE_REQUIRED, $description);
48
            }
49
        }
50
    }
51
52
    /**
53
     * @param \Symfony\Component\Console\Input\InputInterface $input
54
     * @param \Symfony\Component\Console\Output\OutputInterface $output
55
     * @return int
56
     */
57
    protected function execute(InputInterface $input, OutputInterface $output)
58
    {
59
        try {
60
            return $this->command->withIO($input, $output)->execute();
61
        } catch (ConsoleException $e) {
62
            $output->writeln($e->getMessage());
63
            return -1;
64
        }
65
    }
66
}
67