Completed
Push — master ( 2bb920...810e98 )
by Rafael
02:04
created

CountryExtension::getCountryName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 1
Metric Value
c 3
b 2
f 1
dl 0
loc 10
rs 9.4286
cc 3
eloc 6
nc 3
nop 2
1
<?php
2
3
namespace Mero\Bundle\BaseBundle\Twig;
4
5
use Symfony\Component\Intl\Intl;
6
7
/**
8
 * Country filter for Twig.
9
 *
10
 * @author Rafael Mello <[email protected]>
11
 * @license https://github.com/merorafael/MeroBaseBundle/blob/master/LICENSE MIT license
12
 */
13
class CountryExtension extends \Twig_Extension
14
{
15
    public function __construct()
16
    {
17
        if (!class_exists('\Locale')) {
18
            throw new \RuntimeException('The country extension is needed to use intl-based filters.');
19
        }
20
    }
21
22
    public function getFilters()
23
    {
24
        return array(
25
            new \Twig_SimpleFilter('country', [
26
                $this,
27
                'getCountryName',
28
            ]),
29
        );
30
    }
31
32
    /**
33
     * Return the country name using the Locale class.
34
     *
35
     * @param string      $isoCode Country ISO 3166-1 alpha 2 code
36
     * @param null|string $locale  Locale code
37
     *
38
     * @return null|string Country name
39
     */
40
    public function getCountryName($isoCode, $locale = null)
41
    {
42
        if ($isoCode === null) {
43
            return;
44
        }
45
46
        return ($locale === null)
47
            ? Intl::getRegionBundle()->getCountryName($isoCode)
48
            : Intl::getRegionBundle()->getCountryName($isoCode, $locale);
49
    }
50
51
    public function getName()
52
    {
53
        return 'country_extension';
54
    }
55
}
56