ManagerTools::recursiveUnlink()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 0
Metric Value
cc 3
eloc 4
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 7
ccs 4
cts 5
cp 0.8
crap 3.072
rs 10
1
<?php
2
3
namespace Comodojo\Zip\Base;
4
5
use \Comodojo\Foundation\Utils\UniqueId;
6
use \RecursiveIteratorIterator;
7
use \RecursiveDirectoryIterator;
8
use \FilesystemIterator;
9
use \Exception;
10
11
/**
12
 * comodojo/zip - ZipArchive toolbox
13
 *
14
 * @package     Comodojo Spare Parts
15
 * @author      Marco Giovinazzi <[email protected]>
16
 * @license     MIT
17
 *
18
 * LICENSE:
19
 *
20
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
 * THE SOFTWARE.
27
 */
28
29
class ManagerTools
30
{
31
32
    /**
33
     * Get a temporary folder name (random)
34
     *
35
     * @return string
36
     */
37 1
    public static function getTemporaryFolder(): string
38
    {
39 1
        return "zip-temp-folder-" . UniqueId::generate();
40
    }
41
42
    /**
43
     * Unlink a folder recursively
44
     *
45
     * @param string $folder The folder to be removed
46
     * @param bool $remove_folder If true, the folder itself will be removed
47
     * @return bool
48
     * @throws Exception
49
     */
50 1
    public static function recursiveUnlink(string $folder, bool $remove_folder = true): bool
51
    {
52 1
        self::emptyFolder($folder);
53 1
        if ($remove_folder && rmdir($folder) === false) {
54
            throw new Exception("Error deleting folder: $folder");
55
        }
56 1
        return true;
57
    }
58
59 1
    protected static function emptyFolder(string $folder): bool
60
    {
61 1
        $iterator = new RecursiveIteratorIterator(
62 1
            new RecursiveDirectoryIterator($folder, FilesystemIterator::SKIP_DOTS),
63 1
            RecursiveIteratorIterator::CHILD_FIRST
64
        );
65
66 1
        foreach ($iterator as $path) {
67
68 1
            $pathname = $path->getPathname();
69
70 1
            if ($path->isDir()) {
71 1
                $action = rmdir($pathname);
72
            } else {
73 1
                $action = unlink($pathname);
74
            }
75
76 1
            if ($action === false) {
77
                throw new Exception("Error deleting $pathname during recursive unlink of folder: $folder");
78
            }
79
        }
80
81 1
        return true;
82
    }
83
}
84