1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Http\Client\Plugin\Vcr\Recorder; |
6
|
|
|
|
7
|
|
|
use GuzzleHttp\Psr7; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Log\LoggerAwareInterface; |
10
|
|
|
use Psr\Log\LoggerAwareTrait; |
11
|
|
|
use Symfony\Component\Filesystem\Exception\IOException; |
12
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Stores responses using the `guzzlehttp/psr7` library to serialize and deserialize the response. |
16
|
|
|
* Target directory should be part of your VCS. |
17
|
|
|
* |
18
|
|
|
* @author Gary PEGEOT <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
final class FilesystemRecorder implements RecorderInterface, PlayerInterface, LoggerAwareInterface |
21
|
|
|
{ |
22
|
|
|
use LoggerAwareTrait; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
private $directory; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var Filesystem |
31
|
|
|
*/ |
32
|
|
|
private $filesystem; |
33
|
|
|
|
34
|
2 |
|
public function __construct(string $directory, ?Filesystem $filesystem = null) |
35
|
|
|
{ |
36
|
2 |
|
$this->filesystem = $filesystem ?? new Filesystem(); |
37
|
|
|
|
38
|
2 |
|
if (!$this->filesystem->exists($directory)) { |
39
|
|
|
try { |
40
|
|
|
$this->filesystem->mkdir($directory); |
41
|
|
|
} catch (IOException $e) { |
42
|
|
|
throw new \InvalidArgumentException("Unable to create directory \"$directory\"/: {$e->getMessage()}", $e->getCode(), $e); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
2 |
|
$this->directory = realpath($directory).\DIRECTORY_SEPARATOR; |
47
|
2 |
|
} |
48
|
|
|
|
49
|
2 |
|
public function replay(string $name): ?ResponseInterface |
50
|
|
|
{ |
51
|
2 |
|
$filename = "{$this->directory}$name.txt"; |
52
|
2 |
|
$context = compact('filename'); |
53
|
|
|
|
54
|
2 |
|
if (!$this->filesystem->exists($filename)) { |
55
|
1 |
|
$this->log('Unable to replay {filename}', $context); |
56
|
|
|
|
57
|
1 |
|
return null; |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
$this->log('Response replayed from {filename}', $context); |
61
|
|
|
|
62
|
1 |
|
return Psr7\parse_response(file_get_contents($filename)); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
public function record(string $name, ResponseInterface $response): void |
66
|
|
|
{ |
67
|
1 |
|
$filename = "{$this->directory}$name.txt"; |
68
|
1 |
|
$context = compact('name', 'filename'); |
69
|
|
|
|
70
|
1 |
|
$this->filesystem->dumpFile($filename, Psr7\str($response)); |
71
|
|
|
|
72
|
1 |
|
$this->log('Response for {name} stored into {filename}', $context); |
73
|
1 |
|
} |
74
|
|
|
|
75
|
2 |
|
private function log(string $message, array $context = []): void |
76
|
|
|
{ |
77
|
2 |
|
if ($this->logger) { |
78
|
1 |
|
$this->logger->debug("[VCR-PLUGIN][FilesystemRecorder] $message", $context); |
79
|
|
|
} |
80
|
2 |
|
} |
81
|
|
|
} |
82
|
|
|
|