• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / di / 40354306213

26 Oct 2026 03:56PM UTC coverage: 90.858% (+19.0%) from 71.881%
40354306213

push

github

dg
removed Statement compatibility shims from expression classes WIP

3 of 3 new or added lines in 2 files covered. (100.0%)

188 existing lines in 38 files now uncovered.

2733 of 3008 relevant lines covered (90.86%)

0.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.82
/src/DI/ContainerLoader.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace Nette\DI;
9

10
use Nette;
11
use Nette\DI\Compiler\DependencyChecker;
12
use function function_exists, is_string, sprintf, strlen;
13

14

15
/**
16
 * DI container loader.
17
 */
18
class ContainerLoader
19
{
20
        /** @var array<string, array<string, string>>  compiled file => [content hash => loaded class] (auto-rebuild only) */
21
        private static array $loaded = [];
22

23

24
        public function __construct(
1 ✔
25
                private readonly string $tempDirectory,
26
                private readonly bool $autoRebuild = false,
27
        ) {
28
        }
1 ✔
29

30

31
        /**
32
         * Loads the container class, generating it if not already cached. Returns the class name.
33
         * @param  callable(Compiler): ?string  $generator
34
         * @return class-string<Container>
35
         */
36
        public function load(callable $generator, mixed $key = null): string
37
        {
38
                $class = $this->getClassName($key);
1 ✔
39
                $file = "$this->tempDirectory/$class.php";
1 ✔
40
                if ($this->autoRebuild) {
1 ✔
41
                        return $this->loadCurrent($class, $file, $generator(...));
1 ✔
42
                } else {
43
                        $this->loadOnce($class, $file, $generator(...));
1 ✔
44
                        return $class;
1 ✔
45
                }
46
        }
47

48

49
        /**
50
         * Returns the base class name derived from the given key (with auto-rebuild an alias of the first loaded container).
51
         */
52
        public function getClassName(mixed $key): string
53
        {
54
                return 'Container_' . substr(hash('xxh128', serialize($key)), 0, 10);
1 ✔
55
        }
56

57

58
        /**
59
         * Includes the file at most once; it is never rebuilt.
60
         * @param  (\Closure(Compiler): ?string)  $generator
61
         */
62
        private function loadOnce(string $class, string $file, \Closure $generator): void
63
        {
64
                if (class_exists($class, false) || (@include $file) !== false) { // @ - file may not exist
1 ✔
65
                        return;
1 ✔
66
                }
67

68
                $this->withLock($file, function () use ($class, $file, $generator): void {
1 ✔
69
                        if (!is_file($file)) {
1 ✔
70
                                $this->writeContainer($class, $file, $generator);
1 ✔
71
                        }
72

73
                        if ((@include $file) === false) { // @ - error escalated to exception
1 ✔
UNCOV
74
                                throw new Nette\IOException(sprintf("Unable to include '%s'.", $file));
×
75
                        }
76
                });
1 ✔
77
        }
1 ✔
78

79

80
        /**
81
         * Rebuilds the file when expired and includes it whenever its content has not been loaded yet.
82
         * Every build declares a fresh class (the file returns its name), as PHP cannot redeclare a loaded one.
83
         * @param  (\Closure(Compiler): ?string)  $generator
84
         */
85
        private function loadCurrent(string $class, string $file, \Closure $generator): string
86
        {
87
                if (isset(self::$loaded[$file]) && !$this->isExpired($file)) {
1 ✔
88
                        $code = @file_get_contents($file); // @ - file may not exist
1 ✔
89
                        if ($code !== false && ($loaded = self::$loaded[$file][hash('xxh128', $code)] ?? null)) {
1 ✔
90
                                return $loaded;
1 ✔
91
                        }
92
                }
93

94
                return $this->withLock($file, function () use ($class, $file, $generator): string {
1 ✔
95
                        if (!is_file($file) || $this->isExpired($file, $updatedMeta)) {
1 ✔
96
                                if (isset($updatedMeta)) {
1 ✔
UNCOV
97
                                        $this->atomicWrite("$file.meta", $updatedMeta);
×
98
                                } else {
99
                                        $unique = $class . '_' . bin2hex(random_bytes(4));
1 ✔
100
                                        $this->writeContainer($unique, $file, $generator, returnClass: $unique);
1 ✔
101
                                }
102
                        }
103

104
                        $code = @file_get_contents($file); // @ - error escalated to exception
1 ✔
105
                        if ($code === false) {
1 ✔
UNCOV
106
                                throw new Nette\IOException(sprintf("Unable to read '%s'. %s", $file, Nette\Utils\Helpers::getLastError()));
×
107
                        }
108

109
                        return self::$loaded[$file][hash('xxh128', $code)] ??= $this->includeFreshFile($class, $file);
1 ✔
110
                });
1 ✔
111
        }
112

113

114
        /**
115
         * Includes a file whose content has not been loaded yet and returns the class it declares.
116
         */
117
        private function includeFreshFile(string $class, string $file): string
118
        {
119
                if (
120
                        !isset(self::$loaded[$file])
1 ✔
121
                        && class_exists($class, false)
1 ✔
122
                        && realpath((new \ReflectionClass($class))->getFileName() ?: '') === realpath($file)
1 ✔
123
                ) {
124
                        return $class; // included outside of this loader
×
125
                }
126

127
                if (function_exists('opcache_invalidate')) {
1 ✔
128
                        @opcache_invalidate($file, force: true); // @ can be restricted; the file may have been rebuilt by another process
1 ✔
129
                }
130

131
                $declared = @include $file; // @ - error escalated to exception
1 ✔
132
                if ($declared === false) {
1 ✔
133
                        throw new Nette\IOException(sprintf("Unable to include '%s'.", $file));
×
134
                } elseif (!is_string($declared) || !class_exists($declared, false)) {
1 ✔
135
                        $declared = $class; // the file declares $class itself: built without auto-rebuild or by a custom generator
1 ✔
136
                }
137

138
                if (!class_exists($declared, false)) {
1 ✔
139
                        throw new Nette\InvalidStateException(sprintf("File '%s' does not declare class %s.", $file, $class));
×
140
                } elseif (!class_exists($class, false)) {
1 ✔
141
                        class_alias($declared, $class); // getClassName() stays a valid name of the first loaded container
1 ✔
142
                }
143

144
                return $declared;
1 ✔
145
        }
146

147

148
        /** @param  (\Closure(Compiler): ?string)  $generator */
149
        private function writeContainer(string $class, string $file, \Closure $generator, ?string $returnClass = null): void
150
        {
151
                [$code, $meta] = $this->generate($class, $generator);
1 ✔
152
                $this->atomicWrite($file, $returnClass ? "$code\nreturn " . var_export($returnClass, return: true) . ";\n" : $code);
1 ✔
153
                $this->atomicWrite("$file.meta", $meta);
1 ✔
154
        }
1 ✔
155

156

157
        /**
158
         * Runs $fn holding an exclusive lock on the sibling .lock file (against concurrent compilation).
159
         * @param  \Closure(): mixed  $fn
160
         */
161
        private function withLock(string $file, \Closure $fn): mixed
162
        {
163
                Nette\Utils\FileSystem::createDir($this->tempDirectory);
1 ✔
164

165
                $handle = @fopen("$file.lock", 'c+'); // @ is escalated to exception
1 ✔
166
                if (!$handle) {
1 ✔
167
                        throw new Nette\IOException(sprintf("Unable to create file '%s.lock'. %s", $file, Nette\Utils\Helpers::getLastError()));
×
168
                } elseif (!@flock($handle, LOCK_EX)) { // @ is escalated to exception
1 ✔
169
                        throw new Nette\IOException(sprintf(
×
170
                                "Unable to acquire exclusive lock on '%s.lock'. %s",
UNCOV
171
                                $file,
×
UNCOV
172
                                Nette\Utils\Helpers::getLastError(),
×
173
                        ));
174
                }
175

176
                try {
177
                        return $fn();
1 ✔
178
                } finally {
179
                        flock($handle, LOCK_UN);
1 ✔
180
                }
181
        }
182

183

184
        /**
185
         * Atomically writes $content to $file through a temporary file and rename(); on Windows the rename
186
         * is retried briefly, as the target may be momentarily locked by antivirus or opcache.
187
         */
188
        private function atomicWrite(string $file, string $content): void
189
        {
190
                $tmp = "$file.tmp";
1 ✔
191
                if (file_put_contents($tmp, $content) !== strlen($content)) {
1 ✔
UNCOV
192
                        @unlink($tmp); // @ - file may not exist
×
UNCOV
193
                        throw new Nette\IOException(sprintf("Unable to create file '%s'. %s", $file, Nette\Utils\Helpers::getLastError()));
×
194
                }
195

196
                if (function_exists('opcache_invalidate')) {
1 ✔
197
                        @opcache_invalidate($file, force: true); // @ can be restricted; frees a possible handle on the old target
1 ✔
198
                }
199

200
                for ($attempt = 1; !@rename($tmp, $file); $attempt++) { // @ is escalated to exception below
1 ✔
201
                        if ($attempt >= 3 || !Nette\Utils\Helpers::IsWindows) {
×
UNCOV
202
                                @unlink($tmp); // @ - file may not exist
×
UNCOV
203
                                throw new Nette\IOException(sprintf("Unable to create file '%s'. %s", $file, Nette\Utils\Helpers::getLastError()));
×
204
                        }
UNCOV
205
                        usleep(100_000);
×
206
                }
207

208
                if (function_exists('opcache_invalidate')) {
1 ✔
209
                        @opcache_invalidate($file, force: true); // @ can be restricted; refresh with the new content
1 ✔
210
                }
211
        }
1 ✔
212

213

214
        private function isExpired(string $file, ?string &$updatedMeta = null): bool
215
        {
216
                $meta = @unserialize((string) file_get_contents("$file.meta")); // @ - file may not exist
1 ✔
217
                $orig = $meta[2] ?? null;
1 ✔
218
                return empty($meta[0])
1 ✔
219
                        || DependencyChecker::isExpired(...$meta)
1 ✔
220
                        || ($orig !== $meta[2] && $updatedMeta = serialize($meta));
1 ✔
221
        }
222

223

224
        /**
225
         * @param  callable(Compiler): ?string  $generator
226
         * @return array{string, string} code, file
227
         */
228
        protected function generate(string $class, callable $generator): array
229
        {
230
                $compiler = new Compiler;
1 ✔
231
                $compiler->setClassName($class);
1 ✔
232
                $code = $generator(...[&$compiler]) ?? $compiler->compile();
1 ✔
233
                return [
234
                        "<?php\n$code",
1 ✔
235
                        serialize($compiler->exportDependencies()),
1 ✔
236
                ];
237
        }
238
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc