ElasticsearchServiceProvider::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 3
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace xmarcos\Silex;
4
5
use Silex\Application;
6
use Elasticsearch\Client;
7
use InvalidArgumentException;
8
use Silex\ServiceProviderInterface;
9
10
class ElasticsearchServiceProvider implements ServiceProviderInterface
11
{
12
    protected $prefix;
13
14
    /**
15
     * @param string $prefix Prefix name used to register the service in Silex.
16
     */
17
    public function __construct($prefix = 'elasticsearch')
18
    {
19
        if (empty($prefix) || false === is_string($prefix)) {
20
            throw new InvalidArgumentException(
21
                sprintf('$prefix must be a non-empty string, "%s" given', gettype($prefix))
22
            );
23
        }
24
25
        $this->prefix = $prefix;
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function register(Application $app)
32
    {
33
        $prefix           = $this->prefix;
34
        $params_key       = sprintf('%s.params', $prefix);
35
        $app[$params_key] = isset($app[$params_key]) ? $app[$params_key] : [];
36
37
        $app[$prefix] = $app->share(
38
            function (Application $app) use ($params_key) {
39
                return new Client($app[$params_key]);
40
            }
41
        );
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     * @codeCoverageIgnore
47
     */
48
    public function boot(Application $app)
49
    {
50
    }
51
}
52