Completed
Push — master ( a06a95...a1d542 )
by dan
15s
created

Uploader.php (6 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
52
    /**
53
     * Uploader constructor.
54
     *
55
     * @param PrimaryFileSystemWrapper             $PrimaryFileSystemWrapper
56
     * @param FilenameTransliteratorInterface|null $transliterator
57
     * @param FileValidatorInterface|null          $fileValidator
58
     * @param EventDispatcherInterface|null        $eventDispatcher
59
     */
60
    public function __construct(
61
        PrimaryFileSystemWrapper $PrimaryFileSystemWrapper,
62
        FilenameTransliteratorInterface $transliterator = null,
63
        FileValidatorInterface $fileValidator = null,
64
        EventDispatcherInterface $eventDispatcher = null
65
    ) {
66
        $this->fileSystem      = $PrimaryFileSystemWrapper->getFileSystem();
67
        $this->transliterator  = $transliterator;
68
        $this->fileValidator   = $fileValidator;
69
        $this->eventDispatcher = $eventDispatcher;
0 ignored issues
show
The property eventDispatcher does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

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