Language::codeIsValid()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace GinoPane\PHPolyglot\Supplemental\Language;
4
5
use GinoPane\PHPolyglot\Exception\InvalidLanguageCodeException;
6
use GinoPane\PHPolyglot\Supplemental\GetConstantsTrait;
7
8
/**
9
 * Class Language
10
 *
11
 * @author Sergey <Gino Pane> Karavay
12
 */
13
class Language implements LanguageInterface
14
{
15
    /**
16
     * Constant value for undefined language
17
     */
18
    const CODE_UNDEFINED = '';
19
20
    /**
21
     * Stored part of speech
22
     *
23
     * @var string
24
     */
25
    private $language = self::CODE_UNDEFINED;
26
27
    use GetConstantsTrait;
28
29
    /**
30
     * DictionaryEntryPos constructor
31
     *
32
     * @param string $language
33
     *
34
     * @throws InvalidLanguageCodeException
35
     */
36
    public function __construct(string $language = self::CODE_UNDEFINED)
37
    {
38
        $language = strtolower($language);
39
40
        if ($language !== self::CODE_UNDEFINED) {
41
            $this->assertLanguageIsValid($language);
42
        }
43
44
        $this->language = $language;
45
    }
46
47
    /**
48
     * Checks if code is valid
49
     *
50
     * @param string $code
51
     *
52
     * @return bool
53
     */
54
    public function codeIsValid(string $code): bool
55
    {
56
        return $this->constantValueExists($code);
57
    }
58
59
    /**
60
     * Returns current language code
61
     *
62
     * @return string
63
     */
64
    public function getCode(): string
65
    {
66
        return $this->language;
67
    }
68
69
    /**
70
     * Alias for Language::getCode
71
     *
72
     * @see Language::getCode()
73
     *
74
     * @return string
75
     */
76
    public function __toString(): string
77
    {
78
        return $this->getCode();
79
    }
80
81
    /**
82
     * Checks that specified language code is valid
83
     *
84
     * @param string $language
85
     *
86
     * @throws InvalidLanguageCodeException
87
     */
88
    private function assertLanguageIsValid(string $language): void
89
    {
90
        if (!$this->codeIsValid($language)) {
91
            throw new InvalidLanguageCodeException(
92
                sprintf("Language code \"%s\" is invalid", $language)
93
            );
94
        }
95
    }
96
}
97