Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
84.62% covered (warning)
84.62%
66 / 78
55.56% covered (warning)
55.56%
5 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
DirectoryConfig
84.62% covered (warning)
84.62%
66 / 78
55.56% covered (warning)
55.56%
5 / 9
41.98
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 provideConfigs
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 discoverFiles
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 discoverDirectories
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
5.06
 matchFiles
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
5.03
 discoverChildDirectories
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
7
 openDirectory
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 isWithinDirectory
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
5.58
 escapeDirectory
58.82% covered (warning)
58.82%
10 / 17
0.00% covered (danger)
0.00%
0 / 1
2.28
1<?php
2
3declare(strict_types=1);
4
5/**
6 * This file is part of php-fast-forward/config.
7 *
8 * This source file is subject to the license bundled
9 * with this source code in the file LICENSE.
10 *
11 * @copyright Copyright (c) 2025-2026 Felipe Sayão Lobato Abreu <github@mentordosnerds.com>
12 * @license   https://opensource.org/licenses/MIT MIT License
13 *
14 * @see       https://github.com/php-fast-forward/config
15 * @see       https://github.com/php-fast-forward
16 * @see       https://datatracker.ietf.org/doc/html/rfc2119
17 */
18
19namespace FastForward\Config;
20
21use DirectoryIterator;
22use FastForward\Config\Exception\InvalidArgumentException;
23use Generator;
24use Laminas\ConfigAggregator\GlobTrait;
25use UnexpectedValueException;
26
27/**
28 * Class DirectoryConfig.
29 *
30 * Loads and aggregates configuration from a specified directory containing PHP files.
31 * This class MUST validate the target directory and match file names using Laminas glob semantics.
32 * It MAY cache the aggregated result if a cached config file path is provided.
33 *
34 * @extends LaminasConfigAggregatorConfig
35 */
36class DirectoryConfig extends LaminasConfigAggregatorConfig implements ConfigInterface
37{
38    use GlobTrait;
39    use LazyLoadConfigTrait;
40
41    /**
42     * @var string file matching pattern for PHP configuration files
43     */
44    protected const PATTERN = '{,*}.php';
45
46    /**
47     * @var bool whether child directories should be discovered
48     */
49    protected const RECURSIVE = false;
50
51    /**
52     * Constructs a DirectoryConfig instance.
53     *
54     * This constructor SHALL validate the specified directory, and initialize
55     * the Laminas config aggregator with a lazy file provider using the defined pattern.
56     * An existing cache file SHALL be reused when provided.
57     * Generating a cache file additionally requires a truthy config_cache_enabled entry.
58     *
59     * @param string $directory the directory path from which to load configuration files
60     * @param string|null $cachedConfigFile optional path to a cache file for the aggregated configuration
61     *
62     * @throws InvalidArgumentException if the directory is not valid or not readable
63     */
64    public function __construct(
65        private  string $directory,
66        private  ?string $cachedConfigFile = null,
67    ) {
68        if (! is_dir($this->directory) || ! is_readable($this->directory)) {
69            throw InvalidArgumentException::forUnreadableDirectory($this->directory);
70        }
71
72        parent::__construct(
73            providers: [$this->provideConfigs(...)],
74            cachedConfigFile: $this->cachedConfigFile,
75        );
76    }
77
78    /**
79     * Includes discovered PHP files only when the aggregator resolves this provider.
80     *
81     * @return Generator
82     */
83    private function provideConfigs(): Generator
84    {
85        foreach ($this->discoverFiles() as $file) {
86            yield include $file;
87        }
88    }
89
90    /**
91     * Discovers files in depth-then-path order without following directory symlinks.
92     *
93     * @return list<string>
94     */
95    private function discoverFiles(): array
96    {
97        $files = [];
98
99        foreach ($this->discoverDirectories() as $directory => $realDirectory) {
100            foreach ($this->matchFiles($directory, $realDirectory) as $file) {
101                $files[$file] = $file;
102            }
103        }
104
105        return array_values($files);
106    }
107
108    /**
109     * Yields directory paths and their canonical identities in depth-then-path order.
110     *
111     * @return Generator<string, string>
112     */
113    private function discoverDirectories(): Generator
114    {
115        $directories = [$this->directory];
116        $seenDirectories = [];
117
118        while ([] !== $directories) {
119            usort($directories, static fn(string $first, string $second): int => strcmp($first . '/', $second . '/'));
120            $nextDirectories = [];
121            foreach ($directories as $directory) {
122                $realDirectory = realpath($directory);
123                if (false === $realDirectory) {
124                    continue;
125                }
126
127                if (isset($seenDirectories[$realDirectory])) {
128                    continue;
129                }
130
131                $seenDirectories[$realDirectory] = true;
132                yield $directory => $realDirectory;
133                array_push($nextDirectories, ...$this->discoverChildDirectories($directory));
134            }
135
136            $directories = $nextDirectories;
137        }
138    }
139
140    /**
141     * Matches the configured pattern inside a literal directory and resolves each file.
142     *
143     * @param string $directory the discovered directory path
144     * @param string $realDirectory its canonical identity
145     *
146     * @return Generator<int, string>
147     */
148    private function matchFiles(string $directory, string $realDirectory): Generator
149    {
150        $pattern = $this->escapeDirectory($directory) . '/' . static::PATTERN;
151        foreach ($this->glob($pattern) as $file) {
152            $file = (string) $file;
153            if (! is_file($file)) {
154                continue;
155            }
156
157            if (! $this->isWithinDirectory($file, $realDirectory)) {
158                continue;
159            }
160
161            $realFile = realpath($file);
162            if (false !== $realFile) {
163                yield $realFile;
164            }
165        }
166    }
167
168    /**
169     * Selects visible child directories when recursive discovery is enabled.
170     *
171     * @param string $directory the parent directory path
172     *
173     * @return list<string>
174     */
175    private function discoverChildDirectories(string $directory): array
176    {
177        if (! static::RECURSIVE) {
178            return [];
179        }
180
181        $iterator = $this->openDirectory($directory);
182        if (! $iterator instanceof DirectoryIterator) {
183            return [];
184        }
185
186        $directories = [];
187        foreach ($iterator as $entry) {
188            if ($entry->isDir() && ! $entry->isLink() && ! str_starts_with($entry->getFilename(), '.')) {
189                $directories[] = $entry->getPathname();
190            }
191        }
192
193        return $directories;
194    }
195
196    /**
197     * Skips children that become inaccessible between discovery and opening.
198     *
199     * @param string $directory the discovered directory path
200     *
201     * @throws UnexpectedValueException for root failures or unrelated directory-opening errors
202     */
203    private function openDirectory(string $directory): ?DirectoryIterator
204    {
205        try {
206            return new DirectoryIterator($directory);
207        } catch (UnexpectedValueException $unexpectedValueException) {
208            clearstatcache(true, $directory);
209            if ($directory !== $this->directory && (! is_dir($directory) || ! is_readable($directory))) {
210                return null;
211            }
212
213            throw $unexpectedValueException;
214        }
215    }
216
217    /**
218     * Checks a candidate's canonical parent against the selected literal directory.
219     *
220     * @param string $file the candidate path
221     * @param string $directory the canonical selected directory
222     *
223     * @return bool
224     */
225    private function isWithinDirectory(string $file, string $directory): bool
226    {
227        $parent = realpath(\dirname($file));
228        if (false === $parent) {
229            return false;
230        }
231
232        $prefix = rtrim($directory, \DIRECTORY_SEPARATOR) . \DIRECTORY_SEPARATOR;
233
234        if ('\\' === \DIRECTORY_SEPARATOR) {
235            return 0 === strcasecmp($directory, $parent) || 0 === strncasecmp($parent, $prefix, \strlen($prefix));
236        }
237
238        return $directory === $parent || str_starts_with($parent, $prefix);
239    }
240
241    /**
242     * Escapes only the directory, leaving the library's filename pattern intact.
243     *
244     * @param string $directory the literal directory path
245     *
246     * @return string
247     */
248    private function escapeDirectory(string $directory): string
249    {
250        if ('\\' === \DIRECTORY_SEPARATOR) {
251            $directory = str_replace('\\', '/', $directory);
252
253            // Windows glob forces GLOB_NOESCAPE. Verify candidate parent identities before including files.
254            return strtr(rtrim($directory, '/'), [
255                '[' => '[[]',
256                ']' => '[]]',
257                '{' => '?',
258                '}' => '?',
259            ]);
260        }
261
262        return strtr(rtrim($directory, '/'), [
263            '\\' => '\\\\',
264            '[' => '\\[',
265            ']' => '\\]',
266            '*' => '\\*',
267            '?' => '\\?',
268            '{' => '\\{',
269            '}' => '\\}',
270        ]);
271    }
272}