-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathVCRTestHandler.php
74 lines (57 loc) · 1.76 KB
/
VCRTestHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
declare(strict_types=1);
namespace VCR\PHPUnit\TestListener;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use VCR\VCR;
final class VCRTestHandler
{
private function __construct() {}
public static function onStart(string $class, string $method): void
{
if (!method_exists($class, $method)) {
return;
}
$reflection = new \ReflectionMethod($class, $method);
$docBlock = $reflection->getDocComment();
// Use regex to parse the doc_block for a specific annotation
$parsed = self::parseDocBlock($docBlock, '@vcr');
$cassetteName = array_pop($parsed);
if (empty($cassetteName)) {
return;
}
// If the cassette name ends in .json, then use the JSON storage format
if (substr($cassetteName, -5) === '.json') {
VCR::configure()->setStorage('json');
}
VCR::turnOn();
VCR::insertCassette($cassetteName);
}
public static function onEnd(): void
{
VCR::turnOff();
}
private static function parseDocBlock($docBlock, $tag): array
{
$matches = [];
if (empty($docBlock)) {
return $matches;
}
$regex = "/{$tag} (.*)(\\r\\n|\\r|\\n)/U";
preg_match_all($regex, $docBlock, $matches);
if (empty($matches[1])) {
return array();
}
// Removed extra index
$matches = $matches[1];
// Trim the results, array item by array item
foreach ($matches as $ix => $match) {
$matches[$ix] = trim($match);
}
return $matches;
}
}