Passed
Push — main ( 72c6fa...9344f0 )
by Sílvio
02:59
created

FileCacheManager::clearDirectory()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\CacheStore\CacheManager;
4
5
use RecursiveDirectoryIterator;
6
use RecursiveIteratorIterator;
7
use Silviooosilva\CacheerPhp\Exceptions\CacheFileException;
8
9
class FileCacheManager
10
{
11
12
    /**
13
    * @param string $dir
14
    * @return void
15
    */
16
    public function createDirectory(string $dir)
17
    {
18
        if ((!file_exists($dir) || !is_dir($dir)) && !mkdir($dir, 0777, true)) {
19
            throw CacheFileException::create("Could not create directory: {$dir}");
20
        }
21
    }
22
23
    /**
24
    * @param string $filename
25
    * @param string $data
26
    * @return void
27
    */
28
    public function writeFile(string $filename, string $data)
29
    {
30
        if (!@file_put_contents($filename, $data, LOCK_EX)) {
31
            throw CacheFileException::create("Could not write file: {$filename}");
32
        }
33
    }
34
35
    /**
36
    * @param string $filename
37
    * @return string
38
    */
39
    public function readFile(string $filename)
40
    {
41
        if (!file_exists($filename)) {
42
            throw CacheFileException::create("File not found: {$filename}");
43
        }
44
        return file_get_contents($filename);
45
    }
46
47
    /**
48
    * @param string $filename
49
    * @return void
50
    */
51
    public function removeFile(string $filename)
52
    {
53
        if (file_exists($filename)) {
54
            unlink($filename);
55
        }
56
    }
57
58
    /**
59
    * @param string $dir
60
    * @return void
61
    */
62
    public function clearDirectory(string $dir)
63
    {
64
        $iterator = new RecursiveIteratorIterator(
65
            new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
66
            RecursiveIteratorIterator::CHILD_FIRST
67
        );
68
        foreach ($iterator as $file) {
69
            $path = $file->getPathname();
70
            $file->isDir() ? rmdir($path) : unlink($path);
71
        }
72
    }
73
74
    /**
75
    * @param mixed $data
76
    * @param bool $serealize
77
    */
78
    public function serialize(mixed $data, bool $serealize = true)
79
    {
80
        if($serealize) {
81
            return serialize($data);
82
        }
83
        return unserialize($data);
84
    }
85
}
86