Passed
Push — master ( c435b4...4e8fd3 )
by Radu
14:56
created

AbstractFileUploadProcessor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 0
c 1
b 0
f 0
dl 0
loc 2
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WebServCo\Framework\Files\Upload;
6
7
use WebServCo\Framework\Exceptions\UploadException;
8
9
/**
10
 * Advanced functionality.
11
 *
12
 * Uses validation and preprocessing
13
 */
14
abstract class AbstractFileUploadProcessor
15
{
16
    abstract protected function generateUploadedFileName(string $uploadFileName, string $uploadFileMimeType): string;
17
18
    abstract protected function processUploadedFileBeforeSaving(string $filePath): bool;
19
20
    abstract protected function validateUploadedFileBeforeSaving(string $filePath): bool;
21
22
    /**
23
     * @param array<string,string> $allowedExtensions
24
     */
25
    public function __construct(protected array $allowedExtensions)
26
    {
27
    }
28
29
    /**
30
     * @param array<int|string,mixed> $uploadedFiles
31
     */
32
    public function handleUpload(string $fieldName, string $uploadDirectory, array $uploadedFiles): ?string
33
    {
34
        if ([] === $uploadedFiles) {
35
            return null;
36
        }
37
38
        if (!isset($uploadedFiles[$fieldName]['error'])) {
39
            throw new UploadException(Codes::NO_FILE);
40
        }
41
42
        if (Codes::OK !== $uploadedFiles[$fieldName]['error']) {
43
            throw new UploadException($uploadedFiles[$fieldName]['error']);
44
        }
45
46
        $this->validateFileMimeType($uploadedFiles[$fieldName]['type']);
47
48
        $this->validateUploadedFileBeforeSaving($uploadedFiles[$fieldName]['tmp_name']);
49
50
        $this->processUploadedFileBeforeSaving($uploadedFiles[$fieldName]['tmp_name']);
51
52
        $uploadedFileName = $this->generateUploadedFileName(
53
            $uploadedFiles[$fieldName]['name'],
54
            $uploadedFiles[$fieldName]['type'],
55
        );
56
        $uploadPath = $uploadDirectory . $uploadedFileName;
57
        \umask(0002);
58
        $result = \move_uploaded_file($uploadedFiles[$fieldName]['tmp_name'], $uploadPath);
59
60
        if (false === $result) {
61
            throw new UploadException(Codes::CANT_WRITE);
62
        }
63
64
        return $uploadedFileName;
65
    }
66
67
    private function validateFileMimeType(string $fileMimeType): bool
68
    {
69
        if ([] === $this->allowedExtensions) {
70
            // All extensions allowed.
71
            return true;
72
        }
73
74
        if (\array_key_exists($fileMimeType, $this->allowedExtensions)) {
75
            return true;
76
        }
77
78
        throw new UploadException(Codes::TYPE_NOT_ALLOWED);
79
    }
80
}
81