1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Cubiche package. |
4
|
|
|
* |
5
|
|
|
* Copyright (c) Cubiche |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Cubiche\Core\Metadata\Cache; |
12
|
|
|
|
13
|
|
|
use Cubiche\Core\Metadata\ClassMetadata; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* FileCache class. |
17
|
|
|
* |
18
|
|
|
* @author Ivannis Suárez Jerez <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
class FileCache implements CacheInterface |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @var string |
24
|
|
|
*/ |
25
|
|
|
protected $cacheDirectory; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* FileCache constructor. |
29
|
|
|
* |
30
|
|
|
* @param string $cacheDirectory |
31
|
|
|
*/ |
32
|
|
|
public function __construct($cacheDirectory) |
33
|
|
|
{ |
34
|
|
|
if (!is_dir($cacheDirectory)) { |
35
|
|
|
mkdir($cacheDirectory, 0755, true); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
if (!is_writable($cacheDirectory)) { |
39
|
|
|
throw new \InvalidArgumentException(sprintf('The directory "%s" is not writable.', $cacheDirectory)); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$this->cacheDirectory = rtrim($cacheDirectory, '\\/'); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* {@inheritdoc} |
47
|
|
|
*/ |
48
|
|
|
public function load($className) |
49
|
|
|
{ |
50
|
|
|
$filename = $this->fileName($className); |
51
|
|
|
if (!file_exists($filename)) { |
52
|
|
|
return; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return include $filename; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* {@inheritdoc} |
60
|
|
|
*/ |
61
|
|
|
public function save(ClassMetadata $metadata) |
62
|
|
|
{ |
63
|
|
|
$filename = $this->fileName($metadata->className()); |
64
|
|
|
|
65
|
|
|
$tmpFile = tempnam($this->cacheDirectory, 'metadata-cache'); |
66
|
|
|
file_put_contents($tmpFile, '<?php return unserialize('.var_export(serialize($metadata), true).');'); |
67
|
|
|
|
68
|
|
|
@chmod($tmpFile, 0666 & ~umask()); |
|
|
|
|
69
|
|
|
$this->renameFile($tmpFile, $filename); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Renames a file with fallback for windows. |
74
|
|
|
* |
75
|
|
|
* @param string $source |
76
|
|
|
* @param string $target |
77
|
|
|
*/ |
78
|
|
|
private function renameFile($source, $target) |
79
|
|
|
{ |
80
|
|
|
if (false === @rename($source, $target)) { |
81
|
|
|
throw new \RuntimeException(sprintf('Could not write new cache file to %s.', $target)); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @param string $className |
87
|
|
|
* |
88
|
|
|
* @return string |
89
|
|
|
*/ |
90
|
|
|
protected function fileName($className) |
91
|
|
|
{ |
92
|
|
|
return $this->cacheDirectory.'/'.strtr($className, '\\', '-').'.cache.php'; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|
If you suppress an error, we recommend checking for the error condition explicitly: