Passed
Push — feature/initial-implementation ( e556a2...0c2c6c )
by Fike
01:52
created

TypeRegistry::withDefaultTypes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AmaTeam\ElasticSearch\Mapping;
6
7
use Symfony\Component\Finder\Finder;
8
use Symfony\Component\Finder\SplFileInfo;
9
10
class TypeRegistry
11
{
12
    /**
13
     * @var TypeInterface
14
     */
15
    private $idIndex = [];
16
    /**
17
     * @var TypeInterface
18
     */
19
    private $friendlyIdIndex = [];
20
21
    /**
22
     * @param string $id
23
     * @return TypeInterface|null
24
     */
25
    public function findType(string $id): ?TypeInterface
26
    {
27
        if (isset($this->friendlyIdIndex[$id])) {
28
            return $this->friendlyIdIndex[$id];
29
        }
30
        if (isset($this->idIndex[$id])) {
31
            return $this->idIndex[$id];
32
        }
33
        return null;
34
    }
35
36
    public function register(TypeInterface $type): TypeRegistry
37
    {
38
        $this->idIndex[$type->getId()] = $type;
39
        $this->friendlyIdIndex[$type->getFriendlyId()] = $type;
40
        return $this;
41
    }
42
43
    public function withDefaultTypes(): TypeRegistry
44
    {
45
        // TODO: this method should not touch the filesystem
46
        $finder = (new Finder())
47
            ->in(sprintf('%s/%s', __DIR__, 'Type'))
48
            ->name('*.php')
49
            ->notName('Abstract*.php');
50
        /** @var SplFileInfo $file */
51
        foreach ($finder as $file) {
52
            $components = [__NAMESPACE__, 'Type', $file->getBasename('.php')];
53
            $name = implode('\\', $components);
54
            $accessible = method_exists($name, 'getInstance');
55
            $type = $accessible ? $name::getInstance() : new $name();
56
            $this->register($type);
57
        }
58
        return $this;
59
    }
60
61
    private static $instance;
62
63
    public static function getInstance(): TypeRegistry
64
    {
65
        if (!static::$instance) {
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $instance to at least protected.
Loading history...
66
            static::$instance = (new static())
67
                ->withDefaultTypes();
68
        }
69
        return static::$instance;
70
    }
71
}
72