Completed
Push — master ( a27a4d...e1a639 )
by Simonas
01:43 queued 11s
created

AbstractIndexServiceAwareCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[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 ONGR\ElasticsearchBundle\Command;
13
14
use ONGR\ElasticsearchBundle\DependencyInjection\Configuration;
15
use ONGR\ElasticsearchBundle\Service\IndexService;
16
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
17
use Symfony\Component\Console\Command\Command;
18
use Symfony\Component\Console\Input\InputOption;
19
use Symfony\Component\DependencyInjection\Container;
20
21
abstract class AbstractIndexServiceAwareCommand extends Command
22
{
23
    private $container;
24
25
    const INDEX_OPTION = 'index';
26
27
    public function __construct(Container $container)
28
    {
29
        $this->container = $container;
30
        parent::__construct();
31
    }
32
33
    protected function configure()
34
    {
35
        $this->addOption(
36
            self::INDEX_OPTION,
37
            'i',
38
            InputOption::VALUE_REQUIRED,
39
            'ElasticSearch index alias name or index name if you don\'t use aliases.'
40
        );
41
    }
42
43
    protected function getIndex($name): IndexService
44
    {
45
        $name = $name ?? $this->container->getParameter(Configuration::ONGR_DEFAULT_INDEX);
46
        $indexes = $this->container->getParameter(Configuration::ONGR_INDEXES);
47
48
        if (isset($indexes[$name]) && $this->container->has($indexes[$name])) {
49
            return $this->container->get($indexes[$name]);
50
        }
51
52
        throw new \RuntimeException(
53
            sprintf(
54
                'There is no index under `%s` name found. Available options: `%s`.',
55
                $name,
56
                implode('`, `', array_keys($this->container->getParameter(Configuration::ONGR_INDEXES)))
57
            )
58
        );
59
    }
60
61
    public function getContainer(): Container
62
    {
63
        return $this->container;
64
    }
65
}
66