Passed
Push — master ( ad6b2a...b41ca0 )
by Caen
07:45 queued 14s
created

InvalidConfigurationException::try()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\Framework\Exceptions;
6
7
use Throwable;
8
use Hyde\Facades\Filesystem;
9
use InvalidArgumentException;
10
11
use function assert;
12
use function explode;
13
use function realpath;
14
15
class InvalidConfigurationException extends InvalidArgumentException
16
{
17
    public function __construct(string $message = 'Invalid configuration detected.', ?string $namespace = null, ?string $key = null, ?Throwable $previous = null)
18
    {
19
        if ($namespace && $key) {
20
            [$this->file, $this->line] = $this->findConfigLine($namespace, $key);
21
        }
22
23
        parent::__construct($message, previous: $previous);
24
    }
25
26
    /**
27
     * @experimental Please report any issues with this method to the authors at https://github.com/hydephp/develop/issues
28
     *
29
     * @return array{string, int}
0 ignored issues
show
Documentation Bug introduced by
The doc comment array{string, int} at position 2 could not be parsed: Expected ':' at position 2, but found 'string'.
Loading history...
30
     */
31
    protected function findConfigLine(string $namespace, string $key): array
32
    {
33
        $file = realpath("config/$namespace.php");
34
        $contents = Filesystem::getContents($file);
35
        $lines = explode("\n", $contents);
36
37
        foreach ($lines as $line => $content) {
38
            if (str_contains($content, "'$key' =>")) {
39
                break;
40
            }
41
        }
42
43
        assert($file !== false);
44
        assert(isset($line));
45
46
        return [$file, $line + 1];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $line seems to be defined by a foreach iteration on line 37. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
47
    }
48
49
    /**
50
     * @internal
51
     *
52
     * @experimental
53
     */
54
    public static function try(callable $callback, ?string $message = null): mixed
55
    {
56
        try {
57
            return $callback();
58
        } catch (Throwable $exception) {
59
            throw new static($message ?? $exception->getMessage(), previous: $exception);
60
        }
61
    }
62
}
63