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: if (!is_callable($generator)) {
40: list($generator, $key) = array($key, $generator);
41: }
42: $class = $this->getClassName($key);
43: if (!class_exists($class, FALSE)) {
44: $this->loadFile($class, $generator);
45: }
46: return $class;
47: }
48:
49:
50: 51: 52:
53: public function getClassName($key)
54: {
55: return 'Container_' . substr(md5(serialize($key)), 0, 10);
56: }
57:
58:
59: 60: 61:
62: private function loadFile($class, $generator)
63: {
64: $file = "$this->tempDirectory/$class.php";
65: if (!$this->isExpired($file) && (@include $file) !== FALSE) {
66: return;
67: }
68:
69: if (!is_dir($this->tempDirectory)) {
70: @mkdir($this->tempDirectory);
71: }
72:
73: $handle = fopen("$file.lock", 'c+');
74: if (!$handle || !flock($handle, LOCK_EX)) {
75: throw new Nette\IOException("Unable to acquire exclusive lock on '$file.lock'.");
76: }
77:
78: if (!is_file($file) || $this->isExpired($file)) {
79: list($toWrite[$file], $toWrite["$file.meta"]) = $this->generate($class, $generator);
80:
81: foreach ($toWrite as $name => $content) {
82: if (file_put_contents("$name.tmp", $content) !== strlen($content) || !rename("$name.tmp", $name)) {
83: @unlink("$name.tmp");
84: throw new Nette\IOException("Unable to create file '$name'.");
85: }
86: }
87: }
88:
89: if ((@include $file) === FALSE) {
90: throw new Nette\IOException("Unable to include '$file'.");
91: }
92: flock($handle, LOCK_UN);
93: }
94:
95:
96: private function isExpired($file)
97: {
98: if ($this->autoRebuild) {
99: $meta = @unserialize(file_get_contents("$file.meta"));
100: $files = $meta ? array_combine($tmp = array_keys($meta), $tmp) : array();
101: return $meta !== @array_map('filemtime', $files);
102: }
103: return FALSE;
104: }
105:
106:
107: 108: 109:
110: protected function generate($class, $generator)
111: {
112: $compiler = new Compiler;
113: $compiler->getContainerBuilder()->setClassName($class);
114: $code = call_user_func_array($generator, array(& $compiler));
115: $code = $code ?: implode("\n\n\n", $compiler->compile());
116: $files = $compiler->getDependencies();
117: $files = $files ? array_combine($files, $files) : array();
118: return array(
119: "<?php\n$code",
120: serialize(@array_map('filemtime', $files)),
121: );
122: }
123:
124: }
125: