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

Manager::exists()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
c 0
b 0
f 0
rs 9.2
cc 4
eloc 6
nc 4
nop 1
1
<?php
2
3
namespace AmaTeam\ElasticSearch\Entity\Descriptor;
4
5
use AmaTeam\ElasticSearch\API\Entity\Descriptor\LoaderInterface;
6
use AmaTeam\ElasticSearch\API\Entity\Descriptor\ManagerInterface;
7
use AmaTeam\ElasticSearch\API\Entity\Descriptor\RegistryInterface;
8
use AmaTeam\ElasticSearch\API\Entity\DescriptorInterface;
9
use AmaTeam\ElasticSearch\Utility\Arrays;
10
use BadMethodCallException;
11
12
class Manager implements ManagerInterface
13
{
14
    /**
15
     * @var RegistryInterface
16
     */
17
    private $registry;
18
    /**
19
     * @var LoaderInterface[]
20
     */
21
    private $loaders = [];
22
23
    /**
24
     * @param RegistryInterface $registry
25
     * @param LoaderInterface[] $loaders
26
     */
27
    public function __construct(RegistryInterface $registry = null, array $loaders = [])
28
    {
29
        $this->registry = $registry ?: new Registry;
30
        $this->loaders = $loaders;
31
    }
32
33
    public function get(string $name): DescriptorInterface
34
    {
35
        $descriptor = $this->find($name);
36
        if ($descriptor) {
37
            return $descriptor;
38
        }
39
        $message = "Couldn't find metadata descriptor for id `$name`";
40
        throw new BadMethodCallException($message);
41
    }
42
43
    public function find(string $name): ?DescriptorInterface
44
    {
45
        if ($this->registry->has($name)) {
46
            return $this->registry->get($name);
47
        }
48
        foreach ($this->loaders as $loader) {
49
            $descriptor = $loader->load($name);
50
            if ($descriptor) {
51
                $this->registry->register($descriptor);
52
                return $descriptor;
53
            }
54
        }
55
        return null;
56
    }
57
58
    public function exists(string $name): bool
59
    {
60
        if ($this->registry->has($name)) {
61
            return true;
62
        }
63
        foreach ($this->loaders as $loader) {
64
            if ($loader->exists($name)) {
65
                return true;
66
            }
67
        }
68
        return false;
69
    }
70
71
    public function registerLoader(LoaderInterface $loader): Manager
72
    {
73
        $this->deregisterLoader($loader);
74
        $this->loaders[] = $loader;
75
        return $this;
76
    }
77
78
    public function deregisterLoader(LoaderInterface $loader): Manager
79
    {
80
        $this->loaders = Arrays::remove($this->loaders, $loader);
81
        return $this;
82
    }
83
}
84