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

nette / di / 40220877596

25 Oct 2026 06:21PM UTC coverage: 93.845% (-0.07%) from 93.911%
40220877596

push

github

dg
added upgrading.md

2287 of 2437 relevant lines covered (93.84%)

0.94 hits per line

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

95.69
/src/DI/Resolver.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\Definitions\{Definition, Reference, Statement};
12
use Nette\PhpGenerator\Helpers as PhpHelpers;
13
use Nette\Utils\{Arrays, Callback, Reflection, Validators};
14
use function array_key_exists, count, gettype, in_array, is_array, is_int, is_string, sprintf, strlen;
15

16

17
/**
18
 * Resolves and completes service definitions, including autowiring of arguments.
19
 * @internal
20
 */
21
class Resolver
22
{
23
        private ?Definition $currentService = null;
24
        private ?string $currentServiceType = null;
25
        private bool $currentServiceAllowed = false;
26

27
        /** @var \SplObjectStorage<Definition, true> circular reference detector */
28
        private \SplObjectStorage $recursive;
29

30

31
        public function __construct(
1 ✔
32
                private readonly ContainerBuilder $builder,
33
        ) {
34
                $this->recursive = new \SplObjectStorage;
1 ✔
35
        }
1 ✔
36

37

38
        public function getContainerBuilder(): ContainerBuilder
39
        {
40
                return $this->builder;
1 ✔
41
        }
42

43

44
        /**
45
         * Resolves the service type for the given definition.
46
         */
47
        public function resolveDefinition(Definition $def): void
48
        {
49
                if (isset($this->recursive[$def])) {
1 ✔
50
                        $names = array_map(fn($item) => $item->getName(), iterator_to_array($this->recursive));
1 ✔
51
                        throw new ServiceCreationException(sprintf('Circular reference detected for services: %s.', implode(', ', $names)));
1 ✔
52
                }
53

54
                try {
55
                        $this->recursive[$def] = true;
1 ✔
56

57
                        $def->resolveType($this);
1 ✔
58

59
                        if (!$def->getType()) {
1 ✔
60
                                throw new ServiceCreationException('Type of service is unknown.');
1 ✔
61
                        }
62
                } catch (\Throwable $e) {
1 ✔
63
                        throw $this->completeException($e, $def);
1 ✔
64

65
                } finally {
1 ✔
66
                        unset($this->recursive[$def]);
1 ✔
67
                }
68
        }
1 ✔
69

70

71
        /**
72
         * Returns the class name that the given reference points to, or null if not resolvable.
73
         */
74
        public function resolveReferenceType(Reference $ref): ?string
75
        {
76
                if ($ref->isSelf()) {
1 ✔
77
                        return $this->currentServiceType;
1 ✔
78
                } elseif ($ref->isType()) {
1 ✔
79
                        return ltrim($ref->getValue(), '\\');
1 ✔
80
                }
81

82
                $def = $this->resolveReference($ref);
1 ✔
83
                if (!$def->getType()) {
1 ✔
84
                        $this->resolveDefinition($def);
1 ✔
85
                }
86

87
                return $def->getType();
1 ✔
88
        }
89

90

91
        /**
92
         * Returns the class name produced by the given statement's entity, or null if not resolvable.
93
         */
94
        public function resolveEntityType(Statement $statement): ?string
95
        {
96
                $entity = $this->normalizeEntity($statement);
1 ✔
97

98
                if ($statement->arguments === self::getFirstClassCallable()) {
1 ✔
99
                        return \Closure::class;
1 ✔
100

101
                } elseif (is_array($entity)) {
1 ✔
102
                        if ($entity[0] instanceof Reference || $entity[0] instanceof Statement) {
1 ✔
103
                                $entity[0] = $this->resolveEntityType($entity[0] instanceof Statement ? $entity[0] : new Statement($entity[0]));
1 ✔
104
                                if (!$entity[0]) {
1 ✔
105
                                        return null;
1 ✔
106
                                }
107
                        }
108

109
                        try {
110
                                $reflection = Callback::toReflection($entity[0] === '' ? $entity[1] : $entity);
1 ✔
111
                                $refClass = $reflection instanceof \ReflectionMethod
1 ✔
112
                                        ? $reflection->getDeclaringClass()
1 ✔
113
                                        : null;
1 ✔
114
                        } catch (\ReflectionException $e) {
1 ✔
115
                                $refClass = $reflection = null;
1 ✔
116
                        }
117

118
                        if (isset($e)) {
1 ✔
119
                                throw new ServiceCreationException(sprintf('Method %s() is not callable.', Callback::toString($entity)), 0, $e);
1 ✔
120
                        } elseif ($reflection instanceof \ReflectionMethod && $refClass && (!$reflection->isPublic()
1 ✔
121
                                || ($refClass->isTrait() && !$reflection->isStatic())
1 ✔
122
                        )
123
                        ) {
124
                                throw new ServiceCreationException(sprintf('Method %s() is not callable.', Callback::toString($entity)));
1 ✔
125
                        }
126

127
                        $this->addDependency($reflection);
1 ✔
128

129
                        $type = Nette\Utils\Type::fromReflection($reflection) ?? ($annotation = Helpers::getReturnTypeAnnotation($reflection));
1 ✔
130
                        if ($type && !in_array($type->getSingleName(), ['object', 'mixed'], true)) {
1 ✔
131
                                if (isset($annotation)) {
1 ✔
132
                                        trigger_error(
1 ✔
133
                                                'Annotation @return should be replaced with native return type at ' . Callback::toString($entity),
1 ✔
134
                                                E_USER_DEPRECATED,
1 ✔
135
                                        );
136
                                }
137

138
                                return Helpers::ensureClassType(
1 ✔
139
                                        $type,
1 ✔
140
                                        sprintf('return type of %s()', Callback::toString($entity)),
1 ✔
141
                                        allowNullable: true,
1 ✔
142
                                );
143
                        }
144

145
                        return null;
1 ✔
146

147
                } elseif ($entity instanceof Reference) { // alias or factory
1 ✔
148
                        return $this->resolveReferenceType($entity);
1 ✔
149

150
                } elseif (is_string($entity)) { // class
1 ✔
151
                        if (!class_exists($entity)) {
1 ✔
152
                                throw new ServiceCreationException(sprintf(
1 ✔
153
                                        interface_exists($entity)
1 ✔
154
                                                ? "Interface %s can not be used as 'create' or 'factory', did you mean 'implement'?"
1 ✔
155
                                                : "Class '%s' not found.",
1 ✔
156
                                        $entity,
1 ✔
157
                                ));
158
                        }
159

160
                        return $entity;
1 ✔
161
                }
162

163
                return null;
×
164
        }
165

166

167
        /**
168
         * Completes the service definition by resolving and autowiring all its arguments.
169
         */
170
        public function completeDefinition(Definition $def): void
171
        {
172
                $this->currentService = $def;
1 ✔
173
                $this->currentServiceType = $def->getType();
1 ✔
174
                $this->currentServiceAllowed = false;
1 ✔
175

176
                try {
177
                        $def->complete($this);
1 ✔
178

179
                        if ($type = $def->getType()) {
1 ✔
180
                                $this->addDependency(new \ReflectionClass($type));
1 ✔
181
                        }
182

183
                } catch (\Throwable $e) {
1 ✔
184
                        throw $this->completeException($e, $def);
1 ✔
185

186
                } finally {
1 ✔
187
                        $this->currentService = $this->currentServiceType = null;
1 ✔
188
                }
189
        }
1 ✔
190

191

192
        /**
193
         * Resolves and autowires a statement's entity and arguments into a completed Statement.
194
         */
195
        public function completeStatement(Statement $statement, bool $currentServiceAllowed = false): Statement
196
        {
197
                $this->currentServiceAllowed = $currentServiceAllowed;
1 ✔
198
                $entity = $this->normalizeEntity($statement);
1 ✔
199
                $arguments = $this->convertReferences($statement->arguments);
1 ✔
200
                $getter = fn(string $type, bool $single) => $single
1 ✔
201
                        ? $this->getByType($type)
1 ✔
202
                        : array_values(array_filter($this->builder->findAutowired($type), fn($obj) => $obj !== $this->currentService));
1 ✔
203
                $method = null;
1 ✔
204

205
                switch (true) {
206
                        case $statement->arguments === self::getFirstClassCallable():
1 ✔
207
                                if (!is_array($entity) || !PhpHelpers::isIdentifier($entity[1])) {
1 ✔
208
                                        throw new ServiceCreationException(sprintf('Cannot create closure for %s(...)', $entity));
1 ✔
209
                                }
210
                                if ($entity[0] instanceof Statement) {
1 ✔
211
                                        $entity[0] = $this->completeStatement($entity[0], $this->currentServiceAllowed);
×
212
                                }
213
                                break;
1 ✔
214

215
                        case is_string($entity) && str_contains($entity, '?'): // PHP literal
1 ✔
216
                                break;
1 ✔
217

218
                        case $entity === 'not':
1 ✔
219
                                if (count($arguments) !== 1) {
1 ✔
220
                                        throw new ServiceCreationException(sprintf('Function %s() expects 1 parameter, %s given.', $entity, count($arguments)));
1 ✔
221
                                }
222

223
                                $entity = ['', '!'];
1 ✔
224
                                break;
1 ✔
225

226
                        case $entity === 'bool':
1 ✔
227
                        case $entity === 'int':
1 ✔
228
                        case $entity === 'float':
1 ✔
229
                        case $entity === 'string':
1 ✔
230
                                if (count($arguments) !== 1) {
1 ✔
231
                                        throw new ServiceCreationException(sprintf('Function %s() expects 1 parameter, %s given.', $entity, count($arguments)));
1 ✔
232
                                }
233

234
                                $arguments = [$arguments[0], $entity];
1 ✔
235
                                $entity = [Helpers::class, 'convertType'];
1 ✔
236
                                break;
1 ✔
237

238
                        case is_string($entity): // create class
1 ✔
239
                                if (!class_exists($entity)) {
1 ✔
240
                                        throw new ServiceCreationException(sprintf("Class '%s' not found.", $entity));
1 ✔
241
                                } elseif ((new \ReflectionClass($entity))->isAbstract()) {
1 ✔
242
                                        throw new ServiceCreationException(sprintf('Class %s is abstract.', $entity));
1 ✔
243
                                } elseif (($rm = (new \ReflectionClass($entity))->getConstructor()) !== null && !$rm->isPublic()) {
1 ✔
244
                                        throw new ServiceCreationException(sprintf(
1 ✔
245
                                                'Class %s has %s constructor.',
246
                                                $entity,
1 ✔
247
                                                $rm->isProtected() ? 'protected' : 'private',
1 ✔
248
                                        ));
249
                                } elseif ($constructor = (new \ReflectionClass($entity))->getConstructor()) {
1 ✔
250
                                        $arguments = self::autowireArguments($method = $constructor, $arguments, $getter);
1 ✔
251
                                        $this->addDependency($constructor);
1 ✔
252
                                } elseif ($arguments) {
1 ✔
253
                                        throw new ServiceCreationException(sprintf(
1 ✔
254
                                                'Unable to pass arguments, class %s has no constructor.',
255
                                                $entity,
1 ✔
256
                                        ));
257
                                }
258

259
                                break;
1 ✔
260

261
                        case $entity instanceof Reference:
1 ✔
262
                                if ($arguments) {
1 ✔
263
                                        $e = $this->completeException(
×
264
                                                new ServiceCreationException(sprintf(
×
265
                                                        'Parameters were passed to reference @%s, although references cannot have any parameters.',
266
                                                        $entity->getValue(),
×
267
                                                )),
268
                                                $this->currentService,
×
269
                                        );
270
                                        trigger_error($e->getMessage(), E_USER_DEPRECATED);
×
271
                                }
272
                                $entity = [new Reference(ContainerBuilder::ThisContainer), Container::getMethodName($entity->getValue())];
1 ✔
273
                                break;
1 ✔
274

275
                        case is_array($entity):
1 ✔
276
                                if (!preg_match('#^\$?(\\\?' . PhpHelpers::ReIdentifier . ')+(\[\])?$#D', $entity[1])) {
1 ✔
277
                                        throw new ServiceCreationException(sprintf(
1 ✔
278
                                                "Expected function, method or property name, '%s' given.",
279
                                                $entity[1],
1 ✔
280
                                        ));
281
                                }
282

283
                                switch (true) {
284
                                        case $entity[0] === '': // function call
1 ✔
285
                                                if (!function_exists($entity[1])) {
1 ✔
286
                                                        throw new ServiceCreationException(sprintf("Function %s doesn't exist.", $entity[1]));
×
287
                                                }
288

289
                                                $rf = new \ReflectionFunction($entity[1]);
1 ✔
290
                                                $arguments = self::autowireArguments($method = $rf, $arguments, $getter);
1 ✔
291
                                                $this->addDependency($rf);
1 ✔
292
                                                break;
1 ✔
293

294
                                        case $entity[0] instanceof Statement:
1 ✔
295
                                                $entity[0] = $this->completeStatement($entity[0], $this->currentServiceAllowed);
1 ✔
296
                                                // break omitted
297

298
                                        case is_string($entity[0]): // static method call
1 ✔
299
                                        case $entity[0] instanceof Reference:
1 ✔
300
                                                if ($entity[1][0] === '$') { // property getter, setter or appender
1 ✔
301
                                                        Validators::assert($arguments, 'list:0..1', "setup arguments for '" . Callback::toString($entity) . "'");
1 ✔
302
                                                        if (!$arguments && str_ends_with($entity[1], '[]')) {
1 ✔
303
                                                                throw new ServiceCreationException(sprintf('Missing argument for %s.', $entity[1]));
1 ✔
304
                                                        }
305
                                                } elseif (
306
                                                        $type = $entity[0] instanceof Reference
1 ✔
307
                                                                ? $this->resolveReferenceType($entity[0])
1 ✔
308
                                                                : $this->resolveEntityType($entity[0] instanceof Statement ? $entity[0] : new Statement($entity[0]))
1 ✔
309
                                                ) {
310
                                                        $rc = new \ReflectionClass($type);
1 ✔
311
                                                        if ($rc->hasMethod($entity[1])) {
1 ✔
312
                                                                $rm = $rc->getMethod($entity[1]);
1 ✔
313
                                                                if (!$rm->isPublic()) {
1 ✔
314
                                                                        throw new ServiceCreationException(sprintf('%s::%s() is not callable.', $type, $entity[1]));
×
315
                                                                }
316

317
                                                                $arguments = self::autowireArguments($method = $rm, $arguments, $getter);
1 ✔
318
                                                                $this->addDependency($rm);
1 ✔
319
                                                        }
320
                                                }
321
                                }
322
                }
323

324
                try {
325
                        $arguments = $this->completeArguments($arguments);
1 ✔
326
                } catch (ServiceCreationException $e) {
1 ✔
327
                        if (!str_contains($e->getMessage(), ' (used in')) {
1 ✔
328
                                $e->setMessage($e->getMessage() . " (used in {$this->entityToString($entity)})");
1 ✔
329
                        }
330

331
                        throw $e;
1 ✔
332
                }
333

334
                if ($method) {
1 ✔
335
                        $arguments = $this->hideSensitiveArguments($method, $arguments);
1 ✔
336
                }
337

338
                return new Statement($entity, $arguments);
1 ✔
339
        }
340

341

342
        /**
343
         * @param  array<mixed>  $arguments
344
         * @return array<mixed>
345
         */
346
        public function completeArguments(array $arguments): array
347
        {
348
                array_walk_recursive($arguments, function (&$val): void {
1 ✔
349
                        if ($val instanceof Statement) {
1 ✔
350
                                $entity = $val->getEntity();
1 ✔
351
                                if ($entity === 'typed' || $entity === 'tagged') {
1 ✔
352
                                        $services = [];
1 ✔
353
                                        $current = $this->currentService?->getName();
1 ✔
354
                                        foreach ($val->arguments as $argument) {
1 ✔
355
                                                foreach ($entity === 'tagged'
1 ✔
356
                                                        ? $this->builder->findByTag($argument)
1 ✔
357
                                                        : $this->builder->findAutowired($argument) as $name => $foo) {
1 ✔
358
                                                        if ($name !== $current) {
1 ✔
359
                                                                $services[] = new Reference($name);
1 ✔
360
                                                        }
361
                                                }
362
                                        }
363

364
                                        $val = $this->completeArguments($services);
1 ✔
365

366
                                } else {
367
                                        $val = $this->completeStatement($val, $this->currentServiceAllowed);
1 ✔
368
                                }
369
                        } elseif ($val instanceof Definition || $val instanceof Reference) {
1 ✔
370
                                $val = $this->normalizeEntity(new Statement($val));
1 ✔
371
                        }
372
                });
1 ✔
373
                return $arguments;
1 ✔
374
        }
375

376

377
        /**
378
         * Wraps the arguments of #[SensitiveParameter] parameters in sensitive markers, which Tracy hides.
379
         * @param  array<mixed>  $arguments
380
         * @return array<mixed>
381
         */
382
        private function hideSensitiveArguments(\ReflectionFunctionAbstract $method, array $arguments): array
383
        {
384
                foreach ($method->getParameters() as $param) {
1 ✔
385
                        $key = array_key_exists($param->name, $arguments) ? $param->name : $param->getPosition();
1 ✔
386
                        if (!$param->isVariadic() && array_key_exists($key, $arguments) && $param->getAttributes(\SensitiveParameter::class)) {
1 ✔
387
                                $code = (new PhpGenerator($this->builder))->formatPhp('/*sensitive{*/?/*}*/', [$arguments[$key]]);
1 ✔
388
                                $arguments[$key] = ContainerBuilder::literal($code);
1 ✔
389
                        }
390
                }
391

392
                return $arguments;
1 ✔
393
        }
394

395

396
        /**
397
         * Returns literal, Class, Reference, [Class, member], [, globalFunc], [Reference, member], [Statement, member]
398
         * @return string|array{string|Reference|Statement, string}|Reference|null
399
         */
400
        private function normalizeEntity(Statement $statement): string|array|Reference|null
401
        {
402
                $entity = $statement->getEntity();
1 ✔
403
                if (is_array($entity)) {
1 ✔
404
                        $item = &$entity[0];
1 ✔
405
                } else {
406
                        $item = &$entity;
1 ✔
407
                }
408

409
                if ($item instanceof Definition) {
1 ✔
410
                        if ($this->builder->getDefinition($item->getName()) !== $item) {
1 ✔
411
                                throw new ServiceCreationException(sprintf("Service '%s' does not match the expected service.", $item->getName()));
1 ✔
412
                        }
413
                        $item = new Reference($item->getName());
1 ✔
414
                }
415

416
                if ($item instanceof Reference) {
1 ✔
417
                        $item = $this->normalizeReference($item);
1 ✔
418
                }
419

420
                return $entity;
1 ✔
421
        }
422

423

424
        /**
425
         * Normalizes reference to 'self' or named reference (leaves it typed if not possible during resolving) and checks the service exists.
426
         */
427
        public function normalizeReference(Reference $ref): Reference
428
        {
429
                $service = $ref->getValue();
1 ✔
430
                if ($ref->isSelf()) {
1 ✔
431
                        return $ref;
1 ✔
432
                } elseif ($ref->isName()) {
1 ✔
433
                        if (!$this->builder->hasDefinition($service)) {
1 ✔
434
                                throw new ServiceCreationException(sprintf("Reference to missing service '%s'.", $service));
1 ✔
435
                        }
436

437
                        return $this->currentService && $service === $this->currentService->getName()
1 ✔
438
                                ? new Reference(Reference::Self)
1 ✔
439
                                : $ref;
1 ✔
440
                }
441

442
                try {
443
                        return $this->getByType($service);
1 ✔
444
                } catch (NotAllowedDuringResolvingException) {
1 ✔
445
                        return new Reference($service);
1 ✔
446
                }
447
        }
448

449

450
        /**
451
         * Returns the definition that the reference points to.
452
         */
453
        public function resolveReference(Reference $ref): Definition
454
        {
455
                if ($ref->isSelf()) {
1 ✔
456
                        assert($this->currentService !== null);
457
                        return $this->currentService;
×
458
                }
459
                return $this->builder->getDefinition($ref->getValue());
1 ✔
460
        }
461

462

463
        /**
464
         * Returns named reference to service resolved by type (or 'self' reference for local-autowiring).
465
         * @param class-string  $type
466
         * @throws ServiceCreationException when multiple found
467
         * @throws MissingServiceException when not found
468
         * @throws NotAllowedDuringResolvingException
469
         */
470
        public function getByType(string $type): Reference
471
        {
472
                if (
473
                        $this->currentService
1 ✔
474
                        && $this->currentServiceAllowed
1 ✔
475
                        && $this->currentServiceType !== null
1 ✔
476
                        && is_a($this->currentServiceType, $type, allow_string: true)
1 ✔
477
                ) {
478
                        return new Reference(Reference::Self);
1 ✔
479
                }
480

481
                $name = $this->builder->getByType($type, throw: true);
1 ✔
482
                if (
483
                        !$this->currentServiceAllowed
1 ✔
484
                        && $this->currentService === $this->builder->getDefinition($name)
1 ✔
485
                ) {
486
                        throw new MissingServiceException;
1 ✔
487
                }
488

489
                return new Reference($name);
1 ✔
490
        }
491

492

493
        /**
494
         * Adds item to the list of dependencies.
495
         * @param  \ReflectionClass<object>|\ReflectionFunctionAbstract|string  $dep
496
         */
497
        public function addDependency(\ReflectionClass|\ReflectionFunctionAbstract|string $dep): static
498
        {
499
                $this->builder->addDependency($dep);
1 ✔
500
                return $this;
1 ✔
501
        }
502

503

504
        private function completeException(\Throwable $e, ?Definition $def): ServiceCreationException
505
        {
506
                if ($e instanceof ServiceCreationException && str_starts_with($e->getMessage(), "Service '")) {
1 ✔
507
                        return $e;
1 ✔
508
                }
509

510
                if (!$def) {
1 ✔
511
                        return $e instanceof ServiceCreationException
×
512
                                ? $e
×
513
                                : new ServiceCreationException($e->getMessage(), 0, $e);
×
514
                }
515

516
                $name = $def->getName();
1 ✔
517
                $type = $def->getType();
1 ✔
518
                if ($name && !ctype_digit($name)) {
1 ✔
519
                        $message = "Service '$name'" . ($type ? " (type of $type)" : '') . ': ';
1 ✔
520
                } elseif ($type) {
1 ✔
521
                        $message = "Service of type $type: ";
1 ✔
522
                } elseif ($def instanceof Definitions\ServiceDefinition && $def->getEntity()) {
1 ✔
523
                        $message = 'Service (' . $this->entityToString($def->getEntity()) . '): ';
1 ✔
524
                } else {
525
                        $message = '';
1 ✔
526
                }
527

528
                $message .= $type
1 ✔
529
                        ? str_replace("$type::", preg_replace('~.*\\\~', '', $type) . '::', $e->getMessage())
1 ✔
530
                        : $e->getMessage();
1 ✔
531

532
                return $e instanceof ServiceCreationException
1 ✔
533
                        ? $e->setMessage($message)
1 ✔
534
                        : new ServiceCreationException($message, 0, $e);
1 ✔
535
        }
536

537

538
        /** @param  mixed  $entity */
539
        private function entityToString($entity): string
540
        {
541
                $referenceToText = fn(Reference $ref): string => $ref->isSelf() && $this->currentService?->getName() !== null
1 ✔
542
                        ? '@' . $this->currentService->getName()
1 ✔
543
                        : '@' . $ref->getValue();
1 ✔
544
                if (is_string($entity)) {
1 ✔
545
                        return $entity . '::__construct()';
1 ✔
546
                } elseif ($entity instanceof Reference) {
1 ✔
547
                        $entity = $referenceToText($entity);
×
548
                } elseif (is_array($entity)) {
1 ✔
549
                        if (!str_contains($entity[1], '$')) {
1 ✔
550
                                $entity[1] .= '()';
1 ✔
551
                        }
552

553
                        if ($entity[0] instanceof Reference) {
1 ✔
554
                                $entity[0] = $referenceToText($entity[0]);
1 ✔
555
                        } elseif (!is_string($entity[0])) {
1 ✔
556
                                return $entity[1];
1 ✔
557
                        }
558

559
                        return implode('::', $entity);
1 ✔
560
                }
561

562
                return (string) $entity;
×
563
        }
564

565

566
        /**
567
         * @param  array<mixed>  $arguments
568
         * @return array<mixed>
569
         */
570
        private function convertReferences(array $arguments): array
571
        {
572
                array_walk_recursive($arguments, function (&$val): void {
1 ✔
573
                        if (is_string($val) && strlen($val) > 1 && $val[0] === '@' && $val[1] !== '@') {
1 ✔
574
                                $pair = explode('::', substr($val, 1), 2);
1 ✔
575
                                if (!isset($pair[1])) { // @service
1 ✔
576
                                        $val = new Reference($pair[0]);
1 ✔
577
                                } elseif (preg_match('#^[A-Z][a-zA-Z0-9_]*$#D', $pair[1])) { // @service::CONSTANT
1 ✔
578
                                        $val = ContainerBuilder::literal($this->resolveReferenceType(new Reference($pair[0])) . '::' . $pair[1]);
1 ✔
579
                                } else { // @service::property
580
                                        $val = new Statement([new Reference($pair[0]), '$' . $pair[1]]);
1 ✔
581
                                }
582
                        } elseif (is_string($val) && str_starts_with($val, '@@')) { // escaped text @@
1 ✔
583
                                $val = substr($val, 1);
1 ✔
584
                        }
585
                });
1 ✔
586
                return $arguments;
1 ✔
587
        }
588

589

590
        /**
591
         * Add missing arguments using autowiring.
592
         * @param  array<mixed>  $arguments
593
         * @param  (callable(string, bool): (object|object[]|null))  $getter
594
         * @return array<mixed>
595
         * @throws ServiceCreationException
596
         */
597
        public static function autowireArguments(
598
                \ReflectionFunctionAbstract $method,
599
                array $arguments,
600
                callable $getter,
601
        ): array
602
        {
603
                $useName = false;
1 ✔
604
                $num = -1;
1 ✔
605
                $res = [];
1 ✔
606

607
                foreach ($method->getParameters() as $num => $param) {
1 ✔
608
                        $paramName = $param->name;
1 ✔
609

610
                        if ($param->isVariadic()) {
1 ✔
611
                                if ($useName && Arrays::some($arguments, fn($val, $key) => is_int($key))) {
1 ✔
612
                                        throw new ServiceCreationException(sprintf(
1 ✔
613
                                                'Cannot use positional argument after named or omitted argument in %s.',
614
                                                Reflection::toString($param),
1 ✔
615
                                        ));
616

617
                                } elseif (array_key_exists($paramName, $arguments)) {
1 ✔
618
                                        if (!is_array($arguments[$paramName])) {
1 ✔
619
                                                throw new ServiceCreationException(sprintf(
1 ✔
620
                                                        'Parameter %s must be array, %s given.',
621
                                                        Reflection::toString($param),
1 ✔
622
                                                        gettype($arguments[$paramName]),
1 ✔
623
                                                ));
624
                                        }
625

626
                                        $res = [...$res, ...$arguments[$paramName]];
1 ✔
627
                                        unset($arguments[$paramName]);
1 ✔
628

629
                                } else {
630
                                        $res = [...$res, ...$arguments];
1 ✔
631
                                        $arguments = [];
1 ✔
632
                                }
633

634
                        } elseif (array_key_exists($key = $paramName, $arguments) || array_key_exists($key = $num, $arguments)) {
1 ✔
635
                                $res[$useName ? $paramName : $num] = $arguments[$key];
1 ✔
636
                                unset($arguments[$key], $arguments[$num]); // unset $num to enable overwriting in configuration
1 ✔
637

638
                        } elseif (($aw = self::autowireArgument($param, $getter)) !== null) {
1 ✔
639
                                $res[$useName ? $paramName : $num] = $aw;
1 ✔
640

641
                        } else {
642
                                $useName = true; // is optional
1 ✔
643
                        }
644
                }
645

646
                // extra parameters
647
                while (!$useName && array_key_exists(++$num, $arguments)) {
1 ✔
648
                        $res[$num] = $arguments[$num];
1 ✔
649
                        unset($arguments[$num]);
1 ✔
650
                }
651

652
                if ($arguments) {
1 ✔
653
                        throw new ServiceCreationException(sprintf(
1 ✔
654
                                'Unable to pass specified arguments to %s.',
655
                                Reflection::toString($method),
1 ✔
656
                        ));
657
                }
658

659
                return $res;
1 ✔
660
        }
661

662

663
        /**
664
         * Resolves missing argument using autowiring.
665
         * @param  (callable(string, bool): (object|object[]|null))  $getter
666
         * @throws ServiceCreationException
667
         */
668
        private static function autowireArgument(\ReflectionParameter $parameter, callable $getter): mixed
669
        {
670
                $desc = Reflection::toString($parameter);
1 ✔
671
                $type = Nette\Utils\Type::fromReflection($parameter);
1 ✔
672

673
                if ($type?->isClass()) {
1 ✔
674
                        $class = $type->getSingleName();
1 ✔
675
                        try {
676
                                $res = $getter($class, true);
1 ✔
677
                        } catch (MissingServiceException) {
1 ✔
678
                                $res = null;
1 ✔
679
                        } catch (ServiceCreationException $e) {
1 ✔
680
                                throw new ServiceCreationException("{$e->getMessage()} (required by $desc)", 0, $e);
1 ✔
681
                        }
682

683
                        if ($res !== null || $parameter->isOptional()) {
1 ✔
684
                                return $res;
1 ✔
685
                        } elseif (class_exists($class) || interface_exists($class)) {
1 ✔
686
                                throw new ServiceCreationException(sprintf(
1 ✔
687
                                        'Service of type %s required by %s not found. Did you add it to configuration file?',
688
                                        $class,
1 ✔
689
                                        $desc,
1 ✔
690
                                ));
691
                        } else {
692
                                throw new ServiceCreationException(sprintf(
1 ✔
693
                                        "Class '%s' required by %s not found. Check the parameter type and 'use' statements.",
694
                                        $class,
1 ✔
695
                                        $desc,
1 ✔
696
                                ));
697
                        }
698

699
                } elseif ($itemType = self::isArrayOf($parameter, $type)) {
1 ✔
700
                        return $getter($itemType, false);
1 ✔
701

702
                } elseif ($parameter->isOptional()) {
1 ✔
703
                        return null;
1 ✔
704

705
                } else {
706
                        throw new ServiceCreationException(sprintf(
1 ✔
707
                                'Parameter %s has %s, so its value must be specified.',
708
                                $desc,
1 ✔
709
                                $type && !$type->isSimple() ? 'complex type and no default value' : 'no class type or default value',
1 ✔
710
                        ));
711
                }
712
        }
713

714

715
        private static function isArrayOf(\ReflectionParameter $parameter, ?Nette\Utils\Type $type): ?string
716
        {
717
                $method = $parameter->getDeclaringFunction();
1 ✔
718
                return $method instanceof \ReflectionMethod
1 ✔
719
                        && $type?->getSingleName() === 'array'
1 ✔
720
                        && preg_match(
1 ✔
721
                                '#@param[ \t]+(?|([\w\\\]+)\[\]|list<([\w\\\]+)>|array<int,\s*([\w\\\]+)>)[ \t]+\$' . $parameter->name . '#',
1 ✔
722
                                (string) $method->getDocComment(),
1 ✔
723
                                $m,
724
                        )
725
                        && ($itemType = Reflection::expandClassName($m[1], $method->getDeclaringClass()))
1 ✔
726
                        && (class_exists($itemType) || interface_exists($itemType))
1 ✔
727
                        ? $itemType
1 ✔
728
                        : null;
1 ✔
729
        }
730

731

732
        /**
733
         * Returns the sentinel value used to mark first-class callable syntax (...).
734
         * @return list<mixed>
735
         * @internal
736
         */
737
        public static function getFirstClassCallable(): array
738
        {
739
                static $x = [new Nette\PhpGenerator\Literal('...')];
1 ✔
740
                return $x;
1 ✔
741
        }
742
}
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