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