Completed
Pull Request — master (#1)
by Gorka
04:16
created

TranslationCollection::addTranslation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
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
use LIN3S\SharedKernel\Domain\Model\Collection;
15
use LIN3S\SharedKernel\Domain\Model\CollectionElementAlreadyAddedException;
16
17
/**
18
 * @author Beñat Espiña <[email protected]>
19
 */
20
class TranslationCollection extends Collection
21
{
22
    protected function type()
23
    {
24
        return Translation::class;
25
    }
26
27
    public function add($translation)
28
    {
29
        $translations = $this->toArray();
30
        foreach ($translations as $trans) {
31
            if ($translation->locale()->equals($trans->locale())) {
32
                throw new CollectionElementAlreadyAddedException();
33
            }
34
        }
35
        parent::add($translation);
36
    }
37
38
    public function addTranslation($translation, Translatable $translatable)
0 ignored issues
show
Unused Code introduced by
The parameter $translatable is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
39
    {
40
        $translationReflection = new \ReflectionClass($translation);
41
        $origin = $translationReflection->getProperty('origin');
42
        $origin->setAccessible(true);
43
        $origin->setValue($translation, $this);
44
45
        $this->add($translation);
46
    }
47
48
    public function removeTranslation(Locale $locale)
49
    {
50
        foreach ($this->toArray() as $translation) {
51
            if ($locale->equals($translation->locale())) {
52
                return $this->removeElement($translation);
53
            }
54
        }
55
        throw new TranslationDoesNotExistException($locale->locale());
56
    }
57
58
    public function getTranslation(Locale $locale)
59
    {
60
        $resultTranslation = null;
61
        foreach ($this->toArray() as $translation) {
62
            if ($translation->locale()->equals(new Locale($locale))) {
63
                $resultTranslation = $translation;
64
                break;
65
            }
66
        }
67
68
        if (!$resultTranslation instanceof Translation) {
69
            throw new TranslationDoesNotExistException($locale);
70
        }
71
72
        return $resultTranslation;
73
    }
74
}
75