Blame view

vendor/aura/intl/src/Aura/Intl/FormatterLocator.php 1.98 KB
6c4edfa3   Alexandre   First Commit LabI...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
/**
 * 
 * This file is part of the Aura Project for PHP.
 * 
 * @package Aura.Intl
 * 
 * @license http://opensource.org/licenses/bsd-license.php BSD
 * 
 */
namespace Aura\Intl;

/**
 * 
 * A ServiceLocator implementation for loading and retaining formatter objects.
 * 
 * @package Aura.Intl
 * 
 */
class FormatterLocator
{
    /**
     * 
     * A registry to retain formatter objects.
     * 
     * @var array
     * 
     */
    protected $registry;

    /**
     * 
     * Tracks whether or not a registry entry has been converted from a 
     * callable to a formatter object.
     * 
     * @var array
     * 
     */
    protected $converted = [];
    
    /**
     * 
     * Constructor.
     * 
     * @param array $registry An array of key-value pairs where the key is the
     * formatter name the value is a callable that returns a formatter object.
     * 
     */
    public function __construct(array $registry = [])
    {
        foreach ($registry as $name => $spec) {
            $this->set($name, $spec);
        }
    }

    /**
     * 
     * Sets a formatter into the registry by name.
     * 
     * @param string $name The formatter name.
     * 
     * @param callable $spec A callable that returns a formatter object.
     * 
     * @return void
     * 
     */
    public function set($name, $spec)
    {
        $this->registry[$name] = $spec;
        $this->converted[$name] = false;
    }

    /**
     * 
     * Gets a formatter from the registry by name.
     * 
     * @param string $name The formatter to retrieve.
     * 
     * @return FormatterInterface A formatter object.
     * 
     */
    public function get($name)
    {
        if (! isset($this->registry[$name])) {
            throw new Exception\FormatterNotMapped($name);
        }

        if (! $this->converted[$name]) {
            $func = $this->registry[$name];
            $this->registry[$name] = $func();
            $this->converted[$name] = true;
        }

        return $this->registry[$name];
    }
}