Completed
Push — master ( 5aa9d3...178a4b )
by dan
02:07
created

Uploader::getFileSystem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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
    public function getFileSystem()
54
    {
55
        return $this->fileSystem;
56
    }
57
58
    public function setFileSystem($filesystem)
59
    {
60
        $this->fileSystem = $filesystem;
61
    }
62
63
    /**
64
     * Uploader constructor.
65
     *
66
     * @param PrimaryFileSystemWrapper             $PrimaryFileSystemWrapper
67
     * @param FilenameTransliteratorInterface|null $transliterator
68
     * @param FileValidatorInterface|null          $fileValidator
69
     * @param EventDispatcherInterface|null        $eventDispatcher
70
     */
71
    public function __construct(
72
        PrimaryFileSystemWrapper $PrimaryFileSystemWrapper,
73
        FilenameTransliteratorInterface $transliterator = null,
74
        FileValidatorInterface $fileValidator = null,
75
        EventDispatcherInterface $eventDispatcher = null
76
    ) {
77
        $this->fileSystem      = $PrimaryFileSystemWrapper->getFileSystem();
78
        $this->transliterator  = $transliterator;
79
        $this->fileValidator   = $fileValidator;
80
        $this->eventDispatcher = $eventDispatcher;
81
    }
82
83
    public function upload(ResponsiveImageInterface $image)
84
    {
85
        // Dispatch pre-upload event.
86
        if (!empty($this->eventDispatcher)) {
87
            $uploaderEvent = new UploaderEvent($this);
88
            $this->eventDispatcher->dispatch(UploaderEvents::UPLOADER_PRE_UPLOAD, $uploaderEvent);
89
        }
90
91
        $this->file = $image->getFile();
92
93
        // Use UploadedFile's inbuilt validation and allow
94
        // implementation specific custom checks on uploaded file
95
        if ($this->file->isValid() && $this->isValid()) {
96
97
            // Alter name for uniqueness
98
            $path = $this->formatPath();
99
100
            $info = getimagesize($this->file);
101
            list($length, $height) = $info;
102
103
            // Save the actual file to the filesystem.
104
            $stream = fopen($this->file->getRealPath(), 'r+');
105
            $this->fileSystem->writeStream($path, $stream);
106
            fclose($stream);
107
108
            $image->setPath($path);
109
            $image->setHeight($length);
110
            $image->setWidth($height);
111
112
            // If the image has a setFileSystem method set the filesystem data.
113
            if (method_exists($image, 'setFileSystem')) {
114
                $storageData = $this->getStorageDataFormFileSystem();
115
                if (!empty($storageData)) {
116
                    $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...
117
                }
118
            }
119
120
            // Clean up the file property as you won't need it anymore.
121
            $this->file = null;
122
            $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...
123
124
            // Dispatch uploaded event
125
            if (!empty($uploaderEvent)) {
126
                $this->eventDispatcher->dispatch(UploaderEvents::UPLOADER_UPLOADED, $uploaderEvent);
127
            }
128
        }
129
        else {
130
            $error = empty($this->error) ? $this->file->getErrorMessage() : $this->error;
131
            throw new FileException(
132
                $error
133
            );
134
        }
135
    }
136
137
    protected function getStorageDataFormFileSystem()
138
    {
139
        $adapter     = $this->fileSystem->getAdapter();
140
        $adapterType = $this->getAdapterType($adapter);
141
142
        // @TODO: This should be part of the urlEncoders
143
        switch ($adapterType) {
144
            case 'AwsS3Adapter':
145
                $prefix = $adapter->getPathPrefix();
146
                $bucket = $adapter->getBucket();
147
                $region = $adapter->getClient()->getRegion();
148
149
                return [
150
                    'adapter' => $adapterType,
151
                    'prefix'  => $prefix,
152
                    'bucket'  => $bucket,
153
                    'region'  => $region,
154
                ];
155
156
                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...
157
158
            case 'Local':
159
                return [
160
                    'adapter' => $adapterType,
161
                    'prefix'  => 'test/images', // @TODO: what is this?
162
                ];
163
164
                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...
165
        }
166
167
        return [];
168
    }
169
170 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...
171
    {
172
        $class          = get_class($adapter);
173
        $namespaceArray = explode("\\", $class);
174
175
        return array_pop($namespaceArray);
176
    }
177
178
    protected function formatPath()
179
    {
180
        $path = $this->file->getClientOriginalName();
181
        if ($this->transliterator instanceof FilenameTransliteratorInterface) {
182
            $path = $this->transliterator->transliterate($path);
183
        }
184
185
        return $path;
186
    }
187
188
    protected function isValid()
189
    {
190
        if ($this->fileValidator instanceof FileValidatorInterface) {
191
            return $this->fileValidator->validate($this->file);
192
        }
193
194
        return true;
195
    }
196
}
197