Completed
Push — master ( 674066...0b0354 )
by WEBEWEB
03:44
created

FileHelper   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 211
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 30
lcom 0
cbo 2
dl 0
loc 211
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A delete() 0 6 2
A formatSize() 0 24 5
A getContents() 0 6 2
B getFilenames() 0 32 7
A getSize() 0 7 2
A getUnits() 0 13 1
A rename() 0 9 3
B zip() 0 47 8
1
<?php
2
3
/**
4
 * This file is part of the core-library package.
5
 *
6
 * (c) 2018 WEBEWEB
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WBW\Library\Core\Helper\IO;
13
14
use RecursiveDirectoryIterator;
15
use RecursiveIteratorIterator;
16
use WBW\Library\Core\Exception\Argument\IllegalArgumentException;
17
use WBW\Library\Core\Exception\IO\FileNotFoundException;
18
use ZipArchive;
19
20
/**
21
 * File helper.
22
 *
23
 * @author webeweb <https://github.com/webeweb/>
24
 * @package WBW\Library\Core\Helper\IO
25
 */
26
class FileHelper implements FileInterface {
27
28
    /**
29
     * Delete a file.
30
     *
31
     * @param string $filename The filename.
32
     * @return boolean Returns true in case of success, false otherwise.
33
     * @throws FileNotFoundException Throws a file not found exception if the file does not exists.
34
     */
35
    public static function delete($filename) {
36
        if (false === file_exists($filename)) {
37
            throw new FileNotFoundException($filename);
38
        }
39
        return unlink($filename);
40
    }
41
42
    /**
43
     * Format a size.
44
     *
45
     * @param  $size The size.
46
     * @param string $unit The unit.
47
     * @return string Returns the formated size.
48
     */
49
    public static function formatSize($size, $unit = null, $decimals = 2) {
50
51
52
        // Initialize the units.
53
        $units = self::getUnits();
54
55
        // Find the unit.
56
        $index = array_search($unit, $units);
57
        if (null !== $unit && false === $index) {
58
            throw new IllegalArgumentException("The unit \"" . $unit . "\" does not exists");
59
        }
60
61
        // Initialize the output.
62
        $output = $size;
63
64
        $iteration = 0;
65
        while (self::FILE_SIZE_DIVIDER <= $output || $iteration < $index) {
66
            $output /= self::FILE_SIZE_DIVIDER;
67
            ++$iteration;
68
        }
69
70
        // Return the output.
71
        return implode(" ", [sprintf("%." . $decimals . "f", $output), $units[$iteration]]);
72
    }
73
74
    /**
75
     * Get a file contents.
76
     *
77
     * @param string $filename The filename.
78
     * @return string Returns the file contents.
79
     * @throws FileNotFoundException Throws a file not found exception if the file does not exists.
80
     */
81
    public static function getContents($filename) {
82
        if (false === file_exists($filename)) {
83
            throw new FileNotFoundException($filename);
84
        }
85
        return file_get_contents($filename);
86
    }
87
88
    /**
89
     * Get the filenames.
90
     *
91
     * @param string $pathname The pathname.
92
     * @param string $extension The file extension.
93
     * @return array Returns the filenames.
94
     * @throws FileNotFoundException Throws a file not found exception if the directory does not exists.
95
     */
96
    public static function getFilenames($pathname, $extension = null) {
97
98
        // Check if the directory exists.
99
        if (false === file_exists($pathname)) {
100
            throw new FileNotFoundException($pathname);
101
        }
102
103
        // Initialize the filenames.
104
        $filenames = [];
105
106
        // Open the directory.
107
        if (false !== ($directory = opendir($pathname))) {
108
109
            // Initialize the offset.
110
            $offset = strlen($extension);
111
112
            // Read the directory.
113
            while (($file = readdir($directory)) !== false) {
114
115
                // Determines if the file should be added.
116
                if (false === in_array($file, [".", ".."]) && ((null === $extension) || 0 === substr_compare($file, $extension, -$offset))) {
117
                    $filenames[] = $file;
118
                }
119
            }
120
121
            // Close the directory.
122
            closedir($directory);
123
        }
124
125
        // Return the filenames.
126
        return $filenames;
127
    }
128
129
    /**
130
     * Get a file size.
131
     *
132
     * @param string $filename The filename.
133
     * @return integer Returns the file size.
134
     * @throws FileNotFoundException Throws a File not found exception if the file does not exists.
135
     */
136
    public static function getSize($filename) {
137
        if (false === file_exists($filename)) {
138
            throw new FileNotFoundException($filename);
139
        }
140
        clearstatcache();
141
        return filesize($filename);
142
    }
143
144
    /**
145
     * Get the units.
146
     *
147
     * @return array Returns the units.
148
     */
149
    public static function getUnits() {
150
        return [
151
            self::FILE_SIZE_UNIT_B,
152
            self::FILE_SIZE_UNIT_KB,
153
            self::FILE_SIZE_UNIT_MB,
154
            self::FILE_SIZE_UNIT_GB,
155
            self::FILE_SIZE_UNIT_TB,
156
            self::FILE_SIZE_UNIT_PB,
157
            self::FILE_SIZE_UNIT_EB,
158
            self::FILE_SIZE_UNIT_ZB,
159
            self::FILE_SIZE_UNIT_YB,
160
        ];
161
    }
162
163
    /**
164
     * Rename a file.
165
     *
166
     * @param string $oldFilename The old filename.
167
     * @param string $newFilename The new filename.
168
     * @return boolean Returns true in case of success, false otherwise or null if the new filename already exists.
169
     * @throws FileNotFoundException Throws a file not found exception if the file does not exists.
170
     */
171
    public static function rename($oldFilename, $newFilename) {
172
        if (false === file_exists($oldFilename)) {
173
            throw new FileNotFoundException($oldFilename);
174
        }
175
        if (true === file_exists($newFilename)) {
176
            return null;
177
        }
178
        return rename($oldFilename, $newFilename);
179
    }
180
181
    /**
182
     * Zip a file.
183
     *
184
     * @param string $source The source filename.
185
     * @param string $destination The destination filename.
186
     * @throws FileNotFoundException Throws a file not found exception if the source filename is not found.
187
     */
188
    public static function zip($source, $destination) {
189
190
        // Check if the filename exists.
191
        if (false === file_exists($source)) {
192
            throw new FileNotFoundException($source);
193
        }
194
195
        // Initialize the ZIP archive.
196
        $zip = new ZipArchive();
197
        if (true !== $zip->open($destination, ZipArchive::CREATE)) {
198
            return false;
199
        }
200
201
        // Clean up.
202
        $source = str_replace("\\\\", "/", realpath($source));
203
204
        // Is file ? => Add it and return.
205
        if (true === is_file($source)) {
206
            $zip->addFromString(basename($source), self::getContents($source));
207
            return $zip->close();
208
        }
209
210
        // Get and handle the files list.
211
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
212
        foreach ($files as $current) {
213
214
            // Clean up and determines if the file should be added.
215
            $current = str_replace("\\\\", "/", $current);
216
            if (true === in_array($current, [".", ".."])) {
217
                continue;
218
            }
219
220
            // Clean up.
221
            $current = realpath($current);
222
223
            // Initialize the ZIP path.
224
            $zipPath = preg_replace("/^" . str_replace("/", "\/", $source . "/") . "/", "", $current);
225
226
            // Check the file type.
227
            if (true === is_file($current)) {
228
                $zip->addFromString($zipPath, self::getContents($current));
229
            }
230
            if (true === is_dir($current)) {
231
                $zip->addEmptyDir($zipPath);
232
            }
233
        }
234
    }
235
236
}
237