Completed
Push — master ( 992272...53e0af )
by Artem
07:29
created

JmsPreSerializeListener::onPreSerialize()   C

Complexity

Conditions 10
Paths 16

Size

Total Lines 59
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 2 Features 1
Metric Value
c 4
b 2
f 1
dl 0
loc 59
rs 6.5919
cc 10
eloc 35
nc 16
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * This file is part of the FreshVichUploaderSerializationBundle
4
 *
5
 * (c) Artem Genvald <[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
namespace Fresh\VichUploaderSerializationBundle\EventListener;
12
13
use Doctrine\Common\Annotations\CachedReader;
14
use Doctrine\Common\Util\ClassUtils;
15
use Fresh\VichUploaderSerializationBundle\Annotation\VichSerializableField;
16
use Fresh\VichUploaderSerializationBundle\Annotation\VichSerializableClass;
17
use Fresh\VichUploaderSerializationBundle\Exception\IncompatibleUploadableAndSerializableFieldAnnotationException;
18
use JMS\Serializer\EventDispatcher\ObjectEvent;
19
use Monolog\Logger;
20
use Symfony\Component\Routing\RequestContext;
21
use Vich\UploaderBundle\Mapping\Annotation\UploadableField;
22
use Vich\UploaderBundle\Storage\StorageInterface;
23
24
/**
25
 * Class JmsPreSerializeListener
26
 *
27
 * @author Artem Genvald <[email protected]>
28
 */
29
class JmsPreSerializeListener
30
{
31
    /**
32
     * @var StorageInterface $storage Vich storage
33
     */
34
    private $storage;
35
36
    /**
37
     * @var RequestContext $requestContext Request context
38
     */
39
    private $requestContext;
40
41
    /**
42
     * @var CachedReader $annotationReader Cached annotation reader
43
     */
44
    private $annotationReader;
45
46
    /**
47
     * @var Logger $logger Logger
48
     */
49
    private $logger;
50
51
    /**
52
     * @var array $serializedObjects Serialized objects
53
     */
54
    private $serializedObjects = [];
55
56
    /**
57
     * Constructor
58
     *
59
     * @param StorageInterface $storage          Vich storage
60
     * @param RequestContext   $requestContext   Request context
61
     * @param CachedReader     $annotationReader Cached annotation reader
62
     * @param Logger           $logger           Logger
63
     */
64
    public function __construct(
65
        StorageInterface $storage,
66
        RequestContext $requestContext,
67
        CachedReader $annotationReader,
68
        Logger $logger
69
    ) {
70
        $this->storage          = $storage;
71
        $this->requestContext   = $requestContext;
72
        $this->annotationReader = $annotationReader;
73
        $this->logger           = $logger;
74
    }
75
76
    /**
77
     * On pre serialize
78
     *
79
     * @param ObjectEvent $event Event
80
     */
81
    public function onPreSerialize(ObjectEvent $event)
82
    {
83
        $object = $event->getObject();
84
85
        if ($object instanceof \Doctrine\Common\Persistence\Proxy
86
            && ! $object->__isInitialized()
87
        ) {
88
            $object->__load();
89
        }
90
91
        $objectUid = spl_object_hash($object);
92
        if (in_array($objectUid, $this->serializedObjects)) {
93
            return;
94
        }
95
96
        $classAnnotation = $this->annotationReader->getClassAnnotation(
97
            new \ReflectionClass(ClassUtils::getClass($object)),
98
            VichSerializableClass::class
99
        );
100
101
        if ($classAnnotation instanceof VichSerializableClass) {
102
            $reflectionClass = ClassUtils::newReflectionClass(get_class($object));
103
            $this->logger->debug(sprintf('Found @VichSerializableClass annotation for the class "%s"', $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...
104
105
            foreach ($reflectionClass->getProperties() as $property) {
106
                $vichSerializableAnnotation = $this->annotationReader->getPropertyAnnotation($property, VichSerializableField::class);
107
108
                if ($vichSerializableAnnotation instanceof VichSerializableField) {
109
                    $vichUploadableFileAnnotation = $this->annotationReader->getPropertyAnnotation($property, UploadableField::class);
110
111
                    if ($vichUploadableFileAnnotation instanceof UploadableField) {
112
                        throw new IncompatibleUploadableAndSerializableFieldAnnotationException(sprintf(
113
                            'The field "%s" in the class "%s" cannot have @UploadableField and @VichSerializableField annotations at the same moment.',
114
                            $property->getName(),
115
                            $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...
116
                        ));
117
                    }
118
                    $this->logger->debug(sprintf(
119
                        'Found @VichSerializableField annotation for the field "%s" in the class "%s"',
120
                        $property->getName(),
121
                        $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...
122
                    ));
123
124
                    $uri = null;
125
                    $property->setAccessible(true);
126
127
                    if ($property->getValue($event->getObject())) {
128
                        $uri = $this->storage->resolveUri($object, $vichSerializableAnnotation->getField());
129
                        if ($vichSerializableAnnotation->isIncludeHost()) {
130
                            $uri = $this->getHostUrl().$uri;
131
                        }
132
                    }
133
                    $property->setValue($object, $uri);
134
                }
135
            }
136
137
            $this->serializedObjects[$objectUid] = $objectUid;
138
        }
139
    }
140
141
    /**
142
     * Get host url (scheme, host, port)
143
     *
144
     * @return string Host url
145
     */
146
    private function getHostUrl()
147
    {
148
        $url = $this->requestContext->getScheme().'://'.$this->requestContext->getHost();
149
150
        if ($this->requestContext->getScheme() == 'http' && $this->requestContext->getHttpPort() && $this->requestContext->getHttpPort() != 80) {
151
            $url .= ':'.$this->requestContext->getHttpPort();
152
        } elseif ($this->requestContext->getScheme() == 'https' && $this->requestContext->getHttpsPort() && $this->requestContext->getHttpsPort() != 443) {
153
            $url .= ':'.$this->requestContext->getHttpsPort();
154
        }
155
156
        return $url;
157
    }
158
}
159