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

IntlFormatter::throwCannotInstantiateFormatter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
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 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 11
        $values = [];
56 11
        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 11
        }
64
65
        try {
66 11
            $formatter = new MessageFormatter($locale, $string);
67 11
        } catch (\Exception $e) {
68
            $this->throwCannotInstantiateFormatter();
69
        }
70
71 11
        $result = $formatter->format($values);
72 11
        if ($result === false) {
73 1
            throw new Exception\CannotFormat(
74 1
                $formatter->getErrorMessage(),
75 1
                $formatter->getErrorCode()
76 1
            );
77
        }
78
79 10
        return $result;
80
    }
81
82
    protected function throwCannotInstantiateFormatter()
83
    {
84
        throw new Exception\CannotInstantiateFormatter(
85
            intl_get_error_message(),
86
            intl_get_error_code()
87
        );
88
    }
89
}
90