Passed
Push — feature/initial-implementation ( fae671...591f29 )
by Fike
02:37
created

Registry::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
rs 10
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AmaTeam\ElasticSearch\Entity;
6
7
use AmaTeam\ElasticSearch\API\Entity\Loader\ContextInterface;
8
use AmaTeam\ElasticSearch\API\Entity\LoaderInterface;
9
use AmaTeam\ElasticSearch\API\EntityInterface;
10
use AmaTeam\ElasticSearch\API\Entity\RegistryInterface;
11
use BadMethodCallException;
12
13
class Registry implements RegistryInterface
14
{
15
    /**
16
     * @var LoaderInterface
17
     */
18
    private $loader;
19
    /**
20
     * @var EntityInterface[]
21
     */
22
    private $registry = [];
23
24
    /**
25
     * @param LoaderInterface $loader
26
     */
27
    public function __construct(LoaderInterface $loader)
28
    {
29
        $this->loader = $loader;
30
    }
31
32
    public function get(string $name): EntityInterface
33
    {
34
        $entity = $this->find($name);
35
        if ($entity) {
36
            return $entity;
37
        }
38
        throw new BadMethodCallException("Can't get entity for class `$name`");
39
    }
40
41
    public function find(string $name, ContextInterface $context = null): ?EntityInterface
42
    {
43
        if (isset($this->registry[$name])) {
44
            return $this->registry[$name];
45
        }
46
        $entity = $this->loader->load($name, $context);
47
        if (!$entity) {
48
            return null;
49
        }
50
        $this->registry[$name] = $entity;
51
        return $entity;
52
    }
53
54
    public function exists(string $name): bool
55
    {
56
        return isset($this->registry[$name]) || $this->loader->exists($name);
57
    }
58
}
59