-
-
Notifications
You must be signed in to change notification settings - Fork 312
/
Compiler.php
381 lines (330 loc) · 13.9 KB
/
Compiler.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php
declare(strict_types=1);
namespace DI\Compiler;
use DI\Definition\ArrayDefinition;
use DI\Definition\DecoratorDefinition;
use DI\Definition\Definition;
use DI\Definition\EnvironmentVariableDefinition;
use DI\Definition\Exception\InvalidDefinition;
use DI\Definition\FactoryDefinition;
use DI\Definition\ObjectDefinition;
use DI\Definition\Reference;
use DI\Definition\Source\DefinitionSource;
use DI\Definition\StringDefinition;
use DI\Definition\ValueDefinition;
use DI\DependencyException;
use InvalidArgumentException;
use PhpParser\Node\Expr\Closure;
use SuperClosure\Analyzer\AstAnalyzer;
use SuperClosure\Exception\ClosureAnalysisException;
/**
* Compiles the container into PHP code much more optimized for performances.
*
* @author Matthieu Napoli <matthieu@mnapoli.fr>
*/
class Compiler
{
/**
* @var string
*/
private $containerClass;
/**
* @var string
*/
private $containerParentClass;
/**
* Definitions indexed by the entry name. The value can be null if the definition needs to be fetched.
*
* Keys are strings, values are `Definition` objects or null.
*
* @var \ArrayIterator
*/
private $entriesToCompile;
/**
* Map of entry names to method names.
*
* @var string[]
*/
private $entryToMethodMapping = [];
/**
* @var string[]
*/
private $methods = [];
/**
* @var bool
*/
private $autowiringEnabled;
/**
* Compile the container.
*
* @return string The compiled container file name.
*/
public function compile(
DefinitionSource $definitionSource,
string $directory,
string $className,
string $parentClassName,
bool $autowiringEnabled
) : string {
$fileName = rtrim($directory, '/') . '/' . $className . '.php';
if (file_exists($fileName)) {
// The container is already compiled
return $fileName;
}
$this->autowiringEnabled = $autowiringEnabled;
// Validate that a valid class name was provided
$validClassName = preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $className);
if (!$validClassName) {
throw new InvalidArgumentException("The container cannot be compiled: `$className` is not a valid PHP class name");
}
$this->entriesToCompile = new \ArrayIterator($definitionSource->getDefinitions());
// We use an ArrayIterator so that we can keep adding new items to the list while we compile entries
foreach ($this->entriesToCompile as $entryName => $definition) {
$silenceErrors = false;
// This is an entry found by reference during autowiring
if (!$definition) {
$definition = $definitionSource->getDefinition($entryName);
// We silence errors for those entries because type-hints may reference interfaces/abstract classes
// which could later be defined, or even not used (we don't want to block the compilation for those)
$silenceErrors = true;
}
if (!$definition) {
// We do not throw a `NotFound` exception here because the dependency
// could be defined at runtime
continue;
}
// Check that the definition can be compiled
$errorMessage = $this->isCompilable($definition);
if ($errorMessage !== true) {
continue;
}
try {
$this->compileDefinition($entryName, $definition);
} catch (InvalidDefinition $e) {
if ($silenceErrors) {
// forget the entry
unset($this->entryToMethodMapping[$entryName]);
} else {
throw $e;
}
}
}
$this->containerClass = $className;
$this->containerParentClass = $parentClassName;
ob_start();
require __DIR__ . '/Template.php';
$fileContent = ob_get_contents();
ob_end_clean();
$fileContent = "<?php\n" . $fileContent;
$this->createCompilationDirectory(dirname($fileName));
file_put_contents($fileName, $fileContent);
return $fileName;
}
/**
* Use a hash to ensure that the used method names in the CompiledContainer are both unique and idempotent.
*/
private function getHashedValue(string $prefix, string $value): string
{
return $prefix . md5($value);
}
/**
* @throws DependencyException
* @throws InvalidDefinition
* @return string The method name
*/
private function compileDefinition(string $entryName, Definition $definition) : string
{
$methodName = $this->getHashedValue('get', $entryName);
//In case an Entry is already added, the used method should be equal
if(isset($this->entryToMethodMapping[$entryName]) && $this->entryToMethodMapping[$entryName] !== $methodName){
throw new InvalidDefinition(sprintf(
'Entry "%s" cannot be compiled. An Entry with the same name already exists pointing to method %s(), while this one points to method %s().',
$entryName,
$this->entryToMethodMapping[$entryName],
$methodName
));
}
$this->entryToMethodMapping[$entryName] = $methodName;
switch (true) {
case $definition instanceof ValueDefinition:
$value = $definition->getValue();
$code = 'return ' . $this->compileValue($value) . ';';
break;
case $definition instanceof Reference:
$targetEntryName = $definition->getTargetEntryName();
$code = 'return $this->delegateContainer->get(' . $this->compileValue($targetEntryName) . ');';
// If this method is not yet compiled we store it for compilation
if (!isset($this->entriesToCompile[$targetEntryName])) {
$this->entriesToCompile[$targetEntryName] = null;
}
break;
case $definition instanceof StringDefinition:
$entryName = $this->compileValue($definition->getName());
$expression = $this->compileValue($definition->getExpression());
$code = 'return \DI\Definition\StringDefinition::resolveExpression(' . $entryName . ', ' . $expression . ', $this->delegateContainer);';
break;
case $definition instanceof EnvironmentVariableDefinition:
$variableName = $this->compileValue($definition->getVariableName());
$isOptional = $this->compileValue($definition->isOptional());
$defaultValue = $this->compileValue($definition->getDefaultValue());
$code = <<<PHP
\$value = getenv($variableName);
if (false !== \$value) return \$value;
if (!$isOptional) {
throw new \DI\Definition\Exception\InvalidDefinition("The environment variable '{$definition->getVariableName()}' has not been defined");
}
return $defaultValue;
PHP;
break;
case $definition instanceof ArrayDefinition:
try {
$code = 'return ' . $this->compileValue($definition->getValues()) . ';';
} catch (\Exception $e) {
throw new DependencyException(sprintf(
'Error while compiling %s. %s',
$definition->getName(),
$e->getMessage()
), 0, $e);
}
break;
case $definition instanceof ObjectDefinition:
$compiler = new ObjectCreationCompiler($this);
$code = $compiler->compile($definition);
$code .= "\n return \$object;";
break;
case $definition instanceof DecoratorDefinition:
$decoratedDefinition = $definition->getDecoratedDefinition();
if (! $decoratedDefinition instanceof Definition) {
if (! $definition->getName()) {
throw new InvalidDefinition('Decorators cannot be nested in another definition');
}
throw new InvalidDefinition(sprintf(
'Entry "%s" decorates nothing: no previous definition with the same name was found',
$definition->getName()
));
}
$code = sprintf(
'return call_user_func(%s, %s, $this->delegateContainer);',
$this->compileValue($definition->getCallable()),
$this->compileValue($decoratedDefinition)
);
break;
case $definition instanceof FactoryDefinition:
$value = $definition->getCallable();
// Custom error message to help debugging
$isInvokableClass = is_string($value) && class_exists($value) && method_exists($value, '__invoke');
if ($isInvokableClass && !$this->autowiringEnabled) {
throw new InvalidDefinition(sprintf(
'Entry "%s" cannot be compiled. Invokable classes cannot be automatically resolved if autowiring is disabled on the container, you need to enable autowiring or define the entry manually.',
$entryName
));
}
$definitionParameters = '';
if (!empty($definition->getParameters())) {
$definitionParameters = ', ' . $this->compileValue($definition->getParameters());
}
$code = sprintf(
'return $this->resolveFactory(%s, %s%s);',
$this->compileValue($value),
var_export($entryName, true),
$definitionParameters
);
break;
default:
// This case should not happen (so it cannot be tested)
throw new \Exception('Cannot compile definition of type ' . get_class($definition));
}
$this->methods[$methodName] = $code;
return $methodName;
}
public function compileValue($value) : string
{
// Check that the value can be compiled
$errorMessage = $this->isCompilable($value);
if ($errorMessage !== true) {
throw new InvalidDefinition($errorMessage);
}
if ($value instanceof Definition) {
$subEntryName = $this->getHashedValue('SubEntry', $value->getName() . $value);
// Compile the sub-definition in another method
$methodName = $this->compileDefinition($subEntryName, $value);
// The value is now a method call to that method (which returns the value)
return "\$this->$methodName()";
}
if (is_array($value)) {
$value = array_map(function ($value, $key) {
$compiledValue = $this->compileValue($value);
$key = var_export($key, true);
return " $key => $compiledValue,\n";
}, $value, array_keys($value));
$value = implode('', $value);
return "[\n$value ]";
}
if ($value instanceof \Closure) {
return $this->compileClosure($value);
}
return var_export($value, true);
}
private function createCompilationDirectory(string $directory)
{
if (!is_dir($directory) && !@mkdir($directory, 0777, true)) {
throw new InvalidArgumentException(sprintf('Compilation directory does not exist and cannot be created: %s.', $directory));
}
if (!is_writable($directory)) {
throw new InvalidArgumentException(sprintf('Compilation directory is not writable: %s.', $directory));
}
}
/**
* @return string|true If null is returned that means that the value is compilable.
*/
private function isCompilable($value)
{
if ($value instanceof ValueDefinition) {
return $this->isCompilable($value->getValue());
}
if ($value instanceof DecoratorDefinition) {
if (empty($value->getName())) {
return 'Decorators cannot be nested in another definition';
}
}
// All other definitions are compilable
if ($value instanceof Definition) {
return true;
}
if ($value instanceof \Closure) {
return true;
}
if (is_object($value)) {
return 'An object was found but objects cannot be compiled';
}
if (is_resource($value)) {
return 'A resource was found but resources cannot be compiled';
}
return true;
}
private function compileClosure(\Closure $closure) : string
{
$closureAnalyzer = new AstAnalyzer;
try {
$closureData = $closureAnalyzer->analyze($closure);
} catch (ClosureAnalysisException $e) {
if (stripos($e->getMessage(), 'Two closures were declared on the same line') !== false) {
throw new InvalidDefinition('Cannot compile closures when two closures are defined on the same line', 0, $e);
}
throw $e;
}
/** @var Closure $ast */
$ast = $closureData['ast'];
// Force all closures to be static (add the `static` keyword), i.e. they can't use
// $this, which makes sense since their code is copied into another class.
$ast->static = true;
// Check if the closure imports variables with `use`
if (! empty($ast->uses)) {
throw new InvalidDefinition('Cannot compile closures which import variables using the `use` keyword');
}
$code = (new \PhpParser\PrettyPrinter\Standard)->prettyPrint([$ast]);
// Trim spaces and the last `;`
$code = trim($code, "\t\n\r;");
return $code;
}
}