|
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) { |
|
|
|
|
|
|
66
|
|
|
static::$instance = (new static()) |
|
67
|
|
|
->withDefaultTypes(); |
|
68
|
|
|
} |
|
69
|
|
|
return static::$instance; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|