Passed
Push — develop ( 69ffd6...9486de )
by Daniel
08:05
created

ApiNormalizer::supportsDenormalization()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 3
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Silverback\ApiComponentBundle\Serializer;
4
5
use ApiPlatform\Core\DataProvider\ContextAwareCollectionDataProviderInterface;
6
use Doctrine\ORM\EntityManagerInterface;
7
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
8
use Silverback\ApiComponentBundle\Entity\Content\Component\AbstractComponent;
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 || $object instanceof AbstractDynamicPage) && !$object->getLayout()) {
87
            // Should we be using the ItemDataProvider (or detect data provider and use that, we already use a custom data provider for layouts)
88
            $object->setLayout($this->em->getRepository(Layout::class)->findOneBy(['default' => true]));
89
        }
90 6
        if ($object instanceof AbstractDynamicPage) {
91
            $object = $this->populateDynamicComponents($object);
92
        }
93 6
        if ($object instanceof Collection) {
94
            // We should really find whatever the data provider is currently for the resource instead of just using the default
95
            $object->setCollection($this->collectionDataProvider->getCollection($object->getResource(), 'GET', $context));
96
        }
97 6
        if ($object instanceof Form && !$object->getForm()) {
98 1
            $object->setForm($this->formViewFactory->create($object));
99
        }
100 6
        $data = $this->decorated->normalize($object, $format, $context);
101
102 6
        if ($object instanceof FileInterface) {
103 1
            $data = array_merge($data, $this->getFileData($object));
104
        }
105 6
        return $data;
106
    }
107
108
    /**
109
     * @param \Silverback\ApiComponentBundle\Entity\Content\FileInterface $object
110
     * @return array
111
     */
112 1
    private function getFileData(FileInterface $object): array
113
    {
114 1
        $data = [];
115 1
        $filePath = $object->getFilePath();
116 1
        if ($filePath) {
117 1
            if (false !== \exif_imagetype($filePath)) {
118 1
                [$width, $height] = getimagesize($filePath);
119
            } else {
120
                $width = $height = 0;
121
            }
122 1
            $data['width'] = $width;
123 1
            $data['height'] = $height;
124
125 1
            $supported = $this->isImagineSupportedFile($filePath);
126 1
            foreach ($object::getImagineFilters() as $returnKey => $filter) {
127 1
                $data[$returnKey] = $supported ? parse_url(
128 1
                    $this->imagineCacheManager->getBrowserPath($this->pathResolver->resolve($filePath), $filter),
129 1
                    PHP_URL_PATH
130 1
                ) : null;
131
            }
132
133 1
            $data['filePath'] = $this->getPublicPath($filePath);
134
        }
135 1
        return $data;
136
    }
137
138 1
    private function getPublicPath(string $filePath) {
139 1
        $publicPaths = [$this->projectDir, '/public/', '/web/'];
140 1
        foreach ($publicPaths as $path) {
141 1
            if (mb_strpos($filePath, $path) === 0 && $start = \strlen($path)) {
142 1
                $filePath = mb_substr($filePath, $start);
143
            }
144
        }
145 1
        return $filePath;
146
    }
147
148
    /**
149
     * @param mixed $data
150
     * @param string $type
151
     * @param string|null $format
152
     * @return bool
153
     */
154 5
    public function supportsDenormalization($data, $type, $format = null): bool
155
    {
156 5
        return $this->decorated->supportsDenormalization($data, $type, $format);
157
    }
158
159
    /**
160
     * @param mixed $data
161
     * @param string $class
162
     * @param string|null $format
163
     * @param array $context
164
     * @return object
165
     * @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
166
     * @throws \Symfony\Component\Serializer\Exception\RuntimeException
167
     * @throws \Symfony\Component\Serializer\Exception\LogicException
168
     * @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException
169
     * @throws \Symfony\Component\Serializer\Exception\ExtraAttributesException
170
     * @throws \Symfony\Component\Serializer\Exception\BadMethodCallException
171
     * @throws \InvalidArgumentException
172
     */
173 1
    public function denormalize($data, $class, $format = null, array $context = [])
174
    {
175 1
        $context['allow_extra_attributes'] = $class === Form::class;
176 1
        return $this->decorated->denormalize($data, $class, $format, $context);
177
    }
178
179
    /**
180
     * @param SerializerInterface $serializer
181
     */
182 5
    public function setSerializer(SerializerInterface $serializer)
183
    {
184 5
        if ($this->decorated instanceof SerializerAwareInterface) {
185 5
            $this->decorated->setSerializer($serializer);
186
        }
187 5
    }
188
189
    /**
190
     * @param string $filePath
191
     * @return bool
192
     */
193 3
    public function isImagineSupportedFile(?string $filePath): bool
194
    {
195 3
        if (!$filePath) {
196
            return false;
197
        }
198
        try {
199 3
            $imageType = \exif_imagetype($filePath);
200 1
        } catch (\Exception $e) {
201 1
            return false;
202
        }
203 3
        return \in_array($imageType, [IMAGETYPE_JPEG, IMAGETYPE_JPEG2000, IMAGETYPE_PNG, IMAGETYPE_GIF], true);
204
    }
205
206
    private function populateDynamicComponents(AbstractDynamicPage $page): AbstractDynamicPage
207
    {
208
        $components = $this->em->getRepository(AbstractComponent::class)->findByDynamicPage($page);
209
        foreach($components as $component)
210
        {
211
            $page->addComponentLocation(new ComponentLocation(null, $component));
212
        }
213
        return $page;
214
    }
215
}
216