DisplayName::getTranslation()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
/**
4
 * Copyright 2015 SURFnet B.V.
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace OpenConext\Profile\Value;
20
21
use OpenConext\Profile\Assert;
22
use OpenConext\Profile\Exception\LogicException;
23
24
final class DisplayName
25
{
26
    /**
27
     * @var string[]
28
     */
29
    private $translations = [];
30
31
    public function __construct(array $translations = [])
32
    {
33
        Assert::allString(array_keys($translations), 'Translations must be indexed by locale');
34
        Assert::allNotBlank(array_keys($translations), 'Locales may not be blank');
35
        Assert::allString($translations, 'Translations must be strings');
36
37
        $this->translations = $translations;
38
    }
39
40
    /**
41
     * @param string $locale
42
     * @return bool
43
     */
44
    public function hasFilledTranslationForLocale($locale)
45
    {
46
        Assert::string($locale, 'Locale must be string', 'locale');
47
48
        return array_key_exists($locale, $this->translations) && trim($this->translations[$locale]) !== '';
49
    }
50
51
    /**
52
     * @return string
53
     */
54
    public function getTranslation($locale)
55
    {
56
        if (!isset($this->translations[$locale])) {
57
            throw new LogicException(sprintf('Could not find translation for locale "%s"', $locale));
58
        }
59
60
        return $this->translations[$locale];
61
    }
62
63
    public function __toString()
64
    {
65
        return sprintf(
66
            'DisplayName(%s)',
67
            join(
68
                ', ',
69
                array_map(
70
                    function ($locale) {
71
                        return sprintf('%s=%s', $locale, $this->translations[$locale]);
72
                    },
73
                    array_keys($this->translations)
74
                )
75
            )
76
        );
77
    }
78
}
79