JmsSerializeListenerAbstract   A
last analyzed

Complexity

Total Complexity 34

Size/Duplication

Total Lines 186
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 34
lcom 1
cbo 8
dl 0
loc 186
rs 9.68
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
A getObject() 0 12 3
B serializeValue() 0 34 10
B getHostUrl() 0 12 7
A normalizeUrl() 0 14 4
A prepareFilteredUrl() 0 8 3
A stripHostFromUrl() 0 9 4
A addPreNormalizeUrlEvent() 0 12 2
1
<?php declare(strict_types = 1);
2
/*
3
 * This file is part of the Bukashk0zzzLiipImagineSerializationBundle
4
 *
5
 * (c) Denis Golubovskiy <[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 Bukashk0zzz\LiipImagineSerializationBundle\EventListener;
12
13
use Bukashk0zzz\LiipImagineSerializationBundle\Annotation\LiipImagineSerializableField;
14
use Bukashk0zzz\LiipImagineSerializationBundle\Event\UrlNormalizerEvent;
15
use Bukashk0zzz\LiipImagineSerializationBundle\Normalizer\UrlNormalizerInterface;
16
use Doctrine\Common\Annotations\CachedReader;
17
use Doctrine\Common\Persistence\Proxy;
18
use JMS\Serializer\EventDispatcher\ObjectEvent;
19
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
20
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
21
use Symfony\Component\Routing\RequestContext;
22
use Vich\UploaderBundle\Storage\StorageInterface;
23
24
/**
25
 * JmsSerializeListenerAbstract
26
 */
27
class JmsSerializeListenerAbstract
28
{
29
    /**
30
     * @var RequestContext Request context
31
     */
32
    protected $requestContext;
33
34
    /**
35
     * @var CachedReader Cached annotation reader
36
     */
37
    protected $annotationReader;
38
39
    /**
40
     * @var CacheManager LiipImagineBundle Cache Manager
41
     */
42
    protected $cacheManager;
43
44
    /**
45
     * @var StorageInterface Vich storage
46
     */
47
    protected $vichStorage;
48
49
    /**
50
     * @var EventDispatcherInterface
51
     */
52
    protected $eventDispatcher;
53
54
    /**
55
     * @var mixed[] Bundle config
56
     */
57
    protected $config;
58
59
    /**
60
     * JmsSerializeListenerAbstract constructor.
61
     *
62
     * @param mixed[] $config
63
     */
64
    public function __construct(
65
        RequestContext $requestContext,
66
        CachedReader $annotationReader,
67
        CacheManager $cacheManager,
68
        StorageInterface $vichStorage,
69
        EventDispatcherInterface $eventDispatcher,
70
        array $config
71
    ) {
72
        $this->requestContext = $requestContext;
73
        $this->annotationReader = $annotationReader;
74
        $this->cacheManager = $cacheManager;
75
        $this->vichStorage = $vichStorage;
76
        $this->eventDispatcher = $eventDispatcher;
77
        $this->config = $config;
78
    }
79
80
    /**
81
     * @param ObjectEvent $event Event
82
     *
83
     * @return mixed
84
     */
85
    protected function getObject(ObjectEvent $event)
86
    {
87
        $object = $event->getObject();
88
89
        if ($object instanceof Proxy
0 ignored issues
show
Bug introduced by
The class Doctrine\Common\Persistence\Proxy does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
90
            && !$object->__isInitialized()
91
        ) {
92
            $object->__load();
93
        }
94
95
        return $object;
96
    }
97
98
    /**
99
     * @param mixed  $object Serialized object
100
     * @param string $value  Value of field
101
     *
102
     * @return mixed[]|string
103
     */
104
    protected function serializeValue(LiipImagineSerializableField $liipAnnotation, $object, $value)
105
    {
106
        $vichField = $liipAnnotation->getVichUploaderField();
107
        if ($vichField !== null) {
108
            $value = $this->vichStorage->resolveUri($object, $vichField);
109
        }
110
111
        $result = [];
112
        $value = $this->normalizeUrl($value, UrlNormalizerInterface::TYPE_ORIGIN);
113
        if (\array_key_exists('includeOriginal', $this->config) && $this->config['includeOriginal']) {
114
            $result['original'] = (\array_key_exists('includeHostForOriginal', $this->config) && $this->config['includeHostForOriginal'] && $liipAnnotation->getVichUploaderField())
115
                ? $this->getHostUrl().$value
116
                : $value;
117
        }
118
119
        $filters = $liipAnnotation->getFilter();
120
        if (\is_array($filters)) {
121
            /** @var array $filters */
122
            foreach ($filters as $filter) {
123
                $result[$filter] = $this->prepareFilteredUrl($this->cacheManager->getBrowserPath($value, $filter));
124
            }
125
126
            return $result;
127
        }
128
129
        $filtered = $this->cacheManager->getBrowserPath($value, $filters);
130
        if (\count($result) !== 0) {
131
            $result[$filters] = $this->prepareFilteredUrl($filtered);
132
133
            return $result;
134
        }
135
136
        return $filtered;
137
    }
138
139
    /**
140
     * Get host url (scheme, host, port)
141
     *
142
     * @return string Host url
143
     */
144
    protected function getHostUrl(): string
145
    {
146
        $url = $this->requestContext->getScheme().'://'.$this->requestContext->getHost();
147
148
        if ($this->requestContext->getScheme() === 'http' && $this->requestContext->getHttpPort() && $this->requestContext->getHttpPort() !== 80) {
149
            $url .= ':'.$this->requestContext->getHttpPort();
150
        } elseif ($this->requestContext->getScheme() === 'https' && $this->requestContext->getHttpsPort() && $this->requestContext->getHttpsPort() !== 443) {
151
            $url .= ':'.$this->requestContext->getHttpsPort();
152
        }
153
154
        return $url;
155
    }
156
157
    /**
158
     * Normalize url if needed
159
     */
160
    protected function normalizeUrl(string $url, string $normalizer): string
161
    {
162
        $url = $this->addPreNormalizeUrlEvent($normalizer, $url);
163
164
        if (\array_key_exists($normalizer, $this->config) && $this->config[$normalizer]) {
165
            $normalizerClassName = $this->config[$normalizer];
166
            $normalizer = new $normalizerClassName();
167
            if ($normalizer instanceof UrlNormalizerInterface) {
168
                $url = $normalizer->normalize($url);
169
            }
170
        }
171
172
        return $url;
173
    }
174
175
    /**
176
     * If config demands, it will remove host and scheme (protocol) from passed url
177
     */
178
    private function prepareFilteredUrl(string $url): string
179
    {
180
        if (\array_key_exists('includeHost', $this->config) && !$this->config['includeHost']) {
181
            $url = $this->stripHostFromUrl($url);
182
        }
183
184
        return $this->normalizeUrl($url, UrlNormalizerInterface::TYPE_FILTERED);
185
    }
186
187
    /**
188
     * Removes host and scheme (protocol) from passed url
189
     */
190
    private function stripHostFromUrl(string $url): string
191
    {
192
        $parts = \parse_url($url);
193
        if ($parts !== false && \array_key_exists('path', $parts)) {
194
            return \array_key_exists('query', $parts) ? $parts['path'].'?'.$parts['query'] : $parts['path'];
195
        }
196
197
        throw new \InvalidArgumentException('Can\'t strip host from url, because can\'t parse url.');
198
    }
199
200
    private function addPreNormalizeUrlEvent(string $type, string $url): string
201
    {
202
        /** @var UrlNormalizerEvent $event */
203
        $event = $this->eventDispatcher->dispatch(
204
            new UrlNormalizerEvent($url),
0 ignored issues
show
Documentation introduced by
new \Bukashk0zzz\LiipIma...rlNormalizerEvent($url) is of type object<Bukashk0zzz\LiipI...ent\UrlNormalizerEvent>, but the function expects a object<Symfony\Contracts\EventDispatcher\object>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
205
            $type === UrlNormalizerInterface::TYPE_ORIGIN
206
                ? UrlNormalizerEvent::ORIGIN
207
                : UrlNormalizerEvent::FILTERED
208
        );
209
210
        return $event->getUrl();
211
    }
212
}
213