TranslatableDTODataTransformer::serialize()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 1
1
<?php
2
3
/*
4
 * This file is part of the CMS Kernel package.
5
 *
6
 * Copyright (c) 2016-present 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\Application\DataTransformer\Translation;
13
14
use LIN3S\CMSKernel\Domain\Model\Translation\Locale;
15
use LIN3S\CMSKernel\Domain\Model\Translation\Translatable;
16
17
/**
18
 * @author Beñat Espiña <[email protected]>
19
 */
20
abstract class TranslatableDTODataTransformer implements TranslatableDataTransformer
21
{
22
    private $locale;
23
24
    protected $translatable;
25
    protected $translationDTODataTransformer;
26
27
    abstract protected function translatableClass();
28
29
    abstract protected function serialize();
30
31
    public function __construct(TranslationDTODataTransformer $translationDTODataTransformer)
32
    {
33
        $this->translationDTODataTransformer = $translationDTODataTransformer;
34
    }
35
36
    final public function write(Translatable $translatable, Locale $locale = null)
37
    {
38
        $translatableClass = $this->translatableClass();
39
        if (!$translatable instanceof $translatableClass) {
40
            throw new \InvalidArgumentException(
41
                sprintf('Expected instance of %s, %s given', $translatableClass, get_class($translatable))
42
            );
43
        }
44
        $this->translatable = $translatable;
45
        $this->locale = $locale;
46
    }
47
48
    final public function read()
49
    {
50
        if (null === $this->translatable) {
51
            return [];
52
        }
53
        if ($this->locale instanceof Locale) {
54
            $translation = $this->translatable->{$this->locale->locale()}();
55
56
            $this->translationDTODataTransformer->write($translation);
57
            $translationResult = $this->translationDTODataTransformer->read();
58
        } else {
59
            $translationResult = [];
60
            foreach ($this->translatable->translations() as $translation) {
61
                $this->translationDTODataTransformer->write($translation);
62
                $translationResult[$translation->locale()->locale()] = $this->translationDTODataTransformer->read();
63
            }
64
        }
65
66
        return array_merge($this->serialize(), $translationResult);
67
    }
68
}
69