ElasticaAwareCommand::getClient()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
crap 2
1
<?php
2
3
namespace GBProd\ElasticaExtraBundle\Command;
4
5
use Elastica\Client;
6
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
7
use Symfony\Component\DependencyInjection\ContainerInterface;
8
9
/**
10
 * Command tha use elasticsearch client from container
11
 *
12
 * @author gbprod <[email protected]>
13
 */
14
abstract class ElasticaAwareCommand extends ContainerAwareCommand
15
{
16
    /**
17
     * Get elasticsearch client from his name
18
     *
19
     * @param string $clientName
20
     *
21
     * @return Client
22
     */
23 17
    protected function getClient($clientName)
24
    {
25 17
        $clientName = $clientName ?: 'gbprod.elastica_extra.default_client';
26
27 17
        $client = $this->getContainer()
28 17
            ->get(
29 17
                $clientName,
30
                ContainerInterface::NULL_ON_INVALID_REFERENCE
31 17
            )
32 17
        ;
33
34 17
        $this->validateClient($client, $clientName);
35
36 15
        return $client;
37
    }
38
39 17
    protected function validateClient($client, $clientName)
40
    {
41 17
        if (!$client) {
42 1
            throw new \InvalidArgumentException(sprintf(
43 1
                'No client "%s" found',
44
                $clientName
45 1
            ));
46
        }
47
48 16
        if (!$client instanceof Client) {
49 1
            throw new \InvalidArgumentException(sprintf(
50 1
                'Client "%s" should be instance of "%s"',
51 1
                $clientName,
52
                Client::class
53 1
            ));
54
        }
55 15
    }
56
}
57