Completed
Push — master ( 7bf4c8...5aa9d3 )
by dan
11s
created

Uploader::upload()   B

Complexity

Conditions 8
Paths 16

Size

Total Lines 53
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 7.1199
c 0
b 0
f 0
cc 8
eloc 27
nc 16
nop 1

How to fix   Long Method   

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 IrishDan\ResponsiveImageBundle package.
4
 *
5
 * (c) Daniel Byrne <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE file that was distributed with this source
8
 * code.
9
 */
10
11
namespace IrishDan\ResponsiveImageBundle;
12
13
use IrishDan\ResponsiveImageBundle\Event\UploaderEvent;
14
use IrishDan\ResponsiveImageBundle\Event\UploaderEvents;
15
use IrishDan\ResponsiveImageBundle\File\FilenameTransliteratorInterface;
16
use IrishDan\ResponsiveImageBundle\File\FileValidatorInterface;
17
use IrishDan\ResponsiveImageBundle\FileSystem\PrimaryFileSystemWrapper;
18
use League\Flysystem\AdapterInterface;
19
use League\Flysystem\FilesystemInterface;
20
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
21
use Symfony\Component\HttpFoundation\File\Exception\FileException;
22
use Symfony\Component\HttpFoundation\File\UploadedFile;
23
24
/**
25
 * Class Uploader
26
 *
27
 * @package ResponsiveImageBundle
28
 */
29
class Uploader implements UploaderInterface
30
{
31
    /**
32
     * @var FilesystemInterface $fileSystem
33
     */
34
    protected $fileSystem;
35
    /**
36
     * @var UploadedFile $file
37
     */
38
    protected $file;
39
    /**
40
     * @var
41
     */
42
    protected $error;
43
    /**
44
     * @var FilenameTransliteratorInterface
45
     */
46
    protected $transliterator;
47
    /**
48
     * @var FileValidatorInterface
49
     */
50
    protected $fileValidator;
51
    protected $eventDispatcher;
52
53
    /**
54
     * Uploader constructor.
55
     *
56
     * @param PrimaryFileSystemWrapper             $PrimaryFileSystemWrapper
57
     * @param FilenameTransliteratorInterface|null $transliterator
58
     * @param FileValidatorInterface|null          $fileValidator
59
     * @param EventDispatcherInterface|null        $eventDispatcher
60
     */
61
    public function __construct(
62
        PrimaryFileSystemWrapper $PrimaryFileSystemWrapper,
63
        FilenameTransliteratorInterface $transliterator = null,
64
        FileValidatorInterface $fileValidator = null,
65
        EventDispatcherInterface $eventDispatcher = null
66
    ) {
67
        $this->fileSystem      = $PrimaryFileSystemWrapper->getFileSystem();
68
        $this->transliterator  = $transliterator;
69
        $this->fileValidator   = $fileValidator;
70
        $this->eventDispatcher = $eventDispatcher;
71
    }
72
73
    public function upload(ResponsiveImageInterface $image)
74
    {
75
        // Dispatch pre-upload event.
76
        if (!empty($this->eventDispatcher)) {
77
            $uploaderEvent = new UploaderEvent($this);
78
            $this->eventDispatcher->dispatch(UploaderEvents::UPLOADER_PRE_UPLOAD, $uploaderEvent);
79
        }
80
81
        $this->file = $image->getFile();
82
83
        // Use UploadedFile's inbuilt validation and allow
84
        // implementation specific custom checks on uploaded file
85
        if ($this->file->isValid() && $this->isValid()) {
86
87
            // Alter name for uniqueness
88
            $path = $this->formatPath();
89
90
            $info = getimagesize($this->file);
91
            list($length, $height) = $info;
92
93
            // Save the actual file to the filesystem.
94
            $stream = fopen($this->file->getRealPath(), 'r+');
95
            $this->fileSystem->writeStream($path, $stream);
96
            fclose($stream);
97
98
            $image->setPath($path);
99
            $image->setHeight($length);
100
            $image->setWidth($height);
101
102
            // If the image has a setFileSystem method set the filesystem data.
103
            if (method_exists($image, 'setFileSystem')) {
104
                $storageData = $this->getStorageDataFormFileSystem();
105
                if (!empty($storageData)) {
106
                    $image->setFileSystem(serialize($storageData));
0 ignored issues
show
Bug introduced by
The method setFileSystem() does not exist on IrishDan\ResponsiveImage...esponsiveImageInterface. Did you maybe mean setFile()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
107
                }
108
            }
109
110
            // Clean up the file property as you won't need it anymore.
111
            $this->file = null;
112
            $image->setFile(null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object<Symfony\Component...tion\File\UploadedFile>.

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...
113
114
            // Dispatch uploaded event
115
            if (!empty($uploaderEvent)) {
116
                $this->eventDispatcher->dispatch(UploaderEvents::UPLOADER_UPLOADED, $uploaderEvent);
117
            }
118
        }
119
        else {
120
            $error = empty($this->error) ? $this->file->getErrorMessage() : $this->error;
121
            throw new FileException(
122
                $error
123
            );
124
        }
125
    }
126
127
    protected function getStorageDataFormFileSystem()
128
    {
129
        $adapter     = $this->fileSystem->getAdapter();
130
        $adapterType = $this->getAdapterType($adapter);
131
132
        // @TODO: This should be part of the urlEncoders
133
        switch ($adapterType) {
134
            case 'AwsS3Adapter':
135
                $prefix = $adapter->getPathPrefix();
136
                $bucket = $adapter->getBucket();
137
                $region = $adapter->getClient()->getRegion();
138
139
                return [
140
                    'adapter' => $adapterType,
141
                    'prefix'  => $prefix,
142
                    'bucket'  => $bucket,
143
                    'region'  => $region,
144
                ];
145
146
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
147
148
            case 'Local':
149
                return [
150
                    'adapter' => $adapterType,
151
                    'prefix'  => 'test/images', // @TODO: what is this?
152
                ];
153
154
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
155
        }
156
157
        return [];
158
    }
159
160 View Code Duplication
    protected function getAdapterType(AdapterInterface $adapter)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
161
    {
162
        $class          = get_class($adapter);
163
        $namespaceArray = explode("\\", $class);
164
165
        return array_pop($namespaceArray);
166
    }
167
168
    protected function formatPath()
169
    {
170
        $path = $this->file->getClientOriginalName();
171
        if ($this->transliterator instanceof FilenameTransliteratorInterface) {
172
            $path = $this->transliterator->transliterate($path);
173
        }
174
175
        return $path;
176
    }
177
178
    protected function isValid()
179
    {
180
        if ($this->fileValidator instanceof FileValidatorInterface) {
181
            return $this->fileValidator->validate($this->file);
182
        }
183
184
        return true;
185
    }
186
}
187