Passed
Push — master ( b3233a...ff7dc9 )
by Alec
02:23
created

CallerDataFormatter::getFunction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 2
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
    /**
16
     * @param mixed $options
17
     */
18 4
    public function __construct($options = null)
19
    {
20 4
        $this->assertOptions($options);
21 3
        $this->options = $options ?? static::SHOW_LINE_AND_FILE;
22 3
    }
23
24
    /**
25
     * @param mixed $options
26
     */
27 4
    private function assertOptions($options): void
28
    {
29 4
        if (null !== $options && !is_int($options)) {
30 1
            throw new \RuntimeException(
31 1
                'Options for ' . __CLASS__ . ' constructor should be int, "' . typeOf($options) . '" given.'
32
            );
33
        }
34 3
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39 6
    public function process(CallerData $data): string
40
    {
41 6
        if (null !== $class = $data->getClass()) {
42
            return
43 4
                sprintf(
44 4
                    '%s%s%s%s',
45 4
                    $this->getLineAndFile($data),
46 4
                    $class,
47 4
                    $data->getType(),
48 4
                    $this->getFunction($data)
49
                );
50
        }
51
        return
52 2
            sprintf(
53 2
                '%s%s',
54 2
                $this->getLineAndFile($data),
55 2
                $this->getFunction($data)
56
            );
57
    }
58
59
    /**
60
     * @param CallerData $caller
61
     * @return string
62
     */
63 6
    private function getLineAndFile(CallerData $caller): string
64
    {
65 6
        if (($this->options & static::SHOW_LINE_AND_FILE) && self::STR_UNDEFINED !== $caller->getFunction()) {
66
            return
67 4
                sprintf(
68 4
                    '[%s:"%s"] ',
69 4
                    $caller->getLine(),
70 4
                    $caller->getFile()
71
                );
72
        }
73 2
        return '';
74
    }
75
76
    /**
77
     * @param CallerData $caller
78
     * @return string
79
     */
80 6
    private function getFunction(CallerData $caller): string
81
    {
82 6
        $function = $caller->getFunction();
83 6
        if ($function === self::STR_UNDEFINED) {
84 1
            return ucfirst($function);
85
        }
86 5
        return $function . '()';
87
    }
88
}
89