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

DI::make()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 12
nc 8
nop 1
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
}