|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* |
|
4
|
|
|
* This file is part of the Aura Project for PHP. |
|
5
|
|
|
* |
|
6
|
|
|
* @package Aura.Intl |
|
7
|
|
|
* |
|
8
|
|
|
* @license http://opensource.org/licenses/MIT MIT |
|
9
|
|
|
* |
|
10
|
|
|
*/ |
|
11
|
|
|
namespace Aura\Intl; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* |
|
15
|
|
|
* A ServiceLocator implementation for loading and retaining formatter objects. |
|
16
|
|
|
* |
|
17
|
|
|
* @package Aura.Intl |
|
18
|
|
|
* |
|
19
|
|
|
*/ |
|
20
|
|
|
class FormatterLocator |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* |
|
24
|
|
|
* A registry to retain formatter objects. |
|
25
|
|
|
* |
|
26
|
|
|
* @var array |
|
27
|
|
|
* |
|
28
|
|
|
*/ |
|
29
|
|
|
protected $registry; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* |
|
33
|
|
|
* Tracks whether or not a registry entry has been converted from a |
|
34
|
|
|
* callable to a formatter object. |
|
35
|
|
|
* |
|
36
|
|
|
* @var array |
|
37
|
|
|
* |
|
38
|
|
|
*/ |
|
39
|
|
|
protected $converted = []; |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* |
|
43
|
|
|
* Constructor. |
|
44
|
|
|
* |
|
45
|
|
|
* @param array $registry An array of key-value pairs where the key is the |
|
46
|
|
|
* formatter name the value is a callable that returns a formatter object. |
|
47
|
|
|
* |
|
48
|
|
|
*/ |
|
49
|
11 |
|
public function __construct(array $registry = []) |
|
50
|
|
|
{ |
|
51
|
11 |
|
foreach ($registry as $name => $spec) { |
|
52
|
9 |
|
$this->set($name, $spec); |
|
53
|
11 |
|
} |
|
54
|
11 |
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* |
|
58
|
|
|
* Sets a formatter into the registry by name. |
|
59
|
|
|
* |
|
60
|
|
|
* @param string $name The formatter name. |
|
61
|
|
|
* |
|
62
|
|
|
* @param callable $spec A callable that returns a formatter object. |
|
63
|
|
|
* |
|
64
|
|
|
* @return void |
|
65
|
|
|
* |
|
66
|
|
|
*/ |
|
67
|
10 |
|
public function set($name, $spec) |
|
68
|
|
|
{ |
|
69
|
10 |
|
$this->registry[$name] = $spec; |
|
70
|
10 |
|
$this->converted[$name] = false; |
|
71
|
10 |
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* |
|
75
|
|
|
* Gets a formatter from the registry by name. |
|
76
|
|
|
* |
|
77
|
|
|
* @param string $name The formatter to retrieve. |
|
78
|
|
|
* |
|
79
|
|
|
* @return FormatterInterface A formatter object. |
|
80
|
|
|
* |
|
81
|
|
|
* @throws Exception\FormatterNotMapped |
|
82
|
|
|
* |
|
83
|
|
|
*/ |
|
84
|
5 |
|
public function get($name) |
|
85
|
|
|
{ |
|
86
|
5 |
|
if (! isset($this->registry[$name])) { |
|
87
|
1 |
|
throw new Exception\FormatterNotMapped($name); |
|
88
|
|
|
} |
|
89
|
|
|
|
|
90
|
4 |
|
if (! $this->converted[$name]) { |
|
91
|
4 |
|
$func = $this->registry[$name]; |
|
92
|
4 |
|
$this->registry[$name] = $func(); |
|
93
|
4 |
|
$this->converted[$name] = true; |
|
94
|
4 |
|
} |
|
95
|
|
|
|
|
96
|
4 |
|
return $this->registry[$name]; |
|
97
|
|
|
} |
|
98
|
|
|
} |
|
99
|
|
|
|