Completed
Push — fix-clean-code ( fbbd48 )
by Arnaud
01:49
created

Language::getName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
/*
3
 * Copyright (c) Arnaud Ligny <[email protected]>
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Cecil\Renderer;
10
11
use Cecil\Config;
12
use Cecil\Exception\Exception;
13
14
/**
15
 * Class Language.
16
 */
17
class Language
18
{
19
    /**
20
     * Config.
21
     *
22
     * @var Config
23
     */
24
    protected $config;
25
    /**
26
     * Current language.
27
     *
28
     * @var string
29
     */
30
    protected $language;
31
32
    /**
33
     * Language constructor.
34
     *
35
     * @param Config      $config
36
     * @param string|null $language
37
     */
38
    public function __construct(Config $config, string $language = null)
39
    {
40
        $this->config = $config;
41
        $this->language = $language;
42
    }
43
44
    public function __toString()
45
    {
46
        if ($this->language) {
47
            return $this->language;
48
        }
49
50
        return $this->config->getLanguageDefault();
51
    }
52
53
    public function getName(): ?string
54
    {
55
        if ($this->hasProperty('name')) {
56
            return $this->config->getLanguageProperty('name', $this->language);
57
        }
58
    }
59
60
    public function getLocale(): ?string
61
    {
62
        if ($this->hasProperty('locale')) {
63
            return $this->config->getLanguageProperty('locale', $this->language);
64
        }
65
    }
66
67
    public function getWeight(): int
68
    {
69
        if ($this->language) {
70
            return $this->config->getLanguageIndex($this->language);
71
        }
72
73
        return 0;
74
    }
75
76
    private function hasProperty(string $property): bool
77
    {
78
        $value = $this->config->getLanguageProperty($property, $this->language);
79
80
        if (empty($value)) {
81
            $language = $this->language ?: $this->config->getLanguageDefault();
82
83
            throw new Exception(sprintf(
84
                'The property "%s" is empty for language "%s".',
85
                $property,
86
                $language
87
            ));
88
        }
89
90
        return true;
91
    }
92
}
93