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
|
|
|
|