Completed
Push — master ( b0f593...ea408c )
by WEBEWEB
02:59
created

FileHelper::delete()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
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\FileSystem;
13
14
use RecursiveDirectoryIterator;
15
use RecursiveIteratorIterator;
16
use WBW\Library\Core\Exception\Argument\IllegalArgumentException;
17
use WBW\Library\Core\Exception\FileSystem\FileNotFoundException;
18
use WBW\Library\Core\Exception\FileSystem\IOException;
19
use ZipArchive;
20
21
/**
22
 * File helper.
23
 *
24
 * @author webeweb <https://github.com/webeweb/>
25
 * @package WBW\Library\Core\IO
26
 */
27
class FileHelper implements FileInterface {
28
29
    /**
30
     * Append to.
31
     *
32
     * @param string $src The source filename.
33
     * @param string $dest The destination filename.
34
     * @param bool $newline New line ?
35
     * @throws IOException Throws an I/O exception if an error occurs.
36
     */
37
    public static function appendTo($src, $dest, $newline = false) {
38
39
        // Open the destination.
40
        $reader = @fopen($src, "r");
41
        if (false === $reader) {
42
            throw new FileNotFoundException($src);
43
        }
44
45
        // Open the destination.
46
        $writer = @fopen($dest, "a");
47
        if (false === $writer) {
48
            throw new IOException(sprintf("Failed to open \"%s\"", $dest));
49
        }
50
51
        // Append the source into destination.
52
        if (false === @file_put_contents($dest, $reader, FILE_APPEND)) {
53
            throw new IOException(sprintf("Failed to append \"%s\" into \"%s\"", $src, $dest));
54
        }
55
56
        // Append a new line.
57
        if (true === $newline && false === @file_put_contents($dest, "\n", FILE_APPEND)) {
58
            throw new IOException(sprintf("Failed to append \"%s\" into \"%s\"", $src, $dest));
59
        }
60
61
        // Close the files.
62
        if (false === @fclose($reader)) {
63
            throw new IOException(sprintf("Failed to open \"%s\"", $src));
64
        }
65
        if (false === @fclose($writer)) {
66
            throw new IOException(sprintf("Failed to open \"%s\"", $dest));
67
        }
68
    }
69
70
    /**
71
     * Delete a file.
72
     *
73
     * @param string $filename The filename.
74
     * @return boolean Returns true in case of success, false otherwise.
75
     * @throws FileNotFoundException Throws a file not found exception if the file does not exists.
76
     */
77
    public static function delete($filename) {
78
        if (false === file_exists($filename)) {
79
            throw new FileNotFoundException($filename);
80
        }
81
        return unlink($filename);
82
    }
83
84
    /**
85
     * Format a size.
86
     *
87
     * @param  $size The size.
88
     * @param string $unit The unit.
89
     * @return string Returns the formated size.
90
     */
91
    public static function formatSize($size, $unit = null, $decimals = 2) {
92
93
94
        // Initialize the units.
95
        $units = static::getUnits();
96
97
        // Find the unit.
98
        $index = array_search($unit, $units);
99
        if (null !== $unit && false === $index) {
100
            throw new IllegalArgumentException("The unit \"" . $unit . "\" does not exists");
101
        }
102
103
        // Initialize the output.
104
        $output = $size;
105
106
        $iteration = 0;
107
        while (self::FILE_SIZE_DIVIDER <= $output || $iteration < $index) {
108
            $output /= self::FILE_SIZE_DIVIDER;
109
            ++$iteration;
110
        }
111
112
        // Return the output.
113
        return implode(" ", [sprintf("%." . $decimals . "f", $output), $units[$iteration]]);
114
    }
115
116
    /**
117
     * Get a file contents.
118
     *
119
     * @param string $filename The filename.
120
     * @return string Returns the file contents.
121
     * @throws FileNotFoundException Throws a file not found exception if the file does not exists.
122
     */
123
    public static function getContents($filename) {
124
        if (false === file_exists($filename)) {
125
            throw new FileNotFoundException($filename);
126
        }
127
        return file_get_contents($filename);
128
    }
129
130
    /**
131
     * Get the filenames.
132
     *
133
     * @param string $pathname The pathname.
134
     * @param string $extension The file extension.
135
     * @return array Returns the filenames.
136
     * @throws FileNotFoundException Throws a file not found exception if the directory does not exists.
137
     */
138
    public static function getFilenames($pathname, $extension = null) {
139
140
        // Check if the directory exists.
141
        if (false === file_exists($pathname)) {
142
            throw new FileNotFoundException($pathname);
143
        }
144
145
        // Initialize the filenames.
146
        $filenames = [];
147
148
        // Open the directory.
149
        if (false !== ($directory = opendir($pathname))) {
150
151
            // Initialize the offset.
152
            $offset = strlen($extension);
153
154
            // Read the directory.
155
            while (($file = readdir($directory)) !== false) {
156
157
                // Determines if the file should be added.
158
                if (false === in_array($file, [".", ".."]) && ((null === $extension) || 0 === substr_compare($file, $extension, -$offset))) {
159
                    $filenames[] = $file;
160
                }
161
            }
162
163
            // Close the directory.
164
            closedir($directory);
165
        }
166
167
        // Return the filenames.
168
        return $filenames;
169
    }
170
171
    /**
172
     * Get a file size.
173
     *
174
     * @param string $filename The filename.
175
     * @return int Returns the file size.
176
     * @throws FileNotFoundException Throws a File not found exception if the file does not exists.
177
     */
178
    public static function getSize($filename) {
179
        if (false === file_exists($filename)) {
180
            throw new FileNotFoundException($filename);
181
        }
182
        clearstatcache();
183
        return filesize($filename);
184
    }
185
186
    /**
187
     * Get the units.
188
     *
189
     * @return array Returns the units.
190
     */
191
    public static function getUnits() {
192
        return [
193
            self::FILE_SIZE_UNIT_B,
194
            self::FILE_SIZE_UNIT_KB,
195
            self::FILE_SIZE_UNIT_MB,
196
            self::FILE_SIZE_UNIT_GB,
197
            self::FILE_SIZE_UNIT_TB,
198
            self::FILE_SIZE_UNIT_PB,
199
            self::FILE_SIZE_UNIT_EB,
200
            self::FILE_SIZE_UNIT_ZB,
201
            self::FILE_SIZE_UNIT_YB,
202
        ];
203
    }
204
205
    /**
206
     * Rename a file.
207
     *
208
     * @param string $oldFilename The old filename.
209
     * @param string $newFilename The new filename.
210
     * @return boolean Returns true in case of success, false otherwise or null if the new filename already exists.
211
     * @throws FileNotFoundException Throws a file not found exception if the file does not exists.
212
     */
213
    public static function rename($oldFilename, $newFilename) {
214
        if (false === file_exists($oldFilename)) {
215
            throw new FileNotFoundException($oldFilename);
216
        }
217
        if (true === file_exists($newFilename)) {
218
            return null;
219
        }
220
        return rename($oldFilename, $newFilename);
221
    }
222
223
    /**
224
     * Zip a file.
225
     *
226
     * @param string $source The source filename.
227
     * @param string $destination The destination filename.
228
     * @return boolean Returns true in case of success, false otherwise.
229
     * @throws FileNotFoundException Throws a file not found exception if the source filename is not found.
230
     */
231
    public static function zip($source, $destination) {
232
233
        // Check if the filename exists.
234
        if (false === file_exists($source)) {
235
            throw new FileNotFoundException($source);
236
        }
237
238
        // Initialize the ZIP archive.
239
        $zip = new ZipArchive();
240
        $zip->open($destination, ZipArchive::CREATE);
241
242
        // Clean up.
243
        $src = str_replace("\\\\", "/", realpath($source));
244
245
        // Is file ? => Add it and return.
246
        if (true === is_file($src)) {
247
            $zip->addFromString(basename($src), static::getContents($src));
248
            return $zip->close();
249
        }
250
251
        // Handle the files list.
252
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($src), RecursiveIteratorIterator::SELF_FIRST);
253
        foreach ($files as $current) {
254
255
            // Clean up.
256
            $cur = str_replace("\\\\", "/", realpath($current));
257
258
            // Initialize the ZIP path.
259
            $zipPath = preg_replace("/^" . str_replace("/", "\/", $src . "/") . "/", "", $cur);
260
261
            // Check the file type.
262
            if (true === is_file($cur)) {
263
                $zip->addFromString($zipPath, static::getContents($cur));
264
            }
265
            if (true === is_dir($cur)) {
266
                $zip->addEmptyDir($zipPath);
267
            }
268
        }
269
    }
270
271
}
272