Completed
Push — master ( ee9100...4ce895 )
by Ankit
02:56
created

ImageUploadService::setValidationRules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 1
cts 1
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
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
     * Get public path.
153
     */
154
    public function getPublicPath()
155
    {
156
        return $this->publicPath;
157
    }
158
159
    /**
160
     * Set upload folder.
161
     *
162
     * @param $folder
163
     */
164 1
    public function setUploadFolder($folder)
165
    {
166 1
        $this->uploadPath = $this->basePath . $folder . '/' . $this->getUniqueFolderName() . '/';
167
        $this->destination = $this->publicPath ? public_path($this->uploadPath) : $this->uploadPath;
168
    }
169
170
    /**
171
     * Get upload destination.
172 1
     *
173
     * @return string
174 1
     */
175 1
    public function getDestination()
176 1
    {
177
        return $this->destination;
178
    }
179
180 1
    /**
181
     * Get upload path
182
     *
183
     * @return string
184
     */
185
    public function getUploadPath()
186
    {
187 2
        return $this->uploadPath;
188
    }
189 2
190
    /**
191
     * @param $rules
192
     */
193
    public function setValidationRules($rules)
194
    {
195 1
        $this->validationRules = $rules;
196
    }
197 1
198 1
    /**
199
     * Get validation rules.
200
     */
201
    public function getValidationRules()
202
    {
203 1
        return $this->validationRules;
204
    }
205 1
206
    /**
207
     * Perform image validation.
208
     *
209
     * @param $file
210
     *
211
     * @return bool
212
     */
213
    protected function validate($file)
214
    {
215 10
        // Check if file is valid
216
        if ( ! $file->isValid()) {
217
            return false;
218 10
        }
219 9
220
        $inputFile = [$this->field => $file];
221
        $rules     = [$this->field => $this->validationRules];
222 1
223 1
        // Validate
224
        $validator = Validator::make($inputFile, $rules);
225
        if ($validator->fails()) {
226 1
            $this->errors = $validator;
227 1
228
            return false;
229
        }
230
231
        return true;
232
    }
233 1
234
    /**
235
     * Uploads file to required destination.
236
     *
237
     * @return bool
238
     */
239
    public function upload()
240
    {
241 2
        $file = Input::file($this->field);
242
        if ( ! $this->validate($file)) {
243 2
            return false;
244 2
        }
245 1
246
        $originalFileName  = $file->getClientOriginalName();
247
        $encryptedFileName = $this->getUniqueFilename($originalFileName);
248 1
        $mimeType          = $file->getMimeType();
249 1
250 1
        $size = $file->getSize();
251
        if ($file->move($this->getDestination(), $encryptedFileName)) {
252 1
            $this->uploadedFileInfo = [
253 1
                $this->originalImageNameField => $originalFileName,
254 1
                $this->field                  => $encryptedFileName,
255 1
                $this->uploadDir              => $this->getUploadPath(),
256 1
                'size'                        => $size,
257 1
                'extension'                   => $file->getClientOriginalExtension(),
258 1
                'mime_type'                   => $mimeType,
259 1
            ];
260 1
261
            return true;
262
        }
263 1
264
        return false;
265
    }
266
267
    /**
268
     * @return array|object
269
     */
270
    public function getValidationErrors()
271
    {
272 1
        return $this->errors;
273
    }
274 1
275
    /**
276
     * Clear out a folder and its content.
277
     *
278
     * @param string $folder Absolute path to the folder
279
     * @param bool $removeDirectory If you want to remove the folder as well
280
     *
281
     * @throws \Exception
282
     */
283
    public function clean($folder, $removeDirectory = false)
284
    {
285 2
        if ( ! is_dir($folder)) {
286
            throw new \Exception(('Not a folder.'));
287 2
        }
288 1
289
        array_map('unlink', glob($folder . DIRECTORY_SEPARATOR . '*'));
290
        if ($removeDirectory && file_exists($folder)) {
291 1
            rmdir($folder);
292 1
        }
293 1
    }
294
295 1
    /**
296
     * function to generate unique filename for images.
297
     *
298
     * @param string $filename
299
     *
300
     * @return string
301
     */
302
    public function getUniqueFilename($filename)
303
    {
304 7
        $uniqueName = uniqid();
305
        $fileExt    = explode('.', $filename);
306 7
        $mimeType   = end($fileExt);
307 7
        $filename   = $uniqueName . '.' . $mimeType;
308 7
309 7
        return $filename;
310
    }
311 7
312
    /**
313
     * Generate a random UUID for folder name (version 4).
314
     *
315
     * @see http://www.ietf.org/rfc/rfc4122.txt
316
     *
317
     * @return string RFC 4122 UUID
318
     *
319
     * @copyright Matt Farina MIT License https://github.com/lootils/uuid/blob/master/LICENSE
320
     */
321
    public function getUniqueFolderName()
322
    {
323 1
        return sprintf(
324
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
325 1
            mt_rand(0, 65535),
326 1
            mt_rand(0, 65535),
327 1
            mt_rand(0, 65535),
328 1
            mt_rand(0, 4095) | 0x4000,
329 1
            mt_rand(0, 0x3fff) | 0x8000,
330 1
            mt_rand(0, 65535),
331 1
            mt_rand(0, 65535),
332 1
            mt_rand(0, 65535)
333 1
        );
334 1
    }
335
}
336