Passed
Push — main ( 36bb88...fbfcc4 )
by Alexandra
03:15
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 4
        $startKey = $flip['tests'];
28 4
        $endKey = count($pathParts) - 1;
29
30 4
        $approvalFilePath = '';
31
32 4
        for ($i = $startKey; $i <= $endKey; $i++) {
33 4
            $approvalFilePath .= $pathParts[$i] . '/';
34
        }
35
36 4
        return $approvalFilePath . self::APPROVAL_DIR;
37
    }
38
39 4
    public function getApprovalFileName(string $pathToTestFile, string $testMethodName): string
40
    {
41 4
        return pathinfo($pathToTestFile)['filename'] . '.' . $testMethodName;
42
    }
43
44 2
    public function getTestPathAndMethodName(): array
45
    {
46 2
        $traces = debug_backtrace(1);
47
48 2
        foreach ($traces as $key => $trace) {
49 2
            if ($this->endsWith($trace['file'], 'Test.php', true)) {
50 2
                $pathToTestFile = $trace['file'];
51 2
                $testMethodName = $traces[$key + 1]['function'];
52
53 2
                return [$pathToTestFile, $testMethodName];
54
            }
55
        }
56
57
        throw new Exception(sprintf(
58
            'Failed to identify the testing file or method you are using.'
59
        ));
60
    }
61
62 2
    private function endsWith(string $haystack, string $needle, $ignoreCase = false): bool
63
    {
64 2
        if ($ignoreCase) {
65 2
            $haystack = mb_strtolower($haystack);
66 2
            $needle = mb_strtolower($needle);
67
        }
68
69 2
        return mb_substr($haystack, mb_strlen($haystack) - mb_strlen($needle)) === $needle;
70
    }
71
}
72