Completed
Push — master ( b1625e...8b6a24 )
by Ankit
03:27
created

ImageUploadService::getUploadedFileInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace AnkitPokhrel\LaravelImage;
4
5
use Illuminate\Support\Facades\Input;
6
use Illuminate\Support\Facades\Validator;
7
8
/**
9
 * Handles all image upload operation
10
 *
11
 * @author Ankit Pokhrel
12
 */
13
class ImageUploadService
14
{
15
    /** @var string Image field */
16
    protected $field = 'image';
17
18
    /** @var string Upload dir */
19
    protected $uploadDir = 'upload_dir';
20
21
    /** @var string Original image name field */
22
    protected $originalImageNameField = 'original_image_name';
23
24
    /** @var string Upload base path */
25
    protected $basePath = 'uploads/';
26
27
    /** @var string Relative path to upload dir */
28
    protected $uploadPath = '';
29
30
    /** @var bool Is file uploaded in public dir? */
31
    protected $publicPath = true;
32
33
    /** @var string File save destination */
34
    protected $destination = '';
35
36
    /** @var array Uploaded file info */
37
    protected $uploadedFileInfo = [];
38
39
    /** @var string Image validation rules */
40
    protected $validationRules;
41
42
    /** @var array|object Validation errors */
43
    protected $errors = [];
44
45
    /**
46
     * @constructor
47
     *
48
     * @param null $validationRules
49
     */
50
    public function __construct($validationRules = null)
51
    {
52
        // Default validation rules
53
        $this->validationRules = $validationRules ? $validationRules : config('laravelimage.validationRules');
54
55
        // Set default upload folder
56
        $this->setUploadFolder('contents');
57
    }
58
59
    /**
60
     * Get uploaded file info.
61
     *
62
     * @return array
63
     */
64 1
    public function getUploadedFileInfo()
65
    {
66 1
        return $this->uploadedFileInfo;
67
    }
68
69
    /**
70
     * Set upload field.
71
     *
72
     * @param $fieldName
73
     */
74 1
    public function setUploadField($fieldName)
75
    {
76 1
        $this->field = $fieldName;
77 1
    }
78
79
    /**
80
     * get upload field.
81
     *
82
     * return string
83
     */
84 1
    public function getUploadField()
85
    {
86 1
        return $this->field;
87
    }
88
89
    /**
90
     * Set upload directory.
91
     *
92
     * @param string $dir
93
     */
94 1
    public function setUploadDir($dir)
95
    {
96 1
        $this->uploadDir = $dir;
97 1
    }
98
99
    /**
100
     * get upload directory.
101
     *
102
     * return string
103
     */
104 1
    public function getUploadDir()
105
    {
106 1
        return $this->uploadDir;
107
    }
108
109
    /**
110
     * Set original image name field.
111
     *
112
     * @param string $originalImageName
113
     */
114 1
    public function setOriginalImageNameField($originalImageName)
115
    {
116 1
        $this->originalImageNameField = $originalImageName;
117 1
    }
118
119
    /**
120
     * get original image name field.
121
     *
122
     * return string
123
     */
124 1
    public function getOriginalImageNameField()
125
    {
126 1
        return $this->originalImageNameField;
127
    }
128
129
    /**
130
     * Set base path.
131
     *
132
     * @param $path
133
     * @param $publicPath
134
     */
135 1
    public function setBasePath($path, $publicPath = true)
136
    {
137 1
        $this->basePath   = $path;
138 1
        $this->publicPath = $publicPath;
139 1
    }
140
141
    /**
142
     * Get base path.
143
     *
144
     * @return string
145
     */
146 1
    public function getBasePath()
147
    {
148 1
        return $this->basePath;
149
    }
150
151
    /**
152
     * Enable or disable public path.
153
     *
154
     * @param $bool
155
     */
156
    public function setPublicPath($bool)
157
    {
158
        $this->publicPath = $bool;
159
    }
160
161
    /**
162
     * Get public path.
163
     */
164 1
    public function getPublicPath()
165
    {
166 1
        return $this->publicPath;
167
    }
168
169
    /**
170
     * @param $folder
171
     */
172 1
    public function setUploadFolder($folder)
173
    {
174 1
        $this->uploadPath = $this->basePath . $folder . '/' . $this->getUniqueFolderName() . '/';
175 1
        if ($this->publicPath) {
176 1
            $this->destination = public_path($this->uploadPath);
177
        } else {
178
            $this->destination = $this->uploadPath;
179
        }
180 1
    }
181
182
    /**
183
     * Get upload path
184
     *
185
     * @return string
186
     */
187 2
    public function getUploadPath()
188
    {
189 2
        return $this->uploadPath;
190
    }
191
192
    /**
193
     * @param $rules
194
     */
195 1
    public function setValidationRules($rules)
196
    {
197 1
        $this->validationRules = $rules;
198 1
    }
199
200
    /**
201
     * Get validation rules.
202
     */
203 1
    public function getValidationRules()
204
    {
205 1
        return $this->validationRules;
206
    }
207
208
    /**
209
     * Perform image validation.
210
     *
211
     * @param $file
212
     *
213
     * @return bool
214
     */
215 10
    protected function validate($file)
216
    {
217
        // Check if file is valid
218 10
        if ( ! $file->isValid()) {
219 9
            return false;
220
        }
221
222 1
        $inputFile = [$this->field => $file];
223 1
        $rules     = [$this->field => $this->validationRules];
224
225
        // Validate
226 1
        $validator = Validator::make($inputFile, $rules);
227 1
        if ($validator->fails()) {
228
            $this->errors = $validator;
229
230
            return false;
231
        }
232
233 1
        return true;
234
    }
235
236
    /**
237
     * Uploads file to required destination.
238
     *
239
     * @return bool
240
     */
241 2
    public function upload()
242
    {
243 2
        $file = Input::file($this->field);
244 2
        if ( ! $this->validate($file)) {
245 1
            return false;
246
        }
247
248 1
        $originalFileName  = $file->getClientOriginalName();
249 1
        $encryptedFileName = $this->getUniqueFilename($originalFileName);
250 1
        $mimeType          = $file->getMimeType();
251
252 1
        $size = $file->getSize();
253 1
        if ($file->move($this->destination, $encryptedFileName)) {
254 1
            $this->uploadedFileInfo = [
255 1
                $this->originalImageNameField => $originalFileName,
256 1
                $this->field                  => $encryptedFileName,
257 1
                $this->uploadDir              => $this->getUploadPath(),
258 1
                'size'                        => $size,
259 1
                'extension'                   => $file->getClientOriginalExtension(),
260 1
                'mime_type'                   => $mimeType,
261
            ];
262
263 1
            return true;
264
        }
265
266
        return false;
267
    }
268
269
    /**
270
     * @return array|object
271
     */
272 1
    public function getValidationErrors()
273
    {
274 1
        return $this->errors;
275
    }
276
277
    /**
278
     * Clear out a folder and its content.
279
     *
280
     * @param string $folder Absolute path to the folder
281
     * @param bool $removeDirectory If you want to remove the folder as well
282
     *
283
     * @throws \Exception
284
     */
285 2
    public function clean($folder, $removeDirectory = false)
286
    {
287 2
        if ( ! is_dir($folder)) {
288 1
            throw new \Exception(('Not a folder.'));
289
        }
290
291 1
        array_map('unlink', glob($folder . DIRECTORY_SEPARATOR . '*'));
292 1
        if ($removeDirectory && file_exists($folder)) {
293 1
            rmdir($folder);
294
        }
295 1
    }
296
297
    /**
298
     * function to generate unique filename for images.
299
     *
300
     * @param string $filename
301
     *
302
     * @return string
303
     */
304 7
    public function getUniqueFilename($filename)
305
    {
306 7
        $uniqueName = uniqid();
307 7
        $fileExt    = explode('.', $filename);
308 7
        $mimeType   = end($fileExt);
309 7
        $filename   = $uniqueName . '.' . $mimeType;
310
311 7
        return $filename;
312
    }
313
314
    /**
315
     * Generate a random UUID for folder name (version 4).
316
     *
317
     * @see http://www.ietf.org/rfc/rfc4122.txt
318
     *
319
     * @return string RFC 4122 UUID
320
     *
321
     * @copyright Matt Farina MIT License https://github.com/lootils/uuid/blob/master/LICENSE
322
     */
323 1
    public function getUniqueFolderName()
324
    {
325 1
        return sprintf(
326 1
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
327 1
            mt_rand(0, 65535),
328 1
            mt_rand(0, 65535),
329 1
            mt_rand(0, 65535),
330 1
            mt_rand(0, 4095) | 0x4000,
331 1
            mt_rand(0, 0x3fff) | 0x8000,
332 1
            mt_rand(0, 65535),
333 1
            mt_rand(0, 65535),
334 1
            mt_rand(0, 65535)
335
        );
336
    }
337
}
338