Passed
Push — master ( 751d74...a1591c )
by Radu
01:11
created

AbstractUpload::do()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 29
rs 9.0444
cc 6
nc 6
nop 0
1
<?php
2
namespace WebServCo\Framework\Files\Upload;
3
4
use WebServCo\Framework\Exceptions\UploadException;
5
6
abstract class AbstractUpload
7
{
8
    protected $allowedExtensions;
9
    protected $fileName;
10
    protected $fileMimeType;
11
    protected $formFieldName;
12
    protected $uploadDirectory;
13
14
    abstract protected function generateUploadedFileName($uploadFileName, $uploadFileMimeType);
15
16
    public function __construct($uploadDirectory)
17
    {
18
        $this->allowedExtensions = []; // default all
19
        $this->formFieldName = 'upload';
20
        $this->uploadDirectory = $uploadDirectory;
21
    }
22
23
    public function getFileName()
24
    {
25
        return $this->fileName;
26
    }
27
28
    public function getFileMimeType()
29
    {
30
        return $this->fileMimeType;
31
    }
32
33
    final public function do()
34
    {
35
        if (empty($_FILES)) {
36
            return false;
37
        }
38
        if (!isset($_FILES[$this->formFieldName]['error'])) {
39
            throw new UploadException(Codes::NO_FILE);
40
        }
41
        if (Codes::OK != $_FILES[$this->formFieldName]['error']) {
42
            throw new UploadException($_FILES[$this->formFieldName]['error']);
43
        }
44
        $this->checkAllowedExtensions();
45
        $this->fileName = $this->generateUploadedFileName(
46
            $_FILES[$this->formFieldName]['name'],
47
            $_FILES[$this->formFieldName]['type']
48
        );
49
        $this->fileMimeType = $_FILES[$this->formFieldName]['type'];
50
51
        if (!move_uploaded_file($_FILES[$this->formFieldName]['tmp_name'], $this->uploadDirectory.$this->fileName)) {
52
            throw new UploadException(Codes::CANT_WRITE);
53
        }
54
55
        try {
56
            chmod($this->uploadDirectory.$this->fileName, 0664);
57
        } catch (\Exception $e) {
58
            // Operation not permitted
59
        }
60
61
        return true;
62
    }
63
64
    final public function setAllowedExtensions($allowedExtensions)
65
    {
66
        $this->allowedExtensions = $allowedExtensions;
67
    }
68
69
    final public function setFormFieldName($formFieldName)
70
    {
71
        $this->formFieldName = $formFieldName;
72
    }
73
74
    final protected function checkAllowedExtensions()
75
    {
76
        if (!empty($this->allowedExtensions)) {
77
            if (!array_key_exists($_FILES[$this->formFieldName]['type'], $this->allowedExtensions)) {
78
                throw new UploadException(Codes::TYPE_NOT_ALLOWED);
79
            }
80
        }
81
        return true;
82
    }
83
}
84