Completed
Push — master ( 97e09b...3bcd53 )
by
unknown
02:36
created

ImageProvider::getHelperProperties()   C

Complexity

Conditions 10
Paths 11

Size

Total Lines 63
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 37
nc 11
nop 3
dl 0
loc 63
rs 6.3636
c 0
b 0
f 0

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
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sonata\MediaBundle\Provider;
13
14
use Gaufrette\Filesystem;
15
use Imagine\Image\ImagineInterface;
16
use Sonata\CoreBundle\Model\Metadata;
17
use Sonata\MediaBundle\CDN\CDNInterface;
18
use Sonata\MediaBundle\Generator\GeneratorInterface;
19
use Sonata\MediaBundle\Metadata\MetadataBuilderInterface;
20
use Sonata\MediaBundle\Model\MediaInterface;
21
use Sonata\MediaBundle\Thumbnail\ThumbnailInterface;
22
use Symfony\Component\HttpFoundation\File\File;
23
use Symfony\Component\HttpFoundation\File\UploadedFile;
24
25
class ImageProvider extends FileProvider
26
{
27
    /**
28
     * @var ImagineInterface
29
     */
30
    protected $imagineAdapter;
31
32
    /**
33
     * @param string                   $name
34
     * @param Filesystem               $filesystem
35
     * @param CDNInterface             $cdn
36
     * @param GeneratorInterface       $pathGenerator
37
     * @param ThumbnailInterface       $thumbnail
38
     * @param array                    $allowedExtensions
39
     * @param array                    $allowedMimeTypes
40
     * @param ImagineInterface         $adapter
41
     * @param MetadataBuilderInterface $metadata
42
     */
43
    public function __construct($name, Filesystem $filesystem, CDNInterface $cdn, GeneratorInterface $pathGenerator, ThumbnailInterface $thumbnail, array $allowedExtensions, array $allowedMimeTypes, ImagineInterface $adapter, MetadataBuilderInterface $metadata = null)
44
    {
45
        parent::__construct($name, $filesystem, $cdn, $pathGenerator, $thumbnail, $allowedExtensions, $allowedMimeTypes, $metadata);
46
47
        $this->imagineAdapter = $adapter;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function getProviderMetadata()
54
    {
55
        return new Metadata($this->getName(), $this->getName().'.description', false, 'SonataMediaBundle', ['class' => 'fa fa-picture-o']);
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function getHelperProperties(MediaInterface $media, $format, $options = [])
62
    {
63
        if (MediaProviderInterface::FORMAT_REFERENCE === $format) {
64
            $box = $media->getBox();
65
        } else {
66
            $resizerFormat = $this->getFormat($format);
67
            if (false === $resizerFormat) {
68
                throw new \RuntimeException(sprintf('The image format "%s" is not defined.
69
                        Is the format registered in your ``sonata_media`` configuration?', $format));
70
            }
71
72
            $box = $this->resizer->getBox($media, $resizerFormat);
73
        }
74
75
        $mediaWidth = $box->getWidth();
76
77
        $params = [
78
            'alt' => $media->getName(),
79
            'title' => $media->getName(),
80
            'src' => $this->generatePublicUrl($media, $format),
81
            'width' => $mediaWidth,
82
            'height' => $box->getHeight(),
83
        ];
84
85
        if (MediaProviderInterface::FORMAT_ADMIN !== $format) {
86
            $srcSetFormats = $this->getFormats();
87
88
            if (isset($options['srcset']) && is_array($options['srcset'])) {
89
                $srcSetFormats = [];
90
                foreach ($options['srcset'] as $srcSetFormat) {
91
                    $formatName = $this->getFormatName($media, $srcSetFormat);
92
                    $srcSetFormats[$formatName] = $this->getFormat($formatName);
93
                }
94
                unset($options['srcset']);
95
            }
96
97
            if (!isset($options['srcset'])) {
98
                $srcSet = [];
99
100
                foreach ($srcSetFormats as $providerFormat => $settings) {
101
                    // Check if format belongs to the current media's context
102
                    if (0 === strpos($providerFormat, $media->getContext())) {
103
                        $width = $this->resizer->getBox($media, $settings)->getWidth();
104
105
                        $srcSet[] = sprintf('%s %dw', $this->generatePublicUrl($media, $providerFormat), $width);
106
                    }
107
                }
108
109
                // The reference format is not in the formats list
110
                $srcSet[] = sprintf(
111
                    '%s %dw',
112
                    $this->generatePublicUrl($media, MediaProviderInterface::FORMAT_REFERENCE),
113
                    $media->getBox()->getWidth()
114
                );
115
116
                $params['srcset'] = implode(', ', $srcSet);
117
            }
118
119
            $params['sizes'] = sprintf('(max-width: %1$dpx) 100vw, %1$dpx', $mediaWidth);
120
        }
121
122
        return array_merge($params, $options);
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128
    public function getReferenceImage(MediaInterface $media)
129
    {
130
        return sprintf('%s/%s',
131
            $this->generatePath($media),
132
            $media->getProviderReference()
133
        );
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139
    public function updateMetadata(MediaInterface $media, $force = true)
140
    {
141
        try {
142
            if (!$media->getBinaryContent() instanceof \SplFileInfo) {
143
                // this is now optimized at all!!!
144
                $path = tempnam(sys_get_temp_dir(), 'sonata_update_metadata');
145
                $fileObject = new \SplFileObject($path, 'w');
146
                $fileObject->fwrite($this->getReferenceFile($media)->getContent());
147
            } else {
148
                $fileObject = $media->getBinaryContent();
149
            }
150
151
            $image = $this->imagineAdapter->open($fileObject->getPathname());
152
            $size = $image->getSize();
153
154
            $media->setSize($fileObject->getSize());
155
            $media->setWidth($size->getWidth());
156
            $media->setHeight($size->getHeight());
157
        } catch (\LogicException $e) {
158
            $media->setProviderStatus(MediaInterface::STATUS_ERROR);
159
160
            $media->setSize(0);
161
            $media->setWidth(0);
162
            $media->setHeight(0);
163
        }
164
    }
165
166
    /**
167
     * {@inheritdoc}
168
     */
169
    public function generatePublicUrl(MediaInterface $media, $format)
170
    {
171
        if (MediaProviderInterface::FORMAT_REFERENCE === $format) {
172
            $path = $this->getReferenceImage($media);
173
        } else {
174
            $path = $this->thumbnail->generatePublicUrl($this, $media, $format);
175
        }
176
177
        return $this->getCdn()->getPath($path, $media->getCdnIsFlushable());
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183
    public function generatePrivateUrl(MediaInterface $media, $format)
184
    {
185
        return $this->thumbnail->generatePrivateUrl($this, $media, $format);
186
    }
187
188
    /**
189
     * {@inheritdoc}
190
     */
191
    protected function doTransform(MediaInterface $media)
192
    {
193
        parent::doTransform($media);
194
195
        if ($media->getBinaryContent() instanceof UploadedFile) {
196
            $fileName = $media->getBinaryContent()->getClientOriginalName();
197
        } elseif ($media->getBinaryContent() instanceof File) {
198
            $fileName = $media->getBinaryContent()->getFilename();
199
        } else {
200
            // Should not happen, FileProvider should throw an exception in that case
201
            return;
202
        }
203
204
        if (!in_array(strtolower(pathinfo($fileName, PATHINFO_EXTENSION)), $this->allowedExtensions)
205
            || !in_array($media->getBinaryContent()->getMimeType(), $this->allowedMimeTypes)) {
206
            return;
207
        }
208
209
        try {
210
            $image = $this->imagineAdapter->open($media->getBinaryContent()->getPathname());
211
        } catch (\RuntimeException $e) {
212
            $media->setProviderStatus(MediaInterface::STATUS_ERROR);
213
214
            return;
215
        }
216
217
        $size = $image->getSize();
218
219
        $media->setWidth($size->getWidth());
220
        $media->setHeight($size->getHeight());
221
222
        $media->setProviderStatus(MediaInterface::STATUS_OK);
223
    }
224
}
225