Completed
Pull Request — master (#2680)
by
unknown
06:45
created

MediaManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 6
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 4
crap 2
1
<?php
2
3
namespace Kunstmaan\MediaBundle\Helper;
4
5
use Kunstmaan\MediaBundle\Entity\Media;
6
use Kunstmaan\MediaBundle\Helper\Media\AbstractMediaHandler;
7
use Symfony\Component\HttpFoundation\File\File;
8
use Symfony\Component\HttpFoundation\File\UploadedFile;
9
use Symfony\Component\Mime\MimeTypesInterface;
10
use Symfony\Component\Validator\Constraints\Image;
11
use Symfony\Component\Validator\Validator\ValidatorInterface;
12
13
/**
14
 * MediaManager
15
 */
16
class MediaManager
17
{
18
    private const IMAGE_MIMETYPE_REGEX = '/^image\/.*$/m';
19
20
    /**
21
     * @var AbstractMediaHandler[]
22
     */
23
    protected $handlers = [];
24
25
    /**
26
     * @var AbstractMediaHandler
27
     */
28
    protected $defaultHandler;
29
30
    /** @var MimeTypesInterface */
31
    private $mimeTypes;
32
33
    /** @var ValidatorInterface */
34
    private $validator;
35
36
    /** @var array */
37
    private $allowedExtensions;
38
39
    /** @var bool */
40
    private $limitAllowedExtesions;
41
42
    public function __construct(MimeTypesInterface $mimeTypes, ValidatorInterface $validator, array $allowedExtensions, bool $limitAllowedExtensions = true)
43
    {
44
        $this->mimeTypes = $mimeTypes;
45
        $this->validator = $validator;
46
        $this->allowedExtensions = $allowedExtensions;
47
        $this->limitAllowedExtesions = $limitAllowedExtensions;
48
    }
49
50
    /**
51
     * @param AbstractMediaHandler $handler Media handler
52
     *
53
     * @return MediaManager
54
     */
55
    public function addHandler(AbstractMediaHandler $handler)
56
    {
57
        $this->handlers[$handler->getName()] = $handler;
58
59
        return $this;
60
    }
61
62
    /**
63
     * @param AbstractMediaHandler $handler Media handler
64
     *
65
     * @return MediaManager
66
     */
67
    public function setDefaultHandler(AbstractMediaHandler $handler)
68
    {
69
        $this->defaultHandler = $handler;
70
71
        return $this;
72
    }
73
74
    /**
75
     * Returns handler with the highest priority to handle the Media item based on the Type. If no handler is found, it returns FileHandler
76
     *
77
     * @param string $type
78
     *
79
     * @return AbstractMediaHandler
80
     */
81
    public function getHandlerForType($type)
82
    {
83
        $bestHandler = $this->defaultHandler;
84
        foreach ($this->handlers as $handler) {
85
            if ($handler->getType() == $type && $handler->getPriority() > $bestHandler->getPriority()) {
86
                $bestHandler = $handler;
87
            }
88
        }
89
90
        return $bestHandler;
91
    }
92
93
    /**
94
     * @return AbstractMediaHandler[]
95
     */
96
    public function getHandlers()
97
    {
98
        return $this->handlers;
99
    }
100
101
    /**
102
     * @return MediaManager
103
     */
104
    public function prepareMedia(Media $media)
105
    {
106
        $handler = $this->getHandler($media);
107
        $handler->prepareMedia($media);
108
109
        return $this;
110
    }
111
112
    /**
113
     * Returns handler with the highest priority to handle the Media item which can handle the item. If no handler is found, it returns FileHandler
114
     *
115
     * @param Media|File $media
116
     *
117
     * @return AbstractMediaHandler
118
     */
119
    public function getHandler($media)
120
    {
121
        $bestHandler = $this->defaultHandler;
122
        foreach ($this->handlers as $handler) {
123
            if ($handler->canHandle($media) && $handler->getPriority() > $bestHandler->getPriority()) {
124
                $bestHandler = $handler;
125
            }
126
        }
127
128
        return $bestHandler;
129
    }
130
131
    /**
132
     * @param Media $media The media
133
     * @param bool  $new   Is new
134
     */
135
    public function saveMedia(Media $media, $new = false)
136
    {
137
        $handler = $this->getHandler($media);
138
139
        if ($new) {
140
            $handler->saveMedia($media);
141
        } else {
142
            $handler->updateMedia($media);
143
        }
144
    }
145
146
    public function removeMedia(Media $media)
147
    {
148
        $handler = $this->getHandler($media);
149
        $handler->removeMedia($media);
150
    }
151
152
    /**
153
     * @param mixed $data
154
     *
155
     * @return mixed
156
     */
157
    public function createNew($data)
158
    {
159
        if ($this->isExtensionAllowed($data)) {
160
            foreach ($this->handlers as $handler) {
161
                $result = $handler->createNew($data);
162
                if ($result) {
163
                    return $result;
164
                }
165
            }
166
        }
167
168
        return null;
169
    }
170
171
    public function isExtensionAllowed(File $file): bool
172
    {
173
        if (!$this->limitAllowedExtesions) {
174
            return true;
175
        }
176
177
        $mimeType = $this->mimeTypes->guessMimeType($file->getRealPath());
178
        if ($mimeType === 'text/plain' && $file instanceof UploadedFile) {
179
            $mimeType = $file->getClientMimeType();
180
        }
181
        $extensions = $this->mimeTypes->getExtensions($mimeType);
182
        $extension = array_shift($extensions);
183
        if (!in_array($extension, $this->allowedExtensions, true)) {
184
            return false;
185
        }
186
187
        if (1 === preg_match(self::IMAGE_MIMETYPE_REGEX, $mimeType)) {
188
            return 0 === $this->validator->validate($file, new Image(['detectCorrupted' => true]))->count();
189
        }
190
191
        return true;
192
    }
193
194
    /**
195
     * @return array
196
     */
197
    public function getFolderAddActions()
198
    {
199
        $result = [];
200
        foreach ($this->handlers as $handler) {
201
            $actions = $handler->getAddFolderActions();
202
            if ($actions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $actions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
203
                $result = array_merge($actions, $result);
204
            }
205
        }
206
207
        return $result;
208
    }
209
}
210