Helper   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 121
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 44
dl 0
loc 121
rs 10
c 1
b 0
f 0
wmc 15

4 Methods

Rating   Name   Duplication   Size   Complexity  
A moveUploadedFileToTempDirectory() 0 6 2
A formatSize() 0 14 3
A sizeInBytes() 0 16 3
B normalizeFiles() 0 52 7
1
<?php
2
3
/**
4
 * Platine Upload
5
 *
6
 * Platine Upload provides a flexible file uploads with extensible
7
 * validation and storage strategies.
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Upload
12
 *
13
 * @author      Josh Lockhart <[email protected]>
14
 * @copyright   2012 Josh Lockhart
15
 * @link        http://www.joshlockhart.com
16
 * @version     2.0.0
17
 *
18
 * Permission is hereby granted, free of charge, to any person obtaining a copy
19
 * of this software and associated documentation files (the "Software"), to deal
20
 * in the Software without restriction, including without limitation the rights
21
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22
 * copies of the Software, and to permit persons to whom the Software is
23
 * furnished to do so, subject to the following conditions:
24
 *
25
 * The above copyright notice and this permission notice shall be included in all
26
 * copies or substantial portions of the Software.
27
 *
28
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
34
 * SOFTWARE.
35
 */
36
37
/**
38
 *  @file Helper.php
39
 *
40
 *  The Upload Helper class
41
 *
42
 *  @package    Platine\Upload\Util
43
 *  @author Platine Developers Team
44
 *  @copyright  Copyright (c) 2020
45
 *  @license    http://opensource.org/licenses/MIT  MIT License
46
 *  @link   https://www.platine-php.com
47
 *  @version 1.0.0
48
 *  @filesource
49
 */
50
51
declare(strict_types=1);
52
53
namespace Platine\Upload\Util;
54
55
use Platine\Http\UploadedFile;
56
use Platine\Upload\File\File;
57
58
/**
59
 * @class Helper
60
 * @package Platine\Upload\Util
61
 */
62
class Helper
63
{
64
    /**
65
     * Normalize the uploaded files to fit our format
66
     *
67
     * @param array<mixed> $files the normalized
68
     * format of UploadedFile::createFromGlobals()
69
     *
70
     * @return array<string, File>|array<string, array<int, File>>
71
     */
72
    public static function normalizeFiles(array $files): array
73
    {
74
        /** @var array<mixed> $result */
75
        $result = [];
76
77
        /**
78
         * TODO
79
         * Only support for :
80
         * <input type = 'file' name ='my_file' /><br />
81
         * <input type = 'file' name ='files[]' /><br />
82
         *
83
         * Not support currently:
84
         *  <input type = 'file' name ='files[my_name]' />
85
         *  <input type = 'file' name ='files[][foo]' />
86
         *  <input type = 'file' name ='files[][bar][]' />
87
         *  <input type = 'file' name ='files[file1][file2][file3][file_n]' />
88
         *  <input type = 'file' name ='files[file_name][]' />
89
         */
90
        foreach ($files as $name => $file) {
91
            if ($file instanceof UploadedFile) {
92
                $tempName = (string) tempnam(sys_get_temp_dir(), uniqid());
93
                static::moveUploadedFileToTempDirectory($file, $tempName);
94
95
                $result[$name] = File::create(
96
                    $tempName,
97
                    (string) $file->getClientFilename(),
98
                    $file->getClientFilename(),
99
                    $file->getError()
100
                );
101
                continue;
102
            }
103
104
            if (is_array($file)) {
105
                $result[$name] = [];
106
107
                foreach ($file as $index => $file2) {
108
                    if (is_int($index) && $file2 instanceof UploadedFile) {
109
                        $tempName = (string) tempnam(sys_get_temp_dir(), uniqid());
110
                        static::moveUploadedFileToTempDirectory($file2, $tempName);
111
112
                        $result[$name][$index] = File::create(
113
                            $tempName,
114
                            (string) $file2->getClientFilename(),
115
                            $file2->getClientFilename(),
116
                            $file2->getError()
117
                        );
118
                    }
119
                }
120
            }
121
        }
122
123
        return $result;
124
    }
125
126
    /**
127
     * Convert the size like 4G, 7T, 19B to byte
128
     * @param string $size
129
     * @return int
130
     */
131
    public static function sizeInBytes(string $size): int
132
    {
133
        $value = 1.0;
134
        $unit = 'B';
135
        $units = ['B' => 0, 'K' => 1, 'M' => 2, 'G' => 3, 'T' => 4];
136
        $matches = [];
137
        preg_match('/(?<size>[\d\.]+)\s*(?<unit>b|k|m|g|t)?/i', $size, $matches);
138
        if (array_key_exists('unit', $matches)) {
139
            $unit = strtoupper($matches['unit']);
140
        }
141
142
        if (array_key_exists('size', $matches)) {
143
            $value = floatval($matches['size']);
144
        }
145
146
        return (int)($value * pow(1024, $units[$unit]));
147
    }
148
149
    /**
150
     * Format to human readable size
151
     * @param int $size
152
     * @param int $precision
153
     * @return string
154
     */
155
    public static function formatSize(int $size, int $precision = 2): string
156
    {
157
        if ($size > 0) {
158
            $base = log($size) / log(1024);
159
            $suffixes = ['B', 'K', 'M', 'G', 'T'];
160
            $suffix = '';
161
            if (isset($suffixes[floor($base)])) {
162
                $suffix = $suffixes[floor($base)];
163
            }
164
165
            return round(pow(1024, $base - floor($base)), $precision) . $suffix;
166
        }
167
168
        return '';
169
    }
170
171
    /**
172
     * Move uploadedFile to temporary directory
173
     * @param UploadedFile $file
174
     * @param string $tempDir
175
     * @return void
176
     */
177
    protected static function moveUploadedFileToTempDirectory(
178
        UploadedFile $file,
179
        string $tempDir
180
    ): void {
181
        if (in_array($file->getError(), [UPLOAD_ERR_OK])) {
182
            $file->moveTo($tempDir);
183
        }
184
    }
185
}
186