Completed
Push — develop ( cb949f...cc6c0d )
by Daniel
06:01 queued 42s
created

ApiNormalizer::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.004

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 7
dl 0
loc 19
ccs 9
cts 10
cp 0.9
crap 2.004
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Serializer;
4
5
use ApiPlatform\Core\DataProvider\ContextAwareCollectionDataProviderInterface;
6
use Doctrine\Common\Collections\ArrayCollection;
7
use Doctrine\ORM\EntityManagerInterface;
8
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
9
use Silverback\ApiComponentBundle\Entity\Content\Component\Collection\Collection;
10
use Silverback\ApiComponentBundle\Entity\Content\Component\ComponentLocation;
11
use Silverback\ApiComponentBundle\Entity\Content\Component\Form\Form;
12
use Silverback\ApiComponentBundle\Entity\Content\Dynamic\AbstractDynamicPage;
13
use Silverback\ApiComponentBundle\Entity\Content\FileInterface;
14
use Silverback\ApiComponentBundle\Entity\Content\Page;
15
use Silverback\ApiComponentBundle\Entity\Layout\Layout;
16
use Silverback\ApiComponentBundle\Factory\Entity\Content\Component\Form\FormViewFactory;
17
use Silverback\ApiComponentBundle\Imagine\PathResolver;
18
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
19
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
20
use Symfony\Component\Serializer\SerializerAwareInterface;
21
use Symfony\Component\Serializer\SerializerInterface;
22
23
final class ApiNormalizer implements NormalizerInterface, DenormalizerInterface, SerializerAwareInterface
24
{
25
    private $decorated;
26
    private $imagineCacheManager;
27
    private $formViewFactory;
28
    private $pathResolver;
29
    private $em;
30
    private $projectDir;
31
    private $collectionDataProvider;
32
33
    /**
34
     * FileNormalizer constructor.
35
     * @param NormalizerInterface $decorated
36
     * @param CacheManager $imagineCacheManager
37
     * @param FormViewFactory $formViewFactory
38
     * @param PathResolver $pathResolver
39
     * @param EntityManagerInterface $entityManager
40
     * @param ContextAwareCollectionDataProviderInterface $collectionDataProvider
41
     * @param string $projectDir
42
     */
43 10
    public function __construct(
44
        NormalizerInterface $decorated,
45
        CacheManager $imagineCacheManager,
46
        FormViewFactory $formViewFactory,
47
        PathResolver $pathResolver,
48
        EntityManagerInterface $entityManager,
49
        ContextAwareCollectionDataProviderInterface $collectionDataProvider,
50
        string $projectDir = '/'
51
    ) {
52 10
        if (!$decorated instanceof DenormalizerInterface) {
53
            throw new \InvalidArgumentException(sprintf('The decorated normalizer must implement the %s.', DenormalizerInterface::class));
54
        }
55 10
        $this->decorated = $decorated;
56 10
        $this->imagineCacheManager = $imagineCacheManager;
57 10
        $this->formViewFactory = $formViewFactory;
58 10
        $this->pathResolver = $pathResolver;
59 10
        $this->em = $entityManager;
60 10
        $this->collectionDataProvider = $collectionDataProvider;
61 10
        $this->projectDir = $projectDir;
62 10
    }
63
64
    /**
65
     * @param mixed $data
66
     * @param string|null $format
67
     * @return bool
68
     */
69 5
    public function supportsNormalization($data, $format = null): bool
70
    {
71 5
        return $this->decorated->supportsNormalization($data, $format);
72
    }
73
74
    /**
75
     * @param $object
76
     * @param string|null $format
77
     * @param array $context
78
     * @return array|bool|float|int|string
79
     * @throws \Symfony\Component\Serializer\Exception\LogicException
80
     * @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException
81
     * @throws \Symfony\Component\Serializer\Exception\CircularReferenceException
82
     * @throws \ApiPlatform\Core\Exception\ResourceClassNotSupportedException
83
     */
84 6
    public function normalize($object, $format = null, array $context = [])
85
    {
86 6
        if ($object instanceof Page) {
87
            if (!$object->getLayout()) {
88
                $object->setLayout($this->em->getRepository(Layout::class)->findOneBy(['default' => true]));
89
            }
90
        }
91 6
        if ($object instanceof Form && !$object->getForm()) {
92 1
            $object->setForm($this->formViewFactory->create($object));
93
        }
94 6
        if ($object instanceof Collection) {
95
            // We should really find whatever the data provider is currently for the resource instead of just using the default
96
            $object->setCollection($this->collectionDataProvider->getCollection($object->getResource(), 'GET', $context));
97
        }
98 6
        $data = $this->decorated->normalize($object, $format, $context);
99
100 6
        if ($object instanceof FileInterface) {
101 1
            $data = array_merge($data, $this->getFileData($object));
102
        }
103 6
        return $data;
104
    }
105
106
    /**
107
     * @param \Silverback\ApiComponentBundle\Entity\Content\FileInterface $object
108
     * @return array
109
     */
110 1
    private function getFileData(FileInterface $object): array
111
    {
112 1
        $data = [];
113 1
        $filePath = $object->getFilePath();
114 1
        if ($filePath) {
115 1
            if (false !== \exif_imagetype($filePath)) {
116 1
                [$width, $height] = getimagesize($filePath);
117
            } else {
118
                $width = $height = 0;
119
            }
120 1
            $data['width'] = $width;
121 1
            $data['height'] = $height;
122
123 1
            $supported = $this->isImagineSupportedFile($filePath);
124 1
            foreach ($object::getImagineFilters() as $returnKey => $filter) {
125 1
                $data[$returnKey] = $supported ? parse_url(
126 1
                    $this->imagineCacheManager->getBrowserPath($this->pathResolver->resolve($filePath), $filter),
127 1
                    PHP_URL_PATH
128 1
                ) : null;
129
            }
130
131 1
            $data['filePath'] = $this->getPublicPath($filePath);
132
        }
133 1
        return $data;
134
    }
135
136 1
    private function getPublicPath(string $filePath) {
137 1
        $publicPaths = [$this->projectDir, '/public/', '/web/'];
138 1
        foreach ($publicPaths as $path) {
139 1
            if (mb_strpos($filePath, $path) === 0 && $start = \strlen($path)) {
140 1
                $filePath = mb_substr($filePath, $start);
141
            }
142
        }
143 1
        return $filePath;
144
    }
145
146
    /**
147
     * @param mixed $data
148
     * @param string $type
149
     * @param string|null $format
150
     * @return bool
151
     */
152 5
    public function supportsDenormalization($data, $type, $format = null): bool
153
    {
154 5
        return $this->decorated->supportsDenormalization($data, $type, $format);
155
    }
156
157
    /**
158
     * @param mixed $data
159
     * @param string $class
160
     * @param string|null $format
161
     * @param array $context
162
     * @return object
163
     * @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
164
     * @throws \Symfony\Component\Serializer\Exception\RuntimeException
165
     * @throws \Symfony\Component\Serializer\Exception\LogicException
166
     * @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException
167
     * @throws \Symfony\Component\Serializer\Exception\ExtraAttributesException
168
     * @throws \Symfony\Component\Serializer\Exception\BadMethodCallException
169
     * @throws \InvalidArgumentException
170
     */
171 1
    public function denormalize($data, $class, $format = null, array $context = [])
172
    {
173 1
        $context['allow_extra_attributes'] = $class === Form::class;
174 1
        return $this->decorated->denormalize($data, $class, $format, $context);
175
    }
176
177
    /**
178
     * @param SerializerInterface $serializer
179
     */
180 5
    public function setSerializer(SerializerInterface $serializer)
181
    {
182 5
        if ($this->decorated instanceof SerializerAwareInterface) {
183 5
            $this->decorated->setSerializer($serializer);
184
        }
185 5
    }
186
187
    /**
188
     * @param string $filePath
189
     * @return bool
190
     */
191 3
    public function isImagineSupportedFile(?string $filePath): bool
192
    {
193 3
        if (!$filePath) {
194
            return false;
195
        }
196
        try {
197 3
            $imageType = \exif_imagetype($filePath);
198 1
        } catch (\Exception $e) {
199 1
            return false;
200
        }
201 3
        return \in_array($imageType, [IMAGETYPE_JPEG, IMAGETYPE_JPEG2000, IMAGETYPE_PNG, IMAGETYPE_GIF], true);
202
    }
203
}
204