Completed
Push — master ( 9d34e9...5c91c8 )
by Ilario
07:12
created

AbstractCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php declare(strict_types=1);
2
3
namespace Facile\MongoDbBundle\Command;
4
5
use MongoDB\Database as Connection;
6
use Symfony\Component\Console\Command\Command;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Input\InputOption;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Symfony\Component\Console\Style\SymfonyStyle;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
13
/**
14
 * Class AbstractCommand.
15
 */
16
abstract class AbstractCommand extends Command
17
{
18
    /** @var SymfonyStyle */
19
    protected $io;
20
21
    /** @var Connection */
22
    protected $connection;
23
24
    /** @var ContainerInterface */
25 8
    private $container;
26
27 8
    /**
28
     * AbstractCommand constructor.
29 8
     * @param ContainerInterface $container
30 8
     */
31
    public function __construct(ContainerInterface $container, string $name = null)
32
    {
33
        parent::__construct($name);
34
        $this->container = $container;
35 8
    }
36
37 8
    protected function getContainer(): ContainerInterface
38 8
    {
39
        return $this->container;
40 8
    }
41
42 8
    /**
43 2
     * {@inheritdoc}
44
     */
45
    protected function configure()
46 8
    {
47 1
        parent::configure();
48
        $this
49
            ->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'The connection to use for this command');
50 7
    }
51 7
52
    /**
53
     * {@inheritdoc}
54
     */
55
    protected function initialize(InputInterface $input, OutputInterface $output)
56
    {
57
        parent::initialize($input, $output);
58
        $this->io = new SymfonyStyle($input, $output);
59
60
        $connectionName = 'mongo.connection';
61
62
        if ($input->getOption('connection')) {
63
            $connectionName .= '.' . $input->getOption('connection');
64
        }
65
66
        if (! $this->container->has($connectionName)) {
67
            throw new \LogicException(sprintf('No connection named \'%s\' found', $input->getOption('connection')));
68
        }
69
70
        $this->connection = $this->container->get($connectionName);
71
    }
72
}
73