Completed
Push — master ( 0be1c7...fd0431 )
by WEBEWEB
02:02
created

FileUtility   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 214
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 9
Bugs 0 Features 0
Metric Value
wmc 31
c 9
b 0
f 0
lcom 0
cbo 3
dl 0
loc 214
rs 9.8

8 Methods

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