Completed
Pull Request — master (#11)
by dan
02:15
created

Uploader.php (1 issue)

Labels
Severity

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));
106
                }
107
            }
108
109
            // Clean up the file property as you won't need it anymore.
110
            $this->file = null;
111
            $image->setFile(null);
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;
146
147
            case 'Local':
148
                return [
149
                    'adapter' => $adapterType,
150
                    'prefix'  => 'test/images', // @TODO: what is this?
151
                ];
152
153
                break;
154
        }
155
156
        return [];
157
    }
158
159 View Code Duplication
    protected function getAdapterType(AdapterInterface $adapter)
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