Completed
Pull Request — master (#5)
by Bukashk0zzz
03:03 queued 26s
created

JmsPreSerializeListener::onPreSerialize()   C

Complexity

Conditions 10
Paths 16

Size

Total Lines 60
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 60
rs 6.5333
cc 10
eloc 36
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 (
86
            $object instanceof \Doctrine\Common\Persistence\Proxy
87
            && ! $object->__isInitialized()
88
        ) {
89
            $object->__load();
90
        }
91
92
        $objectUid = spl_object_hash($object);
93
        if (in_array($objectUid, $this->serializedObjects)) {
94
            return;
95
        }
96
97
        $classAnnotation = $this->annotationReader->getClassAnnotation(
98
            new \ReflectionClass(ClassUtils::getClass($object)),
99
            VichSerializableClass::class
100
        );
101
102
        if ($classAnnotation instanceof VichSerializableClass) {
103
            $reflectionClass = ClassUtils::newReflectionClass(get_class($object));
104
            $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...
105
106
            foreach ($reflectionClass->getProperties() as $property) {
107
                $vichSerializableAnnotation = $this->annotationReader->getPropertyAnnotation($property, VichSerializableField::class);
108
109
                if ($vichSerializableAnnotation instanceof VichSerializableField) {
110
                    $vichUploadableFileAnnotation = $this->annotationReader->getPropertyAnnotation($property, UploadableField::class);
111
112
                    if ($vichUploadableFileAnnotation instanceof UploadableField) {
113
                        throw new IncompatibleUploadableAndSerializableFieldAnnotationException(sprintf(
114
                            'The field "%s" in the class "%s" cannot have @UploadableField and @VichSerializableField annotations at the same moment.',
115
                            $property->getName(),
116
                            $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...
117
                        ));
118
                    }
119
                    $this->logger->debug(sprintf(
120
                        'Found @VichSerializableField annotation for the field "%s" in the class "%s"',
121
                        $property->getName(),
122
                        $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...
123
                    ));
124
125
                    $uri = null;
126
                    $property->setAccessible(true);
127
128
                    if ($property->getValue($event->getObject())) {
129
                        $uri = $this->storage->resolveUri($object, $vichSerializableAnnotation->getField());
130
                        if ($vichSerializableAnnotation->isIncludeHost()) {
131
                            $uri = $this->getHostUrl().$uri;
132
                        }
133
                    }
134
                    $property->setValue($object, $uri);
135
                }
136
            }
137
138
            $this->serializedObjects[$objectUid] = $objectUid;
139
        }
140
    }
141
142
    /**
143
     * Get host url (scheme, host, port)
144
     *
145
     * @return string Host url
146
     */
147
    private function getHostUrl()
148
    {
149
        $url = $this->requestContext->getScheme().'://'.$this->requestContext->getHost();
150
151
        if ($this->requestContext->getScheme() == 'http' && $this->requestContext->getHttpPort() && $this->requestContext->getHttpPort() != 80) {
152
            $url .= ':'.$this->requestContext->getHttpPort();
153
        } elseif ($this->requestContext->getScheme() == 'https' && $this->requestContext->getHttpsPort() && $this->requestContext->getHttpsPort() != 443) {
154
            $url .= ':'.$this->requestContext->getHttpsPort();
155
        }
156
157
        return $url;
158
    }
159
}
160