diff --git a/src/Recorder/FilesystemRecorder.php b/src/Recorder/FilesystemRecorder.php index 1105c1c..0860de4 100644 --- a/src/Recorder/FilesystemRecorder.php +++ b/src/Recorder/FilesystemRecorder.php @@ -31,7 +31,12 @@ final class FilesystemRecorder implements RecorderInterface, PlayerInterface, Lo */ private $filesystem; - public function __construct(string $directory, ?Filesystem $filesystem = null) + /** + * @var array + */ + private $filters; + + public function __construct(string $directory, ?Filesystem $filesystem = null, array $filters = []) { $this->filesystem = $filesystem ?? new Filesystem(); @@ -44,6 +49,7 @@ public function __construct(string $directory, ?Filesystem $filesystem = null) } $this->directory = realpath($directory).\DIRECTORY_SEPARATOR; + $this->filters = $filters; } public function replay(string $name): ?ResponseInterface @@ -67,7 +73,8 @@ public function record(string $name, ResponseInterface $response): void $filename = "{$this->directory}$name.txt"; $context = compact('name', 'filename'); - $this->filesystem->dumpFile($filename, Psr7\str($response)); + $content = preg_replace(array_keys($this->filters), array_values($this->filters), Psr7\str($response)); + $this->filesystem->dumpFile($filename, $content); $this->log('Response for {name} stored into {filename}', $context); } diff --git a/tests/Recorder/FilesystemRecorderTest.php b/tests/Recorder/FilesystemRecorderTest.php index f8032e3..aab6302 100644 --- a/tests/Recorder/FilesystemRecorderTest.php +++ b/tests/Recorder/FilesystemRecorderTest.php @@ -93,4 +93,28 @@ protected function tearDown(): void $this->filesystem->remove($this->workspace); umask($this->umask); } + + public function testRecordWithFilter(): void + { + $original = new Response(200, ['X-Foo' => 'Bar', 'X-Bar' => 'private-token-065a1bb33f000032ab'], 'The content'); + + $recorder = new FilesystemRecorder($this->workspace, $this->filesystem, [ + '!private-token-[0-9a-z]+!' => 'private-token-xxxx', + '!The content!' => 'The big content', + ]); + $recorder->record('my_awesome_response', $original); + + $this->assertFileExists(sprintf('%s%smy_awesome_response.txt', $this->workspace, \DIRECTORY_SEPARATOR)); + + $replayed = (new FilesystemRecorder($this->workspace))->replay('my_awesome_response'); + + $this->assertNotNull($replayed, 'Response should not be null'); + + $this->assertSame($original->getStatusCode(), $replayed->getStatusCode()); + $expectedHeaders = $original->getHeaders(); + $expectedHeaders['X-Bar'] = ['private-token-xxxx']; + $this->assertSame($expectedHeaders, $replayed->getHeaders()); + $this->assertSame('The big content', (string) $replayed->getBody()); + } + }