LanguageExtension   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 4
dl 0
loc 47
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A getFilters() 0 9 1
A getLanguageName() 0 14 4
A getName() 0 4 1
1
<?php
2
3
namespace Mero\Bundle\BaseBundle\Twig;
4
5
use Symfony\Component\Intl\Intl;
6
7
/**
8
 * Language 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 LanguageExtension 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('language', [
26
                $this,
27
                'getLanguageName',
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 getLanguageName($isoCode, $locale = null)
41
    {
42
        if ($isoCode === null) {
43
            return;
44
        }
45
        if ($locale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
46
            \Locale::setDefault($locale);
47
        }
48
        $language = explode('_', $isoCode);
49
50
        return isset($language[1])
51
            ? Intl::getLanguageBundle()->getLanguageName($language[0], $language[1])
52
            : Intl::getLanguageBundle()->getLanguageName($language[0]);
53
    }
54
55
    public function getName()
56
    {
57
        return 'language_extension';
58
    }
59
}
60