Passed
Push — master ( df14c7...b8b66a )
by Alec
01:40
created

CallerDataFormatter::assertOptions()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 4.125

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 2
nop 1
dl 0
loc 5
ccs 2
cts 4
cp 0.5
crap 4.125
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
4
namespace AlecRabbit\Accessories\Caller;
5
6
use AlecRabbit\Accessories\Caller\Contracts\CallerConstants;
7
use AlecRabbit\Accessories\Caller\Contracts\CallerDataFormatterInterface;
8
use function AlecRabbit\typeOf;
9
10
class CallerDataFormatter implements CallerDataFormatterInterface, CallerConstants
11
{
12
    /** @var int */
13
    protected $options;
14
15 1
    public function __construct($options = null)
16
    {
17 1
        $this->assertOptions($options);
18 1
        $this->options = $options ?? static::SHOW_LINE_AND_FILE;
19 1
    }
20
21 4
    public function process(CallerData $data): string
22
    {
23 4
        if (null !== $class = $data->getClass()) {
24
            return
25 3
                sprintf(
26 3
                    '%s%s%s%s',
27 3
                    $this->getLineAndFile($data),
28 3
                    $class,
29 3
                    $data->getType(),
30 3
                    $this->getFunction($data)
31
                );
32
        }
33
        return
34 1
            sprintf(
35 1
                '%s%s',
36 1
                $this->getLineAndFile($data),
37 1
                $this->getFunction($data)
38
            );
39
    }
40
41
    /**
42
     * @param CallerData $caller
43
     * @return string
44
     */
45 4
    private function getLineAndFile(CallerData $caller): string
46
    {
47 4
        if (($this->options & static::SHOW_LINE_AND_FILE) && self::STR_UNDEFINED !== $caller->getFunction()) {
48
            return
49 4
                sprintf(
50 4
                    '[%s:"%s"] ',
51 4
                    $caller->getLine(),
52 4
                    $caller->getFile()
53
                );
54
        }
55
        return '';
56
    }
57
58 4
    private function getFunction(CallerData $caller)
59
    {
60 4
        if (self::STR_UNDEFINED === $function = $caller->getFunction()) {
61
            $function = ucfirst($function);
62
        } else {
63 4
            $function .= '()';
64
        }
65 4
        return $function;
66
    }
67
68
    /**
69
     * @param $options
70
     */
71 1
    private function assertOptions($options): void
72
    {
73 1
        if (null !== $options && !is_int($options)) {
74
            throw new \RuntimeException(
75
                'Options for ' . __CLASS__ . ' constructor should be int, "' . typeOf($options) . '" given.'
76
            );
77
        }
78 1
    }
79
}
80