Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
74.42% covered (warning)
74.42%
160 / 215
36.84% covered (danger)
36.84%
7 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
PhpFileConfig
74.42% covered (warning)
74.42%
160 / 215
36.84% covered (danger)
36.84%
7 / 19
376.27
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 __invoke
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 set
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 remove
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 loadConfig
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
 mutate
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
8.04
 mutateUnderLock
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 prepareWritableTarget
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
8.09
 dump
80.00% covered (warning)
80.00%
12 / 15
0.00% covered (danger)
0.00%
0 / 1
5.20
 readExistingMetadata
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
4.25
 exportContent
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 applyTemporaryMetadata
64.29% covered (warning)
64.29%
9 / 14
0.00% covered (danger)
0.00%
0 / 1
20.70
 resolveTargetFile
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
10.24
 followSymlinks
83.33% covered (warning)
83.33%
20 / 24
0.00% covered (danger)
0.00%
0 / 1
13.78
 findSymlinkComponent
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
6
 isStreamPath
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
8.63
 absolutePath
42.86% covered (danger)
42.86%
9 / 21
0.00% covered (danger)
0.00%
0 / 1
63.77
 anchorWindowsRootedPath
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 anchorWindowsDriveRelativePath
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
110
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 Brick\VarExporter\VarExporter;
22use FastForward\Config\Exception\InvalidArgumentException;
23use Throwable;
24
25/**
26 * Class PhpFileConfig.
27 *
28 * Provides a configuration source backed by a single PHP file returning an array.
29 * This class MUST load the configuration from the specified PHP file.
30 * It SHALL lazily initialize and retrieve configuration data upon invocation.
31 * If configured as persistent, mutations made via `set` and `remove` SHALL be persisted back to the file.
32 */
33 class PhpFileConfig implements ConfigInterface
34{
35    use LazyLoadConfigTrait;
36
37    private ?string $absoluteFile = null;
38
39    /**
40     * Constructs a PhpFileConfig instance.
41     *
42     * @param string $file the path to the PHP configuration file
43     * @param bool $persistent whether changes should be saved back to the file
44     * @param array<string, mixed>|ConfigInterface|null $defaultConfig optional default configuration when the file does not exist
45     */
46    public function __construct(
47        private  string $file,
48        private  bool $persistent = false,
49        private  array|ConfigInterface|null $defaultConfig = null,
50    ) {}
51
52    /**
53     * Invokes the configuration and returns the configuration data.
54     *
55     * If the file exists, it MUST return a valid array.
56     * If the file does not exist but a default configuration is provided,
57     * the default configuration SHALL be used.
58     *
59     * @return ConfigInterface a ConfigInterface implementation containing the configuration data
60     *
61     * @throws InvalidArgumentException if the file is unreadable or does not return an array
62     */
63    public function __invoke(): ConfigInterface
64    {
65        return $this->loadConfig();
66    }
67
68    /**
69     * Sets configuration data.
70     *
71     * This method MUST update the configuration data in the file if the persistent flag is set to true.
72     *
73     * @param array<string, mixed>|ConfigInterface|string $key the configuration key or an array of key-value pairs to set
74     * @param mixed $value the value to set for the specified key
75     *
76     * @return void
77     *
78     * @throws InvalidArgumentException if the key is invalid or file cannot be written
79     */
80    public function set(array|ConfigInterface|string $key, mixed $value = null): void
81    {
82        if (! $this->persistent) {
83            $this->getConfig()
84                ->set($key, $value);
85
86            return;
87        }
88
89        $this->mutate(static function (ConfigInterface $config) use ($key, $value): void {
90            $config->set($key, $value);
91        });
92    }
93
94    /**
95     * Removes a configuration key and its associated value.
96     *
97     * This method MUST update the configuration data in the file if the persistent flag is set to true.
98     *
99     * @param string $key the configuration key to remove
100     *
101     * @return void
102     *
103     * @throws InvalidArgumentException if the file cannot be written
104     */
105    public function remove(string $key): void
106    {
107        if (! $this->persistent) {
108            $this->getConfig()
109                ->remove($key);
110
111            return;
112        }
113
114        $this->mutate(static function (ConfigInterface $config) use ($key): void {
115            $config->remove($key);
116        });
117    }
118
119    /**
120     * Loads the configuration from the file or default configuration.
121     *
122     * @param string|null $targetFile resolved target shared with a persistent mutation
123     *
124     * @return ConfigInterface
125     *
126     * @throws InvalidArgumentException if the file is unreadable or does not return an array
127     */
128    private function loadConfig(?string $targetFile = null): ConfigInterface
129    {
130        $targetFile ??= $this->resolveTargetFile();
131
132        if (! file_exists($targetFile)) {
133            if (null !== $this->defaultConfig) {
134                $data = $this->defaultConfig instanceof ConfigInterface
135                    ? $this->defaultConfig->toArray()
136                    : $this->defaultConfig;
137
138                return new ArrayConfig($data);
139            }
140
141            throw InvalidArgumentException::forUnreadableFile($this->file);
142        }
143
144        if (! is_file($targetFile) || ! is_readable($targetFile)) {
145            throw InvalidArgumentException::forUnreadableFile($this->file);
146        }
147
148        $data = (static fn(string $file): mixed => require $file)($targetFile);
149
150        if (! \is_array($data)) {
151            throw InvalidArgumentException::forInvalidConfigFile($this->file);
152        }
153
154        return new ArrayConfig($data);
155    }
156
157    /**
158     * Mutates the resolved target under an exclusive process lock.
159     *
160     * @param callable(ConfigInterface): void $operation
161     */
162    private function mutate(callable $operation): void
163    {
164        $targetFile = $this->resolveTargetFile();
165        if ('' === $targetFile || str_contains($targetFile, "\0") || ! \function_exists('str_ends_with')
166            || str_ends_with($targetFile, '/')
167            || ('\\' === \DIRECTORY_SEPARATOR && str_ends_with($targetFile, '\\'))) {
168            throw InvalidArgumentException::forUnwritableFile($this->file);
169        }
170
171        $dir = $this->prepareWritableTarget($targetFile);
172        $lockPath = $dir . '/.' . basename($targetFile) . '.lock';
173        $lockFp   = @fopen($lockPath, 'c+');
174
175        if (false === $lockFp) {
176            throw InvalidArgumentException::forUnwritableFile($this->file);
177        }
178
179        try {
180            $this->mutateUnderLock($lockFp, $targetFile, $operation);
181        } finally {
182            @fclose($lockFp);
183        }
184    }
185
186    /**
187     * @param resource $lockFp
188     * @param string $targetFile
189     * @param callable(ConfigInterface): void $operation
190     */
191    private function mutateUnderLock($lockFp, string $targetFile, callable $operation): void
192    {
193        if (! @flock($lockFp, \LOCK_EX)) {
194            throw InvalidArgumentException::forUnwritableFile($this->file);
195        }
196
197        try {
198            $config = $this->loadConfig($targetFile);
199            $operation($config);
200            $this->dump($config->toArray(), $targetFile);
201            $this->config = $config;
202        } finally {
203            @flock($lockFp, \LOCK_UN);
204        }
205    }
206
207    /**
208     * @param string $targetFile
209     *
210     * @return string
211     */
212    private function prepareWritableTarget(string $targetFile): string
213    {
214        $dir = \dirname($targetFile);
215
216        if (! is_dir($dir)) {
217            if (! @mkdir($dir, 0o777, true) && ! is_dir($dir)) {
218                throw InvalidArgumentException::forUnwritableFile($this->file);
219            }
220        } elseif (! is_writable($dir)) {
221            throw InvalidArgumentException::forUnwritableFile($this->file);
222        }
223
224        if (file_exists($targetFile) && (! is_file($targetFile) || ! is_writable($targetFile))) {
225            throw InvalidArgumentException::forUnwritableFile($this->file);
226        }
227
228        return $dir;
229    }
230
231    /**
232     * Publishes configuration atomically after revalidating the locked target.
233     *
234     * @param array<array-key, mixed> $data
235     * @param string $targetFile
236     */
237    private function dump(array $data, string $targetFile): void
238    {
239        $dir = $this->prepareWritableTarget($targetFile);
240        $existingMetadata = $this->readExistingMetadata($targetFile);
241        $content = $this->exportContent($data);
242        $tmpFile = tempnam($dir, 'cfg_');
243        if (false === $tmpFile) {
244            throw InvalidArgumentException::forUnwritableFile($this->file);
245        }
246
247        try {
248            $bytesWritten = @file_put_contents($tmpFile, $content, \LOCK_EX);
249            if ($bytesWritten !== \strlen($content)) {
250                throw InvalidArgumentException::forUnwritableFile($this->file);
251            }
252
253            $this->applyTemporaryMetadata($tmpFile, $existingMetadata);
254            if (! @rename($tmpFile, $targetFile)) {
255                throw InvalidArgumentException::forUnwritableFile($this->file);
256            }
257        } finally {
258            @unlink($tmpFile);
259        }
260
261        if (\function_exists('opcache_invalidate')) {
262            @opcache_invalidate($targetFile, true);
263        }
264    }
265
266    /**
267     * @param string $targetFile
268     *
269     * @return array<array-key, int>|null
270     */
271    private function readExistingMetadata(string $targetFile): ?array
272    {
273        if (! file_exists($targetFile)) {
274            return null;
275        }
276
277        if (! \function_exists('stat')) {
278            throw InvalidArgumentException::forUnwritableFile($this->file);
279        }
280
281        $metadata = @stat($targetFile);
282        if (false === $metadata) {
283            throw InvalidArgumentException::forUnwritableFile($this->file);
284        }
285
286        return $metadata;
287    }
288
289    /**
290     * @param array<array-key, mixed> $data
291     */
292    private function exportContent(array $data): string
293    {
294        try {
295            $exported = VarExporter::export($data);
296        } catch (Throwable $throwable) {
297            throw new InvalidArgumentException($throwable->getMessage(), (int) $throwable->getCode(), $throwable);
298        }
299
300        return "<?php\n\ndeclare(strict_types=1);\n\nreturn {$exported};\n";
301    }
302
303    /**
304     * @param string $tmpFile
305     * @param array<array-key, int>|null $existingMetadata
306     */
307    private function applyTemporaryMetadata(string $tmpFile, ?array $existingMetadata): void
308    {
309        if (null !== $existingMetadata && '\\' !== \DIRECTORY_SEPARATOR) {
310            if (! \function_exists('filegroup')) {
311                throw InvalidArgumentException::forUnwritableFile($this->file);
312            }
313
314            $temporaryGroup = @filegroup($tmpFile);
315            if (false === $temporaryGroup) {
316                throw InvalidArgumentException::forUnwritableFile($this->file);
317            }
318
319            if ($temporaryGroup !== $existingMetadata['gid']
320                && (! \function_exists('chgrp') || ! @chgrp($tmpFile, $existingMetadata['gid']))) {
321                throw InvalidArgumentException::forUnwritableFile($this->file);
322            }
323        }
324
325        if (! \function_exists('chmod') || (null === $existingMetadata && ! \function_exists('umask'))) {
326            throw InvalidArgumentException::forUnwritableFile($this->file);
327        }
328
329        $mode = null !== $existingMetadata ? ($existingMetadata['mode'] & 0o777) : (0o666 & ~umask());
330        if (! @chmod($tmpFile, $mode)) {
331            throw InvalidArgumentException::forUnwritableFile($this->file);
332        }
333    }
334
335    /**
336     * Anchors the input location on first use and resolves its current symlink target.
337     *
338     * @return string
339     */
340    private function resolveTargetFile(): string
341    {
342        if ('' === $this->file) {
343            return $this->file;
344        }
345
346        if (! \function_exists('str_contains')) {
347            throw InvalidArgumentException::forUnreadableFile($this->file);
348        }
349
350        if (str_contains($this->file, "\0")) {
351            return $this->file;
352        }
353
354        if (! \function_exists('realpath') || ! \function_exists('clearstatcache') || ! \function_exists('is_link')) {
355            throw InvalidArgumentException::forUnreadableFile($this->file);
356        }
357
358        clearstatcache(true);
359        $file = $this->absoluteFile ??= $this->absolutePath($this->file);
360        if ($this->isStreamPath($file)) {
361            return $file;
362        }
363
364        if (file_exists($file) && ! is_file($file)) {
365            return $file;
366        }
367
368        return $this->followSymlinks($file);
369    }
370
371    /**
372     * @param string $file
373     *
374     * @return string
375     */
376    private function followSymlinks(string $file): string
377    {
378        if (! \function_exists('str_ends_with')) {
379            throw InvalidArgumentException::forUnreadableFile($this->file);
380        }
381
382        $visited = [];
383
384        for ($depth = 0; $depth < 64; ++$depth) {
385            if (str_ends_with($file, '/') || ('\\' === \DIRECTORY_SEPARATOR && str_ends_with($file, '\\'))) {
386                return $file;
387            }
388
389            if (! \function_exists('dirname') || ! \function_exists('basename')) {
390                throw InvalidArgumentException::forUnreadableFile($this->file);
391            }
392
393            $component = $this->findSymlinkComponent($file);
394            $link = $component['path'];
395            $suffix = $component['suffix'];
396            if (! $component['linked']) {
397                $file = $link . $suffix;
398                $resolved = realpath($file);
399
400                return false !== $resolved ? $resolved : $file;
401            }
402
403            $file = $link . $suffix;
404            if (isset($visited[$file]) || ! \function_exists('readlink')) {
405                throw InvalidArgumentException::forUnreadableFile($this->file);
406            }
407
408            $visited[$file] = true;
409            $target = @readlink($link);
410            if (false === $target) {
411                throw InvalidArgumentException::forUnreadableFile($this->file);
412            }
413
414            $file = $this->absolutePath($target, \dirname($link)) . $suffix;
415        }
416
417        throw InvalidArgumentException::forUnreadableFile($this->file);
418    }
419
420    /**
421     * @param string $file
422     *
423     * @return array{path: string, suffix: string, linked: bool}
424     */
425    private function findSymlinkComponent(string $file): array
426    {
427        $link = $file;
428        $suffix = '';
429        while (true) {
430            $directory = realpath(\dirname($link));
431            if (false !== $directory) {
432                $link = $directory . \DIRECTORY_SEPARATOR . basename($link);
433            }
434
435            if (is_link($link)) {
436                return [
437                    'path' => $link,
438                    'suffix' => $suffix,
439                    'linked' => true,
440                ];
441            }
442
443            $parent = \dirname($link);
444            if (false !== $directory || $parent === $link) {
445                return [
446                    'path' => $link,
447                    'suffix' => $suffix,
448                    'linked' => false,
449                ];
450            }
451
452            $suffix = \DIRECTORY_SEPARATOR . basename($link) . $suffix;
453            $link = $parent;
454        }
455    }
456
457    /**
458     * Recognizes the registered protocols selected by PHP's native stream lookup.
459     *
460     * @param string $path
461     *
462     * @return bool
463     */
464    private function isStreamPath(string $path): bool
465    {
466        if (! str_contains($path, '://')) {
467            return false;
468        }
469
470        if (! \function_exists('preg_match')) {
471            throw InvalidArgumentException::forUnreadableFile($this->file);
472        }
473
474        if (1 !== preg_match('~^([a-zA-Z0-9+.-]{2,})://~', $path, $matches)) {
475            return false;
476        }
477
478        if (! \function_exists('stream_get_wrappers') || ! \function_exists('in_array')) {
479            throw InvalidArgumentException::forUnreadableFile($this->file);
480        }
481
482        $wrappers = stream_get_wrappers();
483
484        if (\in_array($matches[1], $wrappers, true)) {
485            return true;
486        }
487
488        if (! \function_exists('strtolower')) {
489            throw InvalidArgumentException::forUnreadableFile($this->file);
490        }
491
492        return \in_array(strtolower($matches[1]), $wrappers, true);
493    }
494
495    /**
496     * Resolves relative paths against their containing directory without using include_path.
497     *
498     * @param string $path the file or symlink target path
499     * @param string|null $directory the directory containing a relative symlink target
500     *
501     * @return string
502     */
503    private function absolutePath(string $path, ?string $directory = null): string
504    {
505        if ('\\' === \DIRECTORY_SEPARATOR) {
506            if (! \function_exists('strspn')) {
507                throw InvalidArgumentException::forUnreadableFile($this->file);
508            }
509
510            if (1 === strspn($path, '\\/')) {
511                return $this->anchorWindowsRootedPath($path, $directory);
512            }
513        }
514
515        if (! \function_exists('str_starts_with')) {
516            throw InvalidArgumentException::forUnreadableFile($this->file);
517        }
518
519        if (str_starts_with($path, '/') || (null === $directory && $this->isStreamPath($path))
520            || ('\\' === \DIRECTORY_SEPARATOR && str_starts_with($path, '\\'))) {
521            return $path;
522        }
523
524        if ('\\' === \DIRECTORY_SEPARATOR) {
525            if (! \function_exists('preg_match')) {
526                throw InvalidArgumentException::forUnreadableFile($this->file);
527            }
528
529            if (1 === preg_match('~^[a-zA-Z]:[\\\\/]~', $path)) {
530                return $path;
531            }
532
533            if (1 === preg_match('~^[a-zA-Z]:~', $path)) {
534                return $this->anchorWindowsDriveRelativePath($path);
535            }
536        }
537
538        $directory ??= \function_exists('getcwd') ? getcwd() : false;
539        if (false === $directory) {
540            throw InvalidArgumentException::forUnreadableFile($this->file);
541        }
542
543        return $directory . \DIRECTORY_SEPARATOR . $path;
544    }
545
546    /**
547     * @param string $path
548     * @param string|null $directory
549     *
550     * @return string
551     */
552    private function anchorWindowsRootedPath(string $path, ?string $directory): string
553    {
554        $directory ??= \function_exists('getcwd') ? getcwd() : false;
555        if (false === $directory || ! \function_exists('preg_match') || 1 !== preg_match(
556            '~^(?:[a-zA-Z]:|[\\\\/]{2}(?:[?.][\\\\/]UNC[\\\\/])?[^\\\\/]+[\\\\/][^\\\\/]+)~i',
557            $directory,
558            $root
559        )) {
560            throw InvalidArgumentException::forUnreadableFile($this->file);
561        }
562
563        return $root[0] . $path;
564    }
565
566    /**
567     * @param string $path
568     *
569     * @return string
570     */
571    private function anchorWindowsDriveRelativePath(string $path): string
572    {
573        if (false === realpath($path)) {
574            throw InvalidArgumentException::forUnreadableFile($this->file);
575        }
576
577        if (! \function_exists('substr')) {
578            throw InvalidArgumentException::forUnreadableFile($this->file);
579        }
580
581        $drive = substr($path, 0, 2);
582        $directory = \function_exists('getcwd') ? getcwd() : false;
583        if (false !== $directory && ! \function_exists('strncasecmp')) {
584            throw InvalidArgumentException::forUnreadableFile($this->file);
585        }
586
587        if (false === $directory || 0 !== strncasecmp($drive, $directory, 2)) {
588            $directory = realpath($drive . '.');
589        }
590
591        if (false === $directory || ! \function_exists('rtrim')) {
592            throw InvalidArgumentException::forUnreadableFile($this->file);
593        }
594
595        return rtrim($directory, '\\/') . \DIRECTORY_SEPARATOR . substr($path, 2);
596    }
597}