Passed
Push — main ( 24b6e6...7c0850 )
by Alexandra
02:38
created

FilePathResolver::getTestPathAndMethodName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0987

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 0
dl 0
loc 15
ccs 7
cts 9
cp 0.7778
crap 3.0987
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AHJ\ApprovalTests;
6
7
use Exception;
8
9
final class FilePathResolver
10
{
11
    public const APPROVAL_DIR = 'approval';
12
13 2
    public function resolve(): FilePathResolverResult
14
    {
15 2
        [$pathToTestFile, $testMethodName] = $this->getTestPathAndMethodName();
16
17 2
        $approvalFilePath = $this->getApprovalFilePath($pathToTestFile);
18 2
        $approvalFileName = $this->getApprovalFileName($pathToTestFile, $testMethodName);
19
20 2
        return new FilePathResolverResult($approvalFilePath, $approvalFileName);
21
    }
22
23 4
    public function getApprovalFilePath(string $pathToTestFile): string
24
    {
25 4
        $pathParts = explode('/', pathinfo($pathToTestFile)['dirname']);
26 4
        $flip = array_flip($pathParts);
27
        // TODO: guard from undefined index
28 4
        $startKey = $flip['tests'];
29 4
        $endKey = count($pathParts) - 1;
30
31 4
        $approvalFilePath = '';
32
33 4
        for ($i = $startKey; $i <= $endKey; $i++) {
34 4
            $approvalFilePath .= $pathParts[$i] . '/';
35
        }
36
37 4
        return $approvalFilePath . self::APPROVAL_DIR;
38
    }
39
40 4
    public function getApprovalFileName(string $pathToTestFile, string $testMethodName): string
41
    {
42 4
        return pathinfo($pathToTestFile)['filename'] . '.' . $testMethodName;
43
    }
44
45 2
    public function getTestPathAndMethodName(): array
46
    {
47 2
        $traces = debug_backtrace(1);
48
49 2
        foreach ($traces as $key => $trace) {
50 2
            if ($this->endsWith($trace['file'], 'Test.php', true)) {
51 2
                $pathToTestFile = $trace['file'];
52 2
                $testMethodName = $traces[$key + 1]['function'];
53
54 2
                return [$pathToTestFile, $testMethodName];
55
            }
56
        }
57
58
        throw new Exception(sprintf(
59
            'Failed to identify the testing file or method you are using.'
60
        ));
61
    }
62
63 2
    private function endsWith(string $haystack, string $needle, $ignoreCase = false): bool
64
    {
65 2
        if ($ignoreCase) {
66 2
            $haystack = mb_strtolower($haystack);
67 2
            $needle = mb_strtolower($needle);
68
        }
69
70 2
        return mb_substr($haystack, mb_strlen($haystack) - mb_strlen($needle)) === $needle;
71
    }
72
}
73