IncludeCommand::execute()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 5.0342

Importance

Changes 0
Metric Value
dl 0
loc 33
ccs 16
cts 18
cp 0.8889
rs 8.439
c 0
b 0
f 0
cc 5
eloc 19
nc 5
nop 2
crap 5.0342
1
<?php declare(strict_types=1);
2
3
4
namespace Bigwhoop\Trumpet\Commands;
5
6
class IncludeCommand implements Command
7
{
8 1
    public function getToken(): string
9
    {
10 1
        return 'include';
11
    }
12
13 4
    public function execute(CommandParams $params, CommandExecutionContext $executionContext): string
14
    {
15 4
        $fileName = $params->getFirstArgument();
16
17 4
        if (!$executionContext->hasFileInWorkingDirectory($fileName)) {
18
            throw new ExecutionFailedException("File '$fileName' does not exist.");
19
        }
20
21 4
        $contents = $executionContext->getContentsOfFileInWorkingDirectory($fileName);
22
23 4
        switch ($params->getSecondArgument()) {
24 4
            case 'line':
25 2
                $lines = explode("\n", $contents);
26 2
                $range = $params->getThirdArgument();
27
28 2
                if (is_numeric($range)) {
29 1
                    return implode("\n", array_slice($lines, $range - 1, 1));
30
                }
31
32 1
                $matches = [];
33 1
                if (!preg_match('|(\d+)-(\d+)|', $range, $matches)) {
34
                    throw new ExecutionFailedException("Line definition '$range' is not valid. Must be in format N or N-N.");
35
                }
36
37 1
                $from = min([$matches[1], $matches[2]]);
38 1
                $to = max([$matches[1], $matches[2]]);
39
40 1
                return implode("\n", array_slice($lines, $from - 1, $to - $from + 1));
41
42
            default:
43 2
                return $contents;
44
        }
45
    }
46
}
47