Passed
Pull Request — master (#1013)
by lee
07:38
created

Language::hasProperty()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4.5435

Importance

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