This repository has been archived by the owner on Sep 8, 2019. It is now read-only.
/
SetupFiles.php
76 lines (66 loc) · 2.31 KB
/
SetupFiles.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
/*
* This file is part of the JSONDiskCache package.
*
* (c) Dawid Spiechowicz <spiechu@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiechu\JSONDiskCache;
class SetupFiles
{
/**
* @param string $dirToCreate path to dir
* @param int $perms dir perms
* @return \SplFileInfo created/checked dir
* @throws JSONDiskCacheException
*/
public function setupCacheDir($dirToCreate, $perms)
{
$dir = new \SplFileInfo($dirToCreate);
if (!file_exists($dir)) {
$result = @mkdir($dir, $perms, true);
if (!$result) {
throw new JSONDiskCacheException(error_get_last()['message']);
}
}
if (!$dir->isDir()) {
throw new JSONDiskCacheException("{$dirToCreate} is not a dir");
}
if (!($dir->isReadable() && $dir->isWritable())) {
throw new JSONDiskCacheException("{$dirToCreate} is not readable or writable");
}
return $dir;
}
/**
* @param \SplFileInfo $dir
* @param string $filename
* @param int $perms file perms
* @return \SplFileInfo
* @throws JSONDiskCacheException
*/
public function setupFile(\SplFileInfo $dir, $filename, $perms)
{
if (!$dir->isDir()) {
throw new JSONDiskCacheException("{$dir} is not a dir");
}
$hashFile = new \SplFileInfo($dir->getRealPath() . DIRECTORY_SEPARATOR . $filename);
if (!file_exists($hashFile) && !touch($hashFile)) {
throw new JSONDiskCacheException("Error creating empty hash file {$hashFile->getFilename()}");
}
if (!$hashFile->isFile()) {
throw new JSONDiskCacheException("{$hashFile->getFilename()} is not a file");
}
$filePerms = $hashFile->getPerms() & 0777;
if ($filePerms !== $perms && !chmod($hashFile, $perms)) {
throw new JSONDiskCacheException(
"Cant change file permissions at {$hashFile->getFilename()}"
);
}
if (!($hashFile->isReadable() && $hashFile->isWritable())) {
throw new JSONDiskCacheException("{$hashFile->getFilename()} is not readable or writable");
}
return $hashFile;
}
}