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

ParseException::getFileLabel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
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 RuntimeException;
9
use Illuminate\Support\Arr;
10
11
use function rtrim;
12
use function sprintf;
13
use function explode;
14
15
/** @experimental This class may change significantly before its release. */
16
class ParseException extends RuntimeException
17
{
18
    /** @var int */
19
    protected $code = 422;
20
21
    public function __construct(string $file = '', ?Throwable $previous = null)
22
    {
23
        parent::__construct($this->formatMessage($file, $previous), previous: $previous);
24
    }
25
26
    protected function formatMessage(string $file, ?Throwable $previous): string
27
    {
28
        return rtrim(sprintf('Invalid %s in file%s %s', $this->getTypeLabel($file), $this->getFileLabel($file), $this->getContext($previous)));
29
    }
30
31
    protected function getTypeLabel(string $file): string
32
    {
33
        return match (Arr::last(explode('.', $file))) {
34
            'md' => 'Markdown',
35
            'yaml', 'yml' => 'Yaml',
36
            'json' => 'Json',
37
            default => 'data',
38
        };
39
    }
40
41
    protected function getFileLabel(string $file): string
42
    {
43
        return $file ? sprintf(": '%s'", $file) : '';
44
    }
45
46
    protected function getContext(?Throwable $previous): string
47
    {
48
        return ($previous && $previous->getMessage()) ? sprintf('(%s)', rtrim($previous->getMessage(), '.')) : '';
49
    }
50
}
51