• 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

97.33
/src/DI/Extensions/SearchExtension.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\Extensions;
9

10
use Nette;
11
use Nette\DI;
12
use Nette\DI\Attributes\Hook;
13
use Nette\DI\{ContainerBuilder, Phase};
14
use Nette\Loaders\RobotLoader;
15
use Nette\Schema\Expect;
16
use Nette\Utils\Arrays;
17
use function count, in_array, is_string, sprintf;
18

19

20
/**
21
 * Services auto-discovery.
22
 */
23
final class SearchExtension extends Nette\DI\CompilerExtension
24
{
25
        /** @var array<string, object{in: string, files: list<string>, classes: list<string>, extends: list<string>, implements: list<string>, exclude: object{files: list<string>, classes: list<string>, extends: list<string>, implements: list<string>}, tags: array<string, mixed>}> */
26
        protected $config = [];
27

28
        /** @var array<string, array<string, mixed>> */
29
        private array $classes = [];
30

31

32
        public function __construct(
1 ✔
33
                private readonly string $tempDir,
34
        ) {
35
        }
1 ✔
36

37

38
        public function getConfigSchema(): Nette\Schema\Schema
39
        {
40
                return Expect::arrayOf(
1 ✔
41
                        Expect::structure([
1 ✔
42
                                'in' => Expect::string()->required(),
1 ✔
43
                                'files' => Expect::anyOf(Expect::listOf('string'), Expect::string()->castTo('array'))->default([]),
1 ✔
44
                                'classes' => Expect::anyOf(Expect::listOf('string'), Expect::string()->castTo('array'))->default([]),
1 ✔
45
                                'extends' => Expect::anyOf(Expect::listOf('string'), Expect::string()->castTo('array'))->default([]),
1 ✔
46
                                'implements' => Expect::anyOf(Expect::listOf('string'), Expect::string()->castTo('array'))->default([]),
1 ✔
47
                                'exclude' => Expect::structure([
1 ✔
48
                                        'files' => Expect::anyOf(Expect::listOf('string'), Expect::string()->castTo('array'))->default([]),
1 ✔
49
                                        'classes' => Expect::anyOf(Expect::listOf('string'), Expect::string()->castTo('array'))->default([]),
1 ✔
50
                                        'extends' => Expect::anyOf(Expect::listOf('string'), Expect::string()->castTo('array'))->default([]),
1 ✔
51
                                        'implements' => Expect::anyOf(Expect::listOf('string'), Expect::string()->castTo('array'))->default([]),
1 ✔
52
                                ]),
53
                                'tags' => Expect::array(),
1 ✔
54
                        ]),
55
                )->before(fn($val) => is_string($val['in'] ?? null)
1 ✔
56
                        ? ['default' => $val]
1 ✔
57
                        : $val);
1 ✔
58
        }
59

60

61
        #[Hook(Phase::Register)]
62
        public function doScanDirectories(ContainerBuilder $builder): void
63
        {
64
                foreach (array_filter($this->config) as $name => $batch) {
1 ✔
65
                        if (!is_dir($batch->in)) {
1 ✔
66
                                throw new Nette\DI\InvalidConfigurationException(sprintf(
1 ✔
67
                                        "Option '%s\u{a0}›\u{a0}%s\u{a0}›\u{a0}in' must be valid directory name, '%s' given.",
68
                                        $this->name,
1 ✔
69
                                        $name,
1 ✔
70
                                        $batch->in,
1 ✔
71
                                ));
72
                        }
73

74
                        foreach ($this->findClasses($batch) as $class) {
1 ✔
75
                                $this->classes[$class] = [...$this->classes[$class] ?? [], ...$batch->tags];
1 ✔
76
                        }
77
                }
78
        }
1 ✔
79

80

81
        #[Hook(Phase::Discover)]
82
        public function doDiscoverServices(ContainerBuilder $builder): void
83
        {
84
                foreach ($this->classes as $class => $foo) {
1 ✔
85
                        if ($builder->has(type: $class)) {
1 ✔
86
                                unset($this->classes[$class]);
1 ✔
87
                        }
88
                }
89

90
                foreach ($this->classes as $class => $tags) {
1 ✔
91
                        $def = class_exists($class)
1 ✔
92
                                ? $builder->add(null, $class)
1 ✔
93
                                : $builder->add(null, method_exists($class, 'create') ? di\factory($class) : di\accessor($class));
1 ✔
94
                        $def->setTags(Arrays::normalize($tags, filling: true));
1 ✔
95
                }
96
        }
1 ✔
97

98

99
        /**
100
         * Finds classes matching the given search configuration batch.
101
         * @return string[]
102
         */
103
        public function findClasses(\stdClass $config): array
104
        {
105
                $exclude = $config->exclude;
1 ✔
106
                $robot = new RobotLoader;
1 ✔
107
                $robot->setTempDirectory($this->tempDir);
1 ✔
108
                $robot->addDirectory($config->in);
1 ✔
109
                $robot->acceptFiles = $config->files ?: ['*.php'];
1 ✔
110
                $robot->ignoreDirs = array_values([...$robot->ignoreDirs, ...$exclude->files]);
1 ✔
111
                $robot->reportParseErrors(false);
1 ✔
112
                $robot->refresh();
1 ✔
113
                $classes = array_unique(array_keys($robot->getIndexedClasses()));
1 ✔
114

115
                $acceptRE = self::buildNameRegexp($config->classes);
1 ✔
116
                $rejectRE = self::buildNameRegexp($exclude->classes);
1 ✔
117
                $acceptParent = [...$config->extends, ...$config->implements];
1 ✔
118
                $rejectParent = [...$exclude->extends, ...$exclude->implements];
1 ✔
119

120
                $found = [];
1 ✔
121
                foreach ($classes as $class) {
1 ✔
122
                        if (!class_exists($class) && !interface_exists($class) && !trait_exists($class)) {
1 ✔
UNCOV
123
                                throw new Nette\InvalidStateException(sprintf(
×
124
                                        'Class %s was found, but it cannot be loaded by autoloading.',
125
                                        $class,
×
126
                                ));
127
                        }
128

129
                        $rc = new \ReflectionClass($class);
1 ✔
130
                        if (
131
                                ($rc->isInstantiable()
1 ✔
132
                                        || ($rc->isInterface()
1 ✔
133
                                                && count($methods = $rc->getMethods()) === 1
1 ✔
134
                                                && in_array($methods[0]->name, ['get', 'create'], true))
1 ✔
135
                                )
136
                                && (!$acceptRE || preg_match($acceptRE, $rc->name))
1 ✔
137
                                && (!$rejectRE || !preg_match($rejectRE, $rc->name))
1 ✔
138
                                && (!$acceptParent || Arrays::some($acceptParent, fn($nm) => $rc->isSubclassOf($nm)))
1 ✔
139
                                && (!$rejectParent || Arrays::every($rejectParent, fn($nm) => !$rc->isSubclassOf($nm)))
1 ✔
140
                        ) {
141
                                $found[] = $rc->name;
1 ✔
142
                        }
143
                }
144

145
                return $found;
1 ✔
146
        }
147

148

149
        /** @param  string[]  $masks */
150
        private static function buildNameRegexp(array $masks): ?string
151
        {
152
                $res = [];
1 ✔
153
                foreach ($masks as $mask) {
1 ✔
154
                        $mask = (str_contains($mask, '\\') ? '' : '**\\') . $mask;
1 ✔
155
                        $mask = preg_quote($mask, '#');
1 ✔
156
                        $mask = str_replace('\*\*\\\\', '(.*\\\)?', $mask);
1 ✔
157
                        $mask = str_replace('\\\\\*\*', '(\\\.*)?', $mask);
1 ✔
158
                        $mask = str_replace('\*', '\w*', $mask);
1 ✔
159
                        $res[] = $mask;
1 ✔
160
                }
161

162
                return $res ? '#^(' . implode('|', $res) . ')$#i' : null;
1 ✔
163
        }
164
}
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