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

nette / utils / 20431395313

22 Dec 2025 12:06PM UTC coverage: 93.164% (+71.8%) from 21.324%
20431395313

push

github

dg
Html::addText() accepts int|null for back compatibility [Closes #332][Closes #333]

1 of 1 new or added line in 1 file covered. (100.0%)

140 existing lines in 15 files now uncovered.

2058 of 2209 relevant lines covered (93.16%)

0.93 hits per line

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

94.74
/src/Utils/Finder.php
1
<?php
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
declare(strict_types=1);
9

10
namespace Nette\Utils;
11

12
use Nette;
13
use function array_merge, count, func_get_args, func_num_args, glob, implode, is_array, is_dir, iterator_to_array, preg_match, preg_quote, preg_replace, preg_split, rtrim, spl_object_id, sprintf, str_ends_with, str_starts_with, strnatcmp, strpbrk, strrpos, strtolower, strtr, substr, usort;
14
use const GLOB_NOESCAPE, GLOB_NOSORT, GLOB_ONLYDIR;
15

16

17
/**
18
 * Finder allows searching through directory trees using iterator.
19
 *
20
 * Finder::findFiles('*.php')
21
 *     ->size('> 10kB')
22
 *     ->from('.')
23
 *     ->exclude('temp');
24
 *
25
 * @implements \IteratorAggregate<string, FileInfo>
26
 */
27
class Finder implements \IteratorAggregate
28
{
29
        /** @var array<array{string, string}> */
30
        private array $find = [];
31

32
        /** @var string[] */
33
        private array $in = [];
34

35
        /** @var \Closure[] */
36
        private array $filters = [];
37

38
        /** @var \Closure[] */
39
        private array $descentFilters = [];
40

41
        /** @var array<string|self> */
42
        private array $appends = [];
43
        private bool $childFirst = false;
44

45
        /** @var ?callable */
46
        private $sort;
47
        private int $maxDepth = -1;
48
        private bool $ignoreUnreadableDirs = true;
49

50

51
        /**
52
         * Begins search for files and directories matching mask.
53
         */
54
        public static function find(string|array $masks = ['*']): static
1✔
55
        {
56
                $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic
1✔
57
                return (new static)->addMask($masks, 'dir')->addMask($masks, 'file');
1✔
58
        }
59

60

61
        /**
62
         * Begins search for files matching mask.
63
         */
64
        public static function findFiles(string|array $masks = ['*']): static
1✔
65
        {
66
                $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic
1✔
67
                return (new static)->addMask($masks, 'file');
1✔
68
        }
69

70

71
        /**
72
         * Begins search for directories matching mask.
73
         */
74
        public static function findDirectories(string|array $masks = ['*']): static
1✔
75
        {
76
                $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic
1✔
77
                return (new static)->addMask($masks, 'dir');
1✔
78
        }
79

80

81
        /**
82
         * Finds files matching the specified masks.
83
         */
84
        public function files(string|array $masks = ['*']): static
1✔
85
        {
86
                return $this->addMask((array) $masks, 'file');
1✔
87
        }
88

89

90
        /**
91
         * Finds directories matching the specified masks.
92
         */
93
        public function directories(string|array $masks = ['*']): static
1✔
94
        {
95
                return $this->addMask((array) $masks, 'dir');
1✔
96
        }
97

98

99
        private function addMask(array $masks, string $mode): static
1✔
100
        {
101
                foreach ($masks as $mask) {
1✔
102
                        $mask = FileSystem::unixSlashes($mask);
1✔
103
                        if ($mode === 'dir') {
1✔
104
                                $mask = rtrim($mask, '/');
1✔
105
                        }
106
                        if ($mask === '' || ($mode === 'file' && str_ends_with($mask, '/'))) {
1✔
107
                                throw new Nette\InvalidArgumentException("Invalid mask '$mask'");
1✔
108
                        }
109
                        if (str_starts_with($mask, '**/')) {
1✔
110
                                $mask = substr($mask, 3);
1✔
111
                        }
112
                        $this->find[] = [$mask, $mode];
1✔
113
                }
114
                return $this;
1✔
115
        }
116

117

118
        /**
119
         * Searches in the given directories. Wildcards are allowed.
120
         */
121
        public function in(string|array $paths): static
1✔
122
        {
123
                $paths = is_array($paths) ? $paths : func_get_args(); // compatibility with variadic
1✔
124
                $this->addLocation($paths, '');
1✔
125
                return $this;
1✔
126
        }
127

128

129
        /**
130
         * Searches recursively from the given directories. Wildcards are allowed.
131
         */
132
        public function from(string|array $paths): static
1✔
133
        {
134
                $paths = is_array($paths) ? $paths : func_get_args(); // compatibility with variadic
1✔
135
                $this->addLocation($paths, '/**');
1✔
136
                return $this;
1✔
137
        }
138

139

140
        private function addLocation(array $paths, string $ext): void
1✔
141
        {
142
                foreach ($paths as $path) {
1✔
143
                        if ($path === '') {
1✔
UNCOV
144
                                throw new Nette\InvalidArgumentException("Invalid directory '$path'");
×
145
                        }
146
                        $path = rtrim(FileSystem::unixSlashes($path), '/');
1✔
147
                        $this->in[] = $path . $ext;
1✔
148
                }
149
        }
1✔
150

151

152
        /**
153
         * Lists directory's contents before the directory itself. By default, this is disabled.
154
         */
155
        public function childFirst(bool $state = true): static
1✔
156
        {
157
                $this->childFirst = $state;
1✔
158
                return $this;
1✔
159
        }
160

161

162
        /**
163
         * Ignores unreadable directories. By default, this is enabled.
164
         */
165
        public function ignoreUnreadableDirs(bool $state = true): static
166
        {
UNCOV
167
                $this->ignoreUnreadableDirs = $state;
×
UNCOV
168
                return $this;
×
169
        }
170

171

172
        /**
173
         * Set a compare function for sorting directory entries. The function will be called to sort entries from the same directory.
174
         * @param  callable(FileInfo, FileInfo): int  $callback
175
         */
176
        public function sortBy(callable $callback): static
1✔
177
        {
178
                $this->sort = $callback;
1✔
179
                return $this;
1✔
180
        }
181

182

183
        /**
184
         * Sorts files in each directory naturally by name.
185
         */
186
        public function sortByName(): static
187
        {
188
                $this->sort = fn(FileInfo $a, FileInfo $b): int => strnatcmp($a->getBasename(), $b->getBasename());
1✔
189
                return $this;
1✔
190
        }
191

192

193
        /**
194
         * Adds the specified paths or appends a new finder that returns.
195
         */
196
        public function append(string|array|null $paths = null): static
1✔
197
        {
198
                if ($paths === null) {
1✔
199
                        return $this->appends[] = new static;
1✔
200
                }
201

202
                $this->appends = array_merge($this->appends, (array) $paths);
1✔
203
                return $this;
1✔
204
        }
205

206

207
        /********************* filtering ****************d*g**/
208

209

210
        /**
211
         * Skips entries that matches the given masks relative to the ones defined with the in() or from() methods.
212
         */
213
        public function exclude(string|array $masks): static
1✔
214
        {
215
                $masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic
1✔
216
                foreach ($masks as $mask) {
1✔
217
                        $mask = FileSystem::unixSlashes($mask);
1✔
218
                        if (!preg_match('~^/?(\*\*/)?(.+)(/\*\*|/\*|/|)$~D', $mask, $m)) {
1✔
UNCOV
219
                                throw new Nette\InvalidArgumentException("Invalid mask '$mask'");
×
220
                        }
221
                        $end = $m[3];
1✔
222
                        $re = $this->buildPattern($m[2]);
1✔
223
                        $filter = fn(FileInfo $file): bool => ($end && !$file->isDir())
1✔
224
                                || !preg_match($re, FileSystem::unixSlashes($file->getRelativePathname()));
1✔
225

226
                        $this->descentFilter($filter);
1✔
227
                        if ($end !== '/*') {
1✔
228
                                $this->filter($filter);
1✔
229
                        }
230
                }
231

232
                return $this;
1✔
233
        }
234

235

236
        /**
237
         * Yields only entries which satisfy the given filter.
238
         * @param  callable(FileInfo): bool  $callback
239
         */
240
        public function filter(callable $callback): static
1✔
241
        {
242
                $this->filters[] = \Closure::fromCallable($callback);
1✔
243
                return $this;
1✔
244
        }
245

246

247
        /**
248
         * It descends only to directories that match the specified filter.
249
         * @param  callable(FileInfo): bool  $callback
250
         */
251
        public function descentFilter(callable $callback): static
1✔
252
        {
253
                $this->descentFilters[] = \Closure::fromCallable($callback);
1✔
254
                return $this;
1✔
255
        }
256

257

258
        /**
259
         * Sets the maximum depth of entries.
260
         */
261
        public function limitDepth(?int $depth): static
1✔
262
        {
263
                $this->maxDepth = $depth ?? -1;
1✔
264
                return $this;
1✔
265
        }
266

267

268
        /**
269
         * Restricts the search by size. $operator accepts "[operator] [size] [unit]" example: >=10kB
270
         */
271
        public function size(string $operator, ?int $size = null): static
1✔
272
        {
273
                if (func_num_args() === 1) { // in $operator is predicate
1✔
274
                        if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?((?:\d*\.)?\d+)\s*(K|M|G|)B?$#Di', $operator, $matches)) {
1✔
UNCOV
275
                                throw new Nette\InvalidArgumentException('Invalid size predicate format.');
×
276
                        }
277

278
                        [, $operator, $size, $unit] = $matches;
1✔
279
                        $units = ['' => 1, 'k' => 1e3, 'm' => 1e6, 'g' => 1e9];
1✔
280
                        $size *= $units[strtolower($unit)];
1✔
281
                        $operator = $operator ?: '=';
1✔
282
                }
283

284
                return $this->filter(fn(FileInfo $file): bool => !$file->isFile() || Helpers::compare($file->getSize(), $operator, $size));
1✔
285
        }
286

287

288
        /**
289
         * Restricts the search by modified time. $operator accepts "[operator] [date]" example: >1978-01-23
290
         */
291
        public function date(string $operator, string|int|\DateTimeInterface|null $date = null): static
1✔
292
        {
293
                if (func_num_args() === 1) { // in $operator is predicate
1✔
294
                        if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?(.+)$#Di', $operator, $matches)) {
1✔
UNCOV
295
                                throw new Nette\InvalidArgumentException('Invalid date predicate format.');
×
296
                        }
297

298
                        [, $operator, $date] = $matches;
1✔
299
                        $operator = $operator ?: '=';
1✔
300
                }
301

302
                $date = DateTime::from($date)->getTimestamp();
1✔
303
                return $this->filter(fn(FileInfo $file): bool => !$file->isFile() || Helpers::compare($file->getMTime(), $operator, $date));
1✔
304
        }
305

306

307
        /********************* iterator generator ****************d*g**/
308

309

310
        /**
311
         * Returns an array with all found files and directories.
312
         * @return list<FileInfo>
313
         */
314
        public function collect(): array
315
        {
316
                return iterator_to_array($this->getIterator(), preserve_keys: false);
1✔
317
        }
318

319

320
        /** @return \Generator<string, FileInfo> */
321
        public function getIterator(): \Generator
1✔
322
        {
323
                $plan = $this->buildPlan();
1✔
324
                foreach ($plan as $dir => $searches) {
1✔
325
                        yield from $this->traverseDir($dir, $searches);
1✔
326
                }
327

328
                foreach ($this->appends as $item) {
1✔
329
                        if ($item instanceof self) {
1✔
330
                                yield from $item->getIterator();
1✔
331
                        } else {
332
                                $item = FileSystem::platformSlashes($item);
1✔
333
                                yield $item => new FileInfo($item);
1✔
334
                        }
335
                }
336
        }
1✔
337

338

339
        /**
340
         * @param  array<object{pattern: string, mode: string, recursive: bool}>  $searches
341
         * @param  string[]  $subdirs
342
         * @return \Generator<string, FileInfo>
343
         */
344
        private function traverseDir(string $dir, array $searches, array $subdirs = []): \Generator
1✔
345
        {
346
                if ($this->maxDepth >= 0 && count($subdirs) > $this->maxDepth) {
1✔
347
                        return;
1✔
348
                } elseif (!is_dir($dir)) {
1✔
349
                        throw new Nette\InvalidStateException(sprintf("Directory '%s' does not exist.", rtrim($dir, '/\\')));
1✔
350
                }
351

352
                try {
353
                        $pathNames = new \FilesystemIterator($dir, \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::UNIX_PATHS);
1✔
UNCOV
354
                } catch (\UnexpectedValueException $e) {
×
UNCOV
355
                        if ($this->ignoreUnreadableDirs) {
×
UNCOV
356
                                return;
×
357
                        } else {
UNCOV
358
                                throw new Nette\InvalidStateException($e->getMessage());
×
359
                        }
360
                }
361

362
                $files = $this->convertToFiles($pathNames, implode('/', $subdirs), FileSystem::isAbsolute($dir));
1✔
363

364
                if ($this->sort) {
1✔
365
                        $files = iterator_to_array($files);
1✔
366
                        usort($files, $this->sort);
1✔
367
                }
368

369
                foreach ($files as $file) {
1✔
370
                        $pathName = $file->getPathname();
1✔
371
                        $cache = $subSearch = [];
1✔
372

373
                        if ($file->isDir()) {
1✔
374
                                foreach ($searches as $search) {
1✔
375
                                        if ($search->recursive && $this->proveFilters($this->descentFilters, $file, $cache)) {
1✔
376
                                                $subSearch[] = $search;
1✔
377
                                        }
378
                                }
379
                        }
380

381
                        if ($this->childFirst && $subSearch) {
1✔
382
                                yield from $this->traverseDir($pathName, $subSearch, array_merge($subdirs, [$file->getBasename()]));
1✔
383
                        }
384

385
                        $relativePathname = FileSystem::unixSlashes($file->getRelativePathname());
1✔
386
                        foreach ($searches as $search) {
1✔
387
                                if (
388
                                        "is_$search->mode"(Helpers::IsWindows && $file->isLink() ? $file->getLinkTarget() : $file->getPathname())
1✔
389
                                        && preg_match($search->pattern, $relativePathname)
1✔
390
                                        && $this->proveFilters($this->filters, $file, $cache)
1✔
391
                                ) {
392
                                        yield $pathName => $file;
1✔
393
                                        break;
1✔
394
                                }
395
                        }
396

397
                        if (!$this->childFirst && $subSearch) {
1✔
398
                                yield from $this->traverseDir($pathName, $subSearch, array_merge($subdirs, [$file->getBasename()]));
1✔
399
                        }
400
                }
401
        }
1✔
402

403

404
        private function convertToFiles(iterable $pathNames, string $relativePath, bool $absolute): \Generator
1✔
405
        {
406
                foreach ($pathNames as $pathName) {
1✔
407
                        if (!$absolute) {
1✔
408
                                $pathName = preg_replace('~\.?/~A', '', $pathName);
1✔
409
                        }
410
                        $pathName = FileSystem::platformSlashes($pathName);
1✔
411
                        yield new FileInfo($pathName, $relativePath);
1✔
412
                }
413
        }
1✔
414

415

416
        private function proveFilters(array $filters, FileInfo $file, array &$cache): bool
1✔
417
        {
418
                foreach ($filters as $filter) {
1✔
419
                        $res = &$cache[spl_object_id($filter)];
1✔
420
                        $res ??= $filter($file);
1✔
421
                        if (!$res) {
1✔
422
                                return false;
1✔
423
                        }
424
                }
425

426
                return true;
1✔
427
        }
428

429

430
        /** @return array<string, array<object{pattern: string, mode: string, recursive: bool}>> */
431
        private function buildPlan(): array
432
        {
433
                $plan = $dirCache = [];
1✔
434
                foreach ($this->find as [$mask, $mode]) {
1✔
435
                        $splits = [];
1✔
436
                        if (FileSystem::isAbsolute($mask)) {
1✔
437
                                if ($this->in) {
1✔
438
                                        throw new Nette\InvalidStateException("You cannot combine the absolute path in the mask '$mask' and the directory to search '{$this->in[0]}'.");
1✔
439
                                }
440
                                $splits[] = self::splitRecursivePart($mask);
1✔
441
                        } else {
442
                                foreach ($this->in ?: ['.'] as $in) {
1✔
443
                                        $in = strtr($in, ['[' => '[[]', ']' => '[]]']); // in path, do not treat [ and ] as a pattern by glob()
1✔
444
                                        $splits[] = self::splitRecursivePart($in . '/' . $mask);
1✔
445
                                }
446
                        }
447

448
                        foreach ($splits as [$base, $rest, $recursive]) {
1✔
449
                                $base = $base === '' ? '.' : $base;
1✔
450
                                $dirs = $dirCache[$base] ??= strpbrk($base, '*?[')
1✔
451
                                        ? glob($base, GLOB_NOSORT | GLOB_ONLYDIR | GLOB_NOESCAPE)
1✔
452
                                        : [strtr($base, ['[[]' => '[', '[]]' => ']'])]; // unescape [ and ]
1✔
453

454
                                if (!$dirs) {
1✔
455
                                        throw new Nette\InvalidStateException(sprintf("Directory '%s' does not exist.", rtrim($base, '/\\')));
1✔
456
                                }
457

458
                                $search = (object) ['pattern' => $this->buildPattern($rest), 'mode' => $mode, 'recursive' => $recursive];
1✔
459
                                foreach ($dirs as $dir) {
1✔
460
                                        $plan[$dir][] = $search;
1✔
461
                                }
462
                        }
463
                }
464

465
                return $plan;
1✔
466
        }
467

468

469
        /**
470
         * Since glob() does not know ** wildcard, we divide the path into a part for glob and a part for manual traversal.
471
         */
472
        private static function splitRecursivePart(string $path): array
1✔
473
        {
474
                $a = strrpos($path, '/');
1✔
475
                $parts = preg_split('~(?<=^|/)\*\*($|/)~', substr($path, 0, $a + 1), 2);
1✔
476
                return isset($parts[1])
1✔
477
                        ? [$parts[0], $parts[1] . substr($path, $a + 1), true]
1✔
478
                        : [$parts[0], substr($path, $a + 1), false];
1✔
479
        }
480

481

482
        /**
483
         * Converts wildcards to regular expression.
484
         */
485
        private function buildPattern(string $mask): string
1✔
486
        {
487
                if ($mask === '*') {
1✔
488
                        return '##';
1✔
489
                } elseif (str_starts_with($mask, './')) {
1✔
490
                        $anchor = '^';
1✔
491
                        $mask = substr($mask, 2);
1✔
492
                } else {
493
                        $anchor = '(?:^|/)';
1✔
494
                }
495

496
                $pattern = strtr(
1✔
497
                        preg_quote($mask, '#'),
1✔
498
                        [
499
                                '\*\*/' => '(.+/)?',
1✔
500
                                '\*' => '[^/]*',
501
                                '\?' => '[^/]',
502
                                '\[\!' => '[^',
503
                                '\[' => '[',
504
                                '\]' => ']',
505
                                '\-' => '-',
506
                        ],
507
                );
508
                return '#' . $anchor . $pattern . '$#D' . (Helpers::IsWindows ? 'i' : '');
1✔
509
        }
510
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc