Completed
Push — master ( 0d1123...046206 )
by Artem
17s queued 10s
created

JmsSerializerSubscriber   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 157
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 25
lcom 1
cbo 11
dl 0
loc 157
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A getSubscribedEvents() 0 7 1
A onPostSerialize() 0 18 5
B getHostUrl() 0 17 7
C onPreSerialize() 0 59 11
1
<?php
2
/*
3
 * This file is part of the FreshVichUploaderSerializationBundle
4
 *
5
 * (c) Artem Henvald <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Fresh\VichUploaderSerializationBundle\EventListener;
14
15
use Doctrine\Common\Annotations\Reader;
16
use Doctrine\Common\Persistence\Proxy;
17
use Doctrine\Common\Util\ClassUtils;
18
use Fresh\VichUploaderSerializationBundle\Annotation\VichSerializableClass;
19
use Fresh\VichUploaderSerializationBundle\Annotation\VichSerializableField;
20
use Fresh\VichUploaderSerializationBundle\Exception\IncompatibleUploadableAndSerializableFieldAnnotationException;
21
use JMS\Serializer\EventDispatcher\Events;
22
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
23
use JMS\Serializer\EventDispatcher\ObjectEvent;
24
use JMS\Serializer\EventDispatcher\PreSerializeEvent;
25
use Psr\Log\LoggerInterface;
26
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
27
use Symfony\Component\Routing\RequestContext;
28
use Vich\UploaderBundle\Mapping\Annotation\UploadableField;
29
use Vich\UploaderBundle\Storage\StorageInterface;
30
31
/**
32
 * JmsPreSerializeListener Class.
33
 *
34
 * @author Artem Henvald <[email protected]>
35
 */
36
class JmsSerializerSubscriber implements EventSubscriberInterface
37
{
38
    /** @var StorageInterface */
39
    private $storage;
40
41
    /** @var RequestContext */
42
    private $requestContext;
43
44
    /** @var Reader */
45
    private $annotationReader;
46
47
    /** @var PropertyAccessorInterface */
48
    private $propertyAccessor;
49
50
    /** @var LoggerInterface */
51
    private $logger;
52
53
    /** @var array */
54
    private $serializedObjects = [];
55
56
    /**
57
     * @param StorageInterface          $storage
58
     * @param RequestContext            $requestContext
59
     * @param Reader                    $annotationReader
60
     * @param PropertyAccessorInterface $propertyAccessor
61
     * @param LoggerInterface           $logger
62
     */
63
    public function __construct(StorageInterface $storage, RequestContext $requestContext, Reader $annotationReader, PropertyAccessorInterface $propertyAccessor, LoggerInterface $logger)
64
    {
65
        $this->storage = $storage;
66
        $this->requestContext = $requestContext;
67
        $this->annotationReader = $annotationReader;
68
        $this->propertyAccessor = $propertyAccessor;
69
        $this->logger = $logger;
70
    }
71
72
    /**
73
     * @return array
74
     */
75
    public static function getSubscribedEvents(): array
76
    {
77
        return [
78
            ['event' => Events::PRE_SERIALIZE, 'method' => 'onPreSerialize'],
79
            ['event' => Events::POST_SERIALIZE, 'method' => 'onPostSerialize'],
80
        ];
81
    }
82
83
    /**
84
     * @param PreSerializeEvent $event
85
     *
86
     * @throws IncompatibleUploadableAndSerializableFieldAnnotationException
87
     */
88
    public function onPreSerialize(PreSerializeEvent $event): void
89
    {
90
        $object = $event->getObject();
91
92
        if ($object instanceof Proxy && !$object->__isInitialized()) {
93
            $object->__load();
94
        }
95
96
        $objectUid = \spl_object_hash($object);
97
        if (\array_key_exists($objectUid, $this->serializedObjects)) {
98
            return;
99
        }
100
101
        $classAnnotation = $this->annotationReader->getClassAnnotation(
102
            new \ReflectionClass(ClassUtils::getClass($object)),
103
            VichSerializableClass::class
104
        );
105
106
        if ($classAnnotation instanceof VichSerializableClass) {
107
            $reflectionClass = ClassUtils::newReflectionClass(\get_class($object));
108
            $this->logger->debug(\sprintf(
109
                'Found @VichSerializableClass annotation for the class "%s"',
110
                $reflectionClass->getName()
0 ignored issues
show
Bug introduced by
Consider using $reflectionClass->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
111
            ));
112
113
            foreach ($reflectionClass->getProperties() as $property) {
114
                $vichSerializableAnnotation = $this->annotationReader->getPropertyAnnotation($property, VichSerializableField::class);
115
116
                if ($vichSerializableAnnotation instanceof VichSerializableField) {
117
                    $vichUploadableFileAnnotation = $this->annotationReader->getPropertyAnnotation($property, UploadableField::class);
118
119
                    if ($vichUploadableFileAnnotation instanceof UploadableField) {
120
                        throw new IncompatibleUploadableAndSerializableFieldAnnotationException(\sprintf(
121
                            'The field "%s" in the class "%s" cannot have @UploadableField and @VichSerializableField annotations at the same moment.',
122
                            $property->getName(),
123
                            $reflectionClass->getName()
0 ignored issues
show
Bug introduced by
Consider using $reflectionClass->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
124
                        ));
125
                    }
126
                    $this->logger->debug(\sprintf(
127
                        'Found @VichSerializableField annotation for the field "%s" in the class "%s"',
128
                        $property->getName(),
129
                        $reflectionClass->getName()
0 ignored issues
show
Bug introduced by
Consider using $reflectionClass->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
130
                    ));
131
132
                    $uri = null;
133
                    $property->setAccessible(true);
134
135
                    if ($property->getValue($event->getObject())) {
136
                        $uri = $this->storage->resolveUri($object, $vichSerializableAnnotation->getField());
137
                        if ($vichSerializableAnnotation->isIncludeHost() && false === \filter_var($uri, FILTER_VALIDATE_URL)) {
138
                            $uri = $this->getHostUrl().$uri;
139
                        }
140
                    }
141
                    $this->serializedObjects[$objectUid][$property->getName()] = $property->getValue($event->getObject());
142
                    $property->setValue($object, $uri);
143
                }
144
            }
145
        }
146
    }
147
148
    /**
149
     * @param ObjectEvent $event
150
     */
151
    public function onPostSerialize(ObjectEvent $event): void
152
    {
153
        $object = $event->getObject();
154
155
        if ($object instanceof Proxy && !$object->__isInitialized()) {
156
            $object->__load();
157
        }
158
159
        $objectUid = \spl_object_hash($object);
160
        if (!\array_key_exists($objectUid, $this->serializedObjects)) {
161
            return;
162
        }
163
164
        foreach ($this->serializedObjects[$objectUid] as $propertyName => $propertyValue) {
165
            $this->propertyAccessor->setValue($object, $propertyName, $propertyValue);
166
        }
167
        unset($this->serializedObjects[$objectUid]);
168
    }
169
170
    /**
171
     * Get host url (scheme://host:port).
172
     *
173
     * @return string
174
     */
175
    private function getHostUrl(): string
176
    {
177
        $scheme = $this->requestContext->getScheme();
178
        $url = $scheme.'://'.$this->requestContext->getHost();
179
180
        $httpPort = $this->requestContext->getHttpPort();
181
        if ('http' === $scheme && $httpPort && 80 !== $httpPort) {
182
            return $url.':'.$httpPort;
183
        }
184
185
        $httpsPort = $this->requestContext->getHttpsPort();
186
        if ('https' === $scheme && $httpsPort && 443 !== $httpsPort) {
187
            return $url.':'.$httpsPort;
188
        }
189
190
        return $url;
191
    }
192
}
193