1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\DI;
9:
10: use Nette;
11:
12:
13: 14: 15:
16: class ContainerLoader extends Nette\Object
17: {
18:
19: private $autoRebuild = FALSE;
20:
21:
22: private $tempDirectory;
23:
24:
25: public function __construct($tempDirectory, $autoRebuild = FALSE)
26: {
27: $this->tempDirectory = $tempDirectory;
28: $this->autoRebuild = $autoRebuild;
29: }
30:
31:
32: 33: 34: 35: 36:
37: public function load($key, $generator)
38: {
39: $class = $this->getClassName($key);
40: if (!class_exists($class, FALSE)) {
41: $this->loadFile($class, $generator);
42: }
43: return $class;
44: }
45:
46:
47: 48: 49:
50: public function getClassName($key)
51: {
52: return 'Container_' . substr(md5(serialize($key)), 0, 10);
53: }
54:
55:
56: 57: 58:
59: private function loadFile($class, $generator)
60: {
61: $file = "$this->tempDirectory/$class.php";
62: if (!$this->isExpired($file) && (@include $file) !== FALSE) {
63: return;
64: }
65:
66: if (!is_dir($this->tempDirectory)) {
67: @mkdir($this->tempDirectory);
68: }
69:
70: $handle = fopen("$file.lock", 'c+');
71: if (!$handle || !flock($handle, LOCK_EX)) {
72: throw new Nette\IOException("Unable to acquire exclusive lock on '$file.lock'.");
73: }
74:
75: if (!is_file($file) || $this->isExpired($file)) {
76: list($toWrite[$file], $toWrite["$file.meta"]) = $this->generate($class, $generator);
77:
78: foreach ($toWrite as $name => $content) {
79: if (file_put_contents("$name.tmp", $content) !== strlen($content) || !rename("$name.tmp", $name)) {
80: @unlink("$name.tmp");
81: throw new Nette\IOException("Unable to create file '$name'.");
82: }
83: }
84: }
85:
86: if ((@include $file) === FALSE) {
87: throw new Nette\IOException("Unable to include '$file'.");
88: }
89: flock($handle, LOCK_UN);
90: }
91:
92:
93: private function isExpired($file)
94: {
95: if ($this->autoRebuild) {
96: $meta = @unserialize(file_get_contents("$file.meta"));
97: $files = $meta ? array_combine($tmp = array_keys($meta), $tmp) : array();
98: return $meta !== @array_map('filemtime', $files);
99: }
100: return FALSE;
101: }
102:
103:
104: 105: 106:
107: protected function generate($class, $generator)
108: {
109: $compiler = new Compiler;
110: $compiler->getContainerBuilder()->setClassName($class);
111: $code = call_user_func_array($generator, array(& $compiler));
112: $code = $code ?: implode("\n\n\n", $compiler->compile());
113: $files = $compiler->getDependencies();
114: $files = $files ? array_combine($files, $files) : array();
115: return array(
116: "<?php\n$code",
117: serialize(@array_map('filemtime', $files)),
118: );
119: }
120:
121: }
122: