Completed
Pull Request — master (#22)
by Sergey
12:08
created

DI   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 5
dl 0
loc 43
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 7 1
A bind() 0 7 2
B make() 0 18 5
1
<?php
2
3
namespace Isswp101\Persimmon\DI;
4
5
use Elasticsearch\ClientBuilder;
6
use Isswp101\Persimmon\Exceptions\BindingResolutionException;
7
use Isswp101\Persimmon\Repository\ElasticsearchRepository;
8
use Isswp101\Persimmon\Repository\RuntimeCacheRepository;
9
10
final class DI
11
{
12
    const ELASTICSEARCH = 'elasticsearch';
13
14
    private static $containers = [];
15
    private static $singletons = [];
16
    private static $initialized = false;
17
18
    private static function init(): void
19
    {
20
        DI::bind(DI::ELASTICSEARCH, function () {
21
            $client = ClientBuilder::create()->build();
22
            return new Container(new ElasticsearchRepository($client), new RuntimeCacheRepository());
23
        });
24
    }
25
26
    public static function bind(string $key, $abstract, bool $singleton = true): void
27
    {
28
        DI::$singletons[$key] = $singleton;
29
        DI::$containers[$key] = is_callable($abstract) ? $abstract : function () use ($abstract) {
30
            return new $abstract;
31
        };
32
    }
33
34
    public static function make(string $key)
35
    {
36
        if (!DI::$initialized) {
37
            DI::init();
38
            DI::$initialized = true;
39
        }
40
        $container = DI::$containers[$key] ?? null;
41
        if ($container == null) {
42
            throw new BindingResolutionException('Failed to resolve [' . $key . ']');
43
        }
44
        if (is_callable($container)) {
45
            $container = $container();
46
            if (DI::$singletons[$key]) {
47
                DI::$containers[$key] = $container;
48
            }
49
        }
50
        return $container;
51
    }
52
}