Conditions | 21 |
Paths | 23 |
Total Lines | 58 |
Code Lines | 27 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
68 | public function compress($files, string $destination = '', bool $overwrite = false): bool |
||
69 | { |
||
70 | // Guard against missing classes. |
||
71 | if (!class_exists('\ZipArchive')) { |
||
72 | return false; |
||
73 | } |
||
74 | |||
75 | // Return false immediately if files isn't a string, isn't an array, or is an empty array. |
||
76 | if ((!is_string($files) && !is_array($files)) || (is_array($files) && !count($files))) { |
||
|
|||
77 | return false; |
||
78 | } |
||
79 | |||
80 | // If the destination already exists and overwrite is false, return false. |
||
81 | if (file_exists($destination) && !$overwrite) { |
||
82 | return true; |
||
83 | } |
||
84 | |||
85 | $valid_files = []; |
||
86 | |||
87 | // Cycle through each file. |
||
88 | if (is_string($files) && $files !== '') { |
||
89 | if (is_readable($files)) { |
||
90 | $valid_files[] = $files; |
||
91 | } |
||
92 | } elseif (is_array($files)) { |
||
93 | foreach ($files as $file) { |
||
94 | if (!empty($file) && is_readable($file)) { |
||
95 | $valid_files[] = $file; |
||
96 | } |
||
97 | } |
||
98 | } |
||
99 | |||
100 | // Return false immediately if we don't have any good files. |
||
101 | if (!count($valid_files)) { |
||
102 | return false; |
||
103 | } |
||
104 | |||
105 | // Create the archive. |
||
106 | $zip = new \ZipArchive(); |
||
107 | if ($zip->open($destination, $overwrite ? \ZipArchive::OVERWRITE : \ZipArchive::CREATE) !== true) { |
||
108 | return false; |
||
109 | } |
||
110 | |||
111 | // Add the files. |
||
112 | foreach ($valid_files as $file) { |
||
113 | if ((($Del = strrpos($file, '\\')) !== false) || ($Del = strrpos($file, '/')) !== false) { |
||
114 | $Safe = substr($file, $Del + 1); |
||
115 | } else { |
||
116 | $Safe = $file; |
||
117 | } |
||
118 | $zip->addFile($file, $Safe); |
||
119 | } |
||
120 | |||
121 | // Close the zip -- done! |
||
122 | $zip->close(); |
||
123 | |||
124 | // Check to make sure the file exists. |
||
125 | return file_exists($destination); |
||
126 | } |
||
128 |