-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
Resolver.php
624 lines (512 loc) 路 18.5 KB
/
Resolver.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\DI;
use Nette;
use Nette\DI\Definitions\Definition;
use Nette\DI\Definitions\Reference;
use Nette\DI\Definitions\Statement;
use Nette\PhpGenerator\Helpers as PhpHelpers;
use Nette\Utils\Arrays;
use Nette\Utils\Callback;
use Nette\Utils\Reflection;
use Nette\Utils\Validators;
/**
* Services resolver
* @internal
*/
class Resolver
{
private ContainerBuilder $builder;
private ?Definition $currentService = null;
private ?string $currentServiceType = null;
private bool $currentServiceAllowed = false;
/** circular reference detector */
private \SplObjectStorage $recursive;
public function __construct(ContainerBuilder $builder)
{
$this->builder = $builder;
$this->recursive = new \SplObjectStorage;
}
public function getContainerBuilder(): ContainerBuilder
{
return $this->builder;
}
public function resolveDefinition(Definition $def): void
{
if ($this->recursive->contains($def)) {
$names = array_map(fn($item) => $item->getName(), iterator_to_array($this->recursive));
throw new ServiceCreationException(sprintf('Circular reference detected for services: %s.', implode(', ', $names)));
}
try {
$this->recursive->attach($def);
$def->resolveType($this);
if (!$def->getType()) {
throw new ServiceCreationException('Type of service is unknown.');
}
} catch (\Throwable $e) {
throw $this->completeException($e, $def);
} finally {
$this->recursive->detach($def);
}
}
public function resolveReferenceType(Reference $ref): ?string
{
if ($ref->isSelf()) {
return $this->currentServiceType;
} elseif ($ref->isType()) {
return ltrim($ref->getValue(), '\\');
}
$def = $this->resolveReference($ref);
if (!$def->getType()) {
$this->resolveDefinition($def);
}
return $def->getType();
}
public function resolveEntityType(Statement $statement): ?string
{
$entity = $this->normalizeEntity($statement);
if ($statement->arguments === self::getFirstClassCallable()) {
return \Closure::class;
} elseif (is_array($entity)) {
if ($entity[0] instanceof Reference || $entity[0] instanceof Statement) {
$entity[0] = $this->resolveEntityType($entity[0] instanceof Statement ? $entity[0] : new Statement($entity[0]));
if (!$entity[0]) {
return null;
}
}
try {
$reflection = Callback::toReflection($entity[0] === '' ? $entity[1] : $entity);
assert($reflection instanceof \ReflectionMethod || $reflection instanceof \ReflectionFunction);
$refClass = $reflection instanceof \ReflectionMethod
? $reflection->getDeclaringClass()
: null;
} catch (\ReflectionException $e) {
$refClass = $reflection = null;
}
if (isset($e) || ($refClass && (!$reflection->isPublic()
|| ($refClass->isTrait() && !$reflection->isStatic())
))) {
throw new ServiceCreationException(sprintf('Method %s() is not callable.', Callback::toString($entity)), 0, $e ?? null);
}
$this->addDependency($reflection);
$type = Nette\Utils\Type::fromReflection($reflection);
return $type && !in_array($type->getSingleName(), ['object', 'mixed'], strict: true)
? Helpers::ensureClassType($type, sprintf('return type of %s()', Callback::toString($entity)), allowNullable: true)
: null;
} elseif ($entity instanceof Reference) { // alias or factory
return $this->resolveReferenceType($entity);
} elseif (is_string($entity)) { // class
if (!class_exists($entity)) {
throw new ServiceCreationException(sprintf(
interface_exists($entity)
? "Interface %s can not be used as 'create' or 'factory', did you mean 'implement'?"
: "Class '%s' not found.",
$entity,
));
}
return $entity;
}
return null;
}
public function completeDefinition(Definition $def): void
{
$this->currentService = in_array($def, $this->builder->getDefinitions(), strict: true)
? $def
: null;
$this->currentServiceType = $def->getType();
$this->currentServiceAllowed = false;
try {
$def->complete($this);
$this->addDependency(new \ReflectionClass($def->getType()));
} catch (\Throwable $e) {
throw $this->completeException($e, $def);
} finally {
$this->currentService = $this->currentServiceType = null;
}
}
public function completeStatement(Statement $statement, bool $currentServiceAllowed = false): Statement
{
$this->currentServiceAllowed = $currentServiceAllowed;
$entity = $this->normalizeEntity($statement);
$arguments = $this->convertReferences($statement->arguments);
$getter = fn(string $type, bool $single) => $single
? $this->getByType($type)
: array_values(array_filter($this->builder->findAutowired($type), fn($obj) => $obj !== $this->currentService));
switch (true) {
case $statement->arguments === self::getFirstClassCallable():
if (!is_array($entity) || !PhpHelpers::isIdentifier($entity[1])) {
throw new ServiceCreationException(sprintf('Cannot create closure for %s(...)', $entity));
}
if ($entity[0] instanceof Statement) {
$entity[0] = $this->completeStatement($entity[0], $this->currentServiceAllowed);
}
break;
case is_string($entity) && str_contains($entity, '?'): // PHP literal
break;
case $entity === 'not':
case $entity === 'bool':
case $entity === 'int':
case $entity === 'float':
case $entity === 'string':
if (count($arguments) !== 1) {
throw new ServiceCreationException(sprintf('Function %s() expects 1 parameter, %s given.', $entity, count($arguments)));
}
break;
case is_string($entity): // create class
if (!class_exists($entity)) {
throw new ServiceCreationException(sprintf("Class '%s' not found.", $entity));
} elseif ((new \ReflectionClass($entity))->isAbstract()) {
throw new ServiceCreationException(sprintf('Class %s is abstract.', $entity));
} elseif (($rm = (new \ReflectionClass($entity))->getConstructor()) !== null && !$rm->isPublic()) {
throw new ServiceCreationException(sprintf('Class %s has %s constructor.', $entity, $rm->isProtected() ? 'protected' : 'private'));
} elseif ($constructor = (new \ReflectionClass($entity))->getConstructor()) {
$arguments = self::autowireArguments($constructor, $arguments, $getter);
$this->addDependency($constructor);
} elseif ($arguments) {
throw new ServiceCreationException(sprintf(
'Unable to pass arguments, class %s has no constructor.',
$entity,
));
}
break;
case $entity instanceof Reference:
$entity = [new Reference(ContainerBuilder::ThisContainer), Container::getMethodName($entity->getValue())];
break;
case is_array($entity):
if (!preg_match('#^\$?(\\\\?' . PhpHelpers::ReIdentifier . ')+(\[\])?$#D', $entity[1])) {
throw new ServiceCreationException(sprintf(
"Expected function, method or property name, '%s' given.",
$entity[1],
));
}
switch (true) {
case $entity[0] === '': // function call
if (!Arrays::isList($arguments)) {
throw new ServiceCreationException(sprintf(
'Unable to pass specified arguments to %s.',
$entity[0],
));
} elseif (!function_exists($entity[1])) {
throw new ServiceCreationException(sprintf("Function %s doesn't exist.", $entity[1]));
}
$rf = new \ReflectionFunction($entity[1]);
$arguments = self::autowireArguments($rf, $arguments, $getter);
$this->addDependency($rf);
break;
case $entity[0] instanceof Statement:
$entity[0] = $this->completeStatement($entity[0], $this->currentServiceAllowed);
// break omitted
case is_string($entity[0]): // static method call
case $entity[0] instanceof Reference:
if ($entity[1][0] === '$') { // property getter, setter or appender
Validators::assert($arguments, 'list:0..1', "setup arguments for '" . Callback::toString($entity) . "'");
if (!$arguments && str_ends_with($entity[1], '[]')) {
throw new ServiceCreationException(sprintf('Missing argument for %s.', $entity[1]));
}
} elseif (
$type = $entity[0] instanceof Reference
? $this->resolveReferenceType($entity[0])
: $this->resolveEntityType($entity[0] instanceof Statement ? $entity[0] : new Statement($entity[0]))
) {
$rc = new \ReflectionClass($type);
if ($rc->hasMethod($entity[1])) {
$rm = $rc->getMethod($entity[1]);
if (!$rm->isPublic()) {
throw new ServiceCreationException(sprintf('%s::%s() is not callable.', $type, $entity[1]));
}
$arguments = self::autowireArguments($rm, $arguments, $getter);
$this->addDependency($rm);
} elseif (!Arrays::isList($arguments)) {
throw new ServiceCreationException(sprintf('Unable to pass specified arguments to %s::%s().', $type, $entity[1]));
}
}
}
}
try {
$arguments = $this->completeArguments($arguments);
} catch (ServiceCreationException $e) {
if (!str_contains($e->getMessage(), "\nRelated to")) {
if (is_string($entity)) {
$desc = $entity . '::__construct()';
} else {
$desc = Helpers::entityToString($entity);
$desc = preg_replace('~@self::~A', '', $desc);
}
if ($currentServiceAllowed) {
$desc .= ' in setup';
}
$e->setMessage($e->getMessage() . "\nRelated to $desc.");
}
throw $e;
}
return new Statement($entity, $arguments);
}
public function completeArguments(array $arguments): array
{
array_walk_recursive($arguments, function (&$val): void {
if ($val instanceof Statement) {
$entity = $val->getEntity();
if ($entity === 'typed' || $entity === 'tagged') {
$services = [];
$current = $this->currentService?->getName();
foreach ($val->arguments as $argument) {
foreach ($entity === 'tagged' ? $this->builder->findByTag($argument) : $this->builder->findAutowired($argument) as $name => $foo) {
if ($name !== $current) {
$services[] = new Reference($name);
}
}
}
$val = $this->completeArguments($services);
} else {
$val = $this->completeStatement($val, $this->currentServiceAllowed);
}
} elseif ($val instanceof Definition || $val instanceof Reference) {
$val = $this->normalizeEntity(new Statement($val));
}
});
return $arguments;
}
/** Returns literal, Class, Reference, [Class, member], [, globalFunc], [Reference, member], [Statement, member] */
private function normalizeEntity(Statement $statement): string|array|Reference|null
{
$entity = $statement->getEntity();
if (is_array($entity)) {
$item = &$entity[0];
} else {
$item = &$entity;
}
if ($item instanceof Definition) {
$name = current(array_keys($this->builder->getDefinitions(), $item, strict: true));
if ($name === false) {
throw new ServiceCreationException(sprintf("Service '%s' not found in definitions.", $item->getName()));
}
$item = new Reference($name);
}
if ($item instanceof Reference) {
$item = $this->normalizeReference($item);
}
return $entity;
}
/**
* Normalizes reference to 'self' or named reference (or leaves it typed if it is not possible during resolving) and checks existence of service.
*/
public function normalizeReference(Reference $ref): Reference
{
$service = $ref->getValue();
if ($ref->isSelf()) {
return $ref;
} elseif ($ref->isName()) {
if (!$this->builder->hasDefinition($service)) {
throw new ServiceCreationException(sprintf("Reference to missing service '%s'.", $service));
}
return $this->currentService && $service === $this->currentService->getName()
? new Reference(Reference::Self)
: $ref;
}
try {
return $this->getByType($service);
} catch (NotAllowedDuringResolvingException) {
return new Reference($service);
}
}
public function resolveReference(Reference $ref): Definition
{
return $ref->isSelf()
? $this->currentService
: $this->builder->getDefinition($ref->getValue());
}
/**
* Returns named reference to service resolved by type (or 'self' reference for local-autowiring).
* @throws ServiceCreationException when multiple found
* @throws MissingServiceException when not found
*/
public function getByType(string $type): Reference
{
if (
$this->currentService
&& $this->currentServiceAllowed
&& is_a($this->currentServiceType, $type, allow_string: true)
) {
return new Reference(Reference::Self);
}
$name = $this->builder->getByType($type, throw: true);
if (
!$this->currentServiceAllowed
&& $this->currentService === $this->builder->getDefinition($name)
) {
throw new MissingServiceException;
}
return new Reference($name);
}
/**
* Adds item to the list of dependencies.
*/
public function addDependency(\ReflectionClass|\ReflectionFunctionAbstract|string $dep): static
{
$this->builder->addDependency($dep);
return $this;
}
private function completeException(\Throwable $e, Definition $def): ServiceCreationException
{
$message = $e->getMessage();
if ($e instanceof ServiceCreationException && str_starts_with($message, '[Service ')) {
return $e;
}
if ($tmp = $def->getType()) {
$message = str_replace(" $tmp::", ' ' . preg_replace('~.*\\\\~', '', $tmp) . '::', $message);
}
$message = '[' . $def->getDescriptor() . "]\n" . $message;
return $e instanceof ServiceCreationException
? $e->setMessage($message)
: new ServiceCreationException($message, 0, $e);
}
private function convertReferences(array $arguments): array
{
array_walk_recursive($arguments, function (&$val): void {
if (is_string($val) && strlen($val) > 1 && $val[0] === '@' && $val[1] !== '@') {
$pair = explode('::', substr($val, 1), 2);
if (!isset($pair[1])) { // @service
$val = new Reference($pair[0]);
} elseif (preg_match('#^[A-Z][a-zA-Z0-9_]*$#D', $pair[1])) { // @service::CONSTANT
$val = ContainerBuilder::literal($this->resolveReferenceType(new Reference($pair[0])) . '::' . $pair[1]);
} else { // @service::property
$val = new Statement([new Reference($pair[0]), '$' . $pair[1]]);
}
} elseif (is_string($val) && str_starts_with($val, '@@')) { // escaped text @@
$val = substr($val, 1);
}
});
return $arguments;
}
/**
* Add missing arguments using autowiring.
* @param (callable(string $type, bool $single): (object|object[]|null)) $getter
* @throws ServiceCreationException
*/
public static function autowireArguments(
\ReflectionFunctionAbstract $method,
array $arguments,
callable $getter,
): array
{
$useName = false;
$num = -1;
$res = [];
foreach ($method->getParameters() as $num => $param) {
$paramName = $param->name;
if ($param->isVariadic()) {
if ($useName && Arrays::some($arguments, fn($val, $key) => is_int($key))) {
throw new ServiceCreationException(sprintf(
'Cannot use positional argument after named or omitted argument in %s.',
Reflection::toString($param),
));
} elseif (array_key_exists($paramName, $arguments)) {
if (!is_array($arguments[$paramName])) {
throw new ServiceCreationException(sprintf(
'Parameter %s must be array, %s given.',
Reflection::toString($param),
gettype($arguments[$paramName]),
));
}
$res = array_merge($res, $arguments[$paramName]);
unset($arguments[$paramName]);
} else {
$res = array_merge($res, $arguments);
$arguments = [];
}
} elseif (array_key_exists($key = $paramName, $arguments) || array_key_exists($key = $num, $arguments)) {
$val = $arguments[$key];
$res[$useName ? $paramName : $num] = is_scalar($val) && $param->getAttributes(\SensitiveParameter::class)
? ContainerBuilder::literal('/*sensitive{*/?/*}*/', [$val])
: $val;
unset($arguments[$key], $arguments[$num]); // unset $num to enable overwriting in configuration
} elseif (($aw = self::autowireArgument($param, $getter)) !== null) {
$res[$useName ? $paramName : $num] = $aw;
} else {
$useName = true; // is optional
}
}
// extra parameters
while (!$useName && array_key_exists(++$num, $arguments)) {
$res[$num] = $arguments[$num];
unset($arguments[$num]);
}
if ($arguments) {
throw new ServiceCreationException(sprintf(
'Unable to pass specified arguments to %s.',
Reflection::toString($method),
));
}
return $res;
}
/**
* Resolves missing argument using autowiring.
* @param (callable(string $type, bool $single): (object|object[]|null)) $getter
* @throws ServiceCreationException
*/
private static function autowireArgument(\ReflectionParameter $parameter, callable $getter): mixed
{
$desc = Reflection::toString($parameter);
$type = Nette\Utils\Type::fromReflection($parameter);
if ($type?->isClass()) {
$class = $type->getSingleName();
try {
$res = $getter($class, true);
} catch (MissingServiceException) {
$res = null;
} catch (ServiceCreationException $e) {
throw new ServiceCreationException(sprintf("%s\nRequired by %s.", $e->getMessage(), $desc), 0, $e);
}
if ($res !== null || $parameter->isOptional()) {
return $res;
} elseif (class_exists($class) || interface_exists($class)) {
throw new ServiceCreationException(sprintf(
"Service of type %s required by %s not found.\nDid you add it to configuration file?",
$class,
$desc,
));
} else {
throw new ServiceCreationException(sprintf(
"Class '%s' required by %s not found.\nCheck the parameter type and 'use' statements.",
$class,
$desc,
));
}
} elseif ($itemType = self::isArrayOf($parameter, $type)) {
return $getter($itemType, false);
} elseif ($parameter->isOptional()) {
return null;
} else {
throw new ServiceCreationException(sprintf(
'Parameter %s has %s, so its value must be specified.',
$desc,
$type && !$type->isSimple() ? 'complex type and no default value' : 'no class type or default value',
));
}
}
private static function isArrayOf(\ReflectionParameter $parameter, ?Nette\Utils\Type $type): ?string
{
$method = $parameter->getDeclaringFunction();
return $method instanceof \ReflectionMethod
&& $type?->getSingleName() === 'array'
&& preg_match(
'#@param[ \t]+(?|([\w\\\\]+)\[\]|list<([\w\\\\]+)>|array<int,\s*([\w\\\\]+)>)[ \t]+\$' . $parameter->name . '#',
(string) $method->getDocComment(),
$m,
)
&& ($itemType = Reflection::expandClassName($m[1], $method->getDeclaringClass()))
&& (class_exists($itemType) || interface_exists($itemType))
? $itemType
: null;
}
/** @internal */
public static function getFirstClassCallable(): array
{
static $x = [new Nette\PhpGenerator\Literal('...')];
return $x;
}
}