Completed
Pull Request — 2.x (#28)
by Hari
01:45
created

IntlFormatter::format()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 16
cts 16
cp 1
rs 8.439
c 0
b 0
f 0
cc 5
eloc 16
nc 12
nop 3
crap 5
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
use MessageFormatter;
14
use Aura\Intl\Exception;
15
16
/**
17
 *
18
 * Uses php intl extension to format messages
19
 *
20
 * @package Aura.Intl
21
 *
22
 */
23
class IntlFormatter implements FormatterInterface
24
{
25
    /**
26
     *
27
     * Constructor.
28
     *
29
     * @param string $icu_version The current ICU version; mostly used for
30
     * testing.
31
     *
32
     * @throws Exception\IcuVersionTooLow when the Version of ICU installed
33
     * is too low for Aura.Intl to work properly.
34
     *
35
     */
36 12
    public function __construct($icu_version = INTL_ICU_VERSION)
37
    {
38 12
        if (version_compare($icu_version, '4.8') < 0) {
39 1
            throw new Exception\IcuVersionTooLow('ICU Version 4.8 or higher required.');
40
        }
41 11
    }
42
43
    /**
44
     *
45
     * Format the message with the help of php intl extension
46
     *
47
     * @param string $locale
48
     * @param string $string
49
     * @param array $tokens_values
50
     * @return string
51
     * @throws Exception
52
     */
53 11
    public function format($locale, $string, array $tokens_values)
54
    {
55
        $values = [];
56 11
        foreach ($tokens_values as $token => $value) {
57 11
            // convert an array to a CSV string
58
            if (is_array($value)) {
59
                $value = '"' . implode('", "', $value) . '"';
60
            }
61 11
62 11
            $values[$token] = $value;
63
        }
64 11
65
        try {
66
            $formatter = new MessageFormatter($locale, $string);
67 11
        } catch (\Exception $e) {
68 11
            $this->throwCannotInstantiateFormatter();
69 11
        }
70 11
71 11
        $result = $formatter->format($values);
72 11
        if ($result === false) {
73 8
            throw new Exception\CannotFormat(
74
                $formatter->getErrorMessage(),
75
                $formatter->getErrorCode()
76
            );
77
        }
78 11
79 11
        return $result;
80 11
    }
81 11
82
    protected function throwCannotInstantiateFormatter()
83 11
    {
84 11
        throw new Exception\CannotInstantiateFormatter(
85
            intl_get_error_message(),
86 11
            intl_get_error_code()
87 11
        );
88 11
    }
89
}
90