Translatable::translations()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the CMS Kernel library.
5
 *
6
 * Copyright (c) 2016 LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace LIN3S\CMSKernel\Domain\Model\Translation;
13
14
/**
15
 * @author Beñat Espiña <[email protected]>
16
 */
17
abstract class Translatable
18
{
19
    protected $translations;
20
21
    public function __construct(Translation $translation)
22
    {
23
        $this->translations = new TranslationCollection();
24
        $this->addTranslation($translation);
25
    }
26
27
    public function translations()
28
    {
29
        return new TranslationCollection($this->translations->getValues());
30
    }
31
32
    public function addTranslation(Translation $translation)
33
    {
34
        $translationReflection = new \ReflectionClass($translation);
35
        $origin = $translationReflection->getProperty('origin');
36
        $origin->setAccessible(true);
37
        $origin->setValue($translation, $this);
38
39
        $this->translations->add($translation);
40
    }
41
42
    public function removeTranslation(Locale $locale)
43
    {
44
        foreach ($this->translations as $translation) {
45
            if ($locale->equals($translation->locale())) {
46
                return $this->translations->removeElement($translation);
47
            }
48
        }
49
        throw new TranslationDoesNotExistException($locale->locale());
50
    }
51
52
    public function __call($locale, $args)
53
    {
54
        $resultTranslation = null;
55
        foreach ($this->translations() as $translation) {
56
            if ($translation->locale()->equals(new Locale($locale))) {
57
                $resultTranslation = $translation;
58
                break;
59
            }
60
        }
61
62
        if (!$resultTranslation instanceof Translation) {
63
            throw new TranslationDoesNotExistException($locale);
64
        }
65
66
        return $resultTranslation;
67
    }
68
}
69