This repository has been archived by the owner on Jul 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCache.php
62 lines (49 loc) · 1.46 KB
/
Cache.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace Vdlp\Phast;
use Illuminate\Filesystem\Filesystem;
use InvalidArgumentException;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
final class Cache
{
private const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
private const BYTE_PRECISION = [0, 0, 1, 2, 2, 3, 3, 4, 4];
private const BYTE_NEXT = 1024;
/**
* @var string
*/
private $path;
public function __construct()
{
$this->path = config('phast.cache.cacheRoot');
}
public function clear(): void
{
$fs = new Filesystem();
$fs->cleanDirectory($this->path);
}
/**
* @throws InvalidArgumentException
*/
public function size(): string
{
$iterator = Finder::create()
->files()
->ignoreDotFiles(true)
->in($this->path);
$totalSize = 0;
/** @var SplFileInfo $file */
foreach ($iterator as $file) {
$totalSize += $file->getSize();
}
return self::humanReadableBytes($totalSize, 2);
}
private static function humanReadableBytes($bytes, ?int $precision = null): string
{
for ($i = 0; ($bytes / self::BYTE_NEXT) >= 0.9 && $i < count(self::BYTE_UNITS); $i++) {
$bytes /= self::BYTE_NEXT;
}
return round($bytes, is_null($precision) ? self::BYTE_PRECISION[$i] : $precision) . self::BYTE_UNITS[$i];
}
}