/
ClassCollectionLoader.php
113 lines (97 loc) · 2.51 KB
/
ClassCollectionLoader.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
namespace Symfony\Foundation;
/*
* This file is part of the symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
*
*
* @package symfony
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
*/
class ClassCollectionLoader
{
static public function load($classes, $cacheDir, $name, $autoReload)
{
$cache = $cacheDir.'/'.$name.'.php';
// auto-reload
$reload = false;
if ($autoReload)
{
$metadata = $cacheDir.'/'.$name.'.meta';
if (!file_exists($metadata) || !file_exists($cache))
{
$reload = true;
}
else
{
$time = filemtime($cache);
$meta = unserialize(file_get_contents($metadata));
if ($meta[1] != $classes)
{
$reload = true;
}
else
{
foreach ($meta[0] as $resource)
{
if (!file_exists($resource) || filemtime($resource) > $time)
{
$reload = true;
break;
}
}
}
}
}
if (!$reload && file_exists($cache))
{
require_once $cache;
return;
}
$files = array();
$content = '';
foreach ($classes as $class)
{
if (!class_exists($class) && !interface_exists($class))
{
throw new \InvalidArgumentException(sprintf('Unable to load class "%s"', $class));
}
$r = new \ReflectionClass($class);
$files[] = $r->getFileName();
$content .= preg_replace(array('/^\s*<\?php/', '/\?>\s*$/'), '', file_get_contents($r->getFileName()));
}
// cache the core classes
if (!is_dir(dirname($cache)))
{
mkdir(dirname($cache), 0777, true);
}
self::writeCacheFile($cache, Kernel::stripComments('<?php '.$content));
if ($autoReload)
{
// save the resources
self::writeCacheFile($metadata, serialize(array($files, $classes)));
}
}
static protected function writeCacheFile($file, $content)
{
$tmpFile = tempnam(dirname($file), basename($file));
if (!$fp = @fopen($tmpFile, 'wb'))
{
die(sprintf('Failed to write cache file "%s".', $tmpFile));
}
@fwrite($fp, $content);
@fclose($fp);
if ($content != file_get_contents($tmpFile))
{
die(sprintf('Failed to write cache file "%s" (cache corrupted).', $tmpFile));
}
@rename($tmpFile, $file);
chmod($file, 0644);
}
}