Completed
Pull Request — 2.x (#29)
by Hari
02:15
created

IntlFormatter::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
crap 2
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 13
    public function __construct($icu_version = INTL_ICU_VERSION)
37
    {
38 13
        if (version_compare($icu_version, '4.8') < 0) {
39 1
            throw new Exception\IcuVersionTooLow('ICU Version 4.8 or higher required.');
40
        }
41 12
    }
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 12
    public function format($locale, $string, array $tokens_values)
54
    {
55 12
        $values = [];
56 12
        foreach ($tokens_values as $token => $value) {
57
            // convert an array to a CSV string
58 11
            if (is_array($value)) {
59 1
                $value = '"' . implode('", "', $value) . '"';
60 1
            }
61
62 11
            $values[$token] = $value;
63 12
        }
64
65
        try {
66 12
            $formatter = new MessageFormatter($locale, $string);
67 12
            if (! $formatter) {
68 1
                $this->throwCannotInstantiateFormatter();
69
            }
70 12
        } catch (\Exception $e) {
71 1
            $this->throwCannotInstantiateFormatter();
72
        }
73
74 11
        $result = $formatter->format($values);
75 11
        if ($result === false) {
76 1
            throw new Exception\CannotFormat(
77 1
                $formatter->getErrorMessage(),
78 1
                $formatter->getErrorCode()
79 1
            );
80
        }
81
82 10
        return $result;
83
    }
84
85 1
    protected function throwCannotInstantiateFormatter()
86
    {
87 1
        throw new Exception\CannotInstantiateFormatter(
88 1
            intl_get_error_message(),
89 1
            intl_get_error_code()
90 1
        );
91
    }
92
}
93