Skip to content

Commit

Permalink
add redactedProperties
Browse files Browse the repository at this point in the history
  • Loading branch information
Gyvastis committed Sep 4, 2021
1 parent c0febc9 commit 974723b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
25 changes: 21 additions & 4 deletions src/SnapshotDriver/SnapshotJsonObjectDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@

class SnapshotJsonObjectDriver implements Driver
{
public function __construct(private array $ignoredProperties = [])
public function __construct(
private array $ignoredProperties = [],
private array $redactedProperties = []
)
{
}

Expand All @@ -39,7 +42,8 @@ public function serialize($data): string
AbstractNormalizer::IGNORED_ATTRIBUTES => $this->ignoredProperties,
]);

$this->unsetIgnoredKeys($normalizedData, $this->ignoredProperties);
$this->ignoreKeys($normalizedData, $this->ignoredProperties);
$this->redactKeys($normalizedData, $this->redactedProperties);

return $serializer->serialize($normalizedData, JsonEncoder::FORMAT, [
'json_encode_options' => JSON_PRETTY_PRINT
Expand All @@ -56,14 +60,27 @@ public function match($expected, $actual)
Assert::assertEquals($expected, $this->serialize($actual));
}

private function unsetIgnoredKeys(array &$values, array $ignoredKeys): void
private function ignoreKeys(array &$values, array $ignoredKeys): void
{
foreach($values as $key => $value) {
if (in_array($key, $ignoredKeys)) {
unset($values[$key]);
}
else if(is_array($value)) {
$this->unsetIgnoredKeys($value, $ignoredKeys);
$this->ignoreKeys($value, $ignoredKeys);
$values[$key] = $value;
}
}
}

private function redactKeys(array &$values, array $redactedKeys): void
{
foreach($values as $key => $value) {
if (in_array($key, $redactedKeys)) {
$values[$key] = 'REDACTED';
}
else if(is_array($value)) {
$this->redactKeys($value, $redactedKeys);
$values[$key] = $value;
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Traits/AssertMatchesJsonObjectSnapshotTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ trait AssertMatchesJsonObjectSnapshotTrait
{
use MatchesSnapshots;

public function assertMatchesJsonObjectSnapshot($actual, array $ignoredProperties = []): void
public function assertMatchesJsonObjectSnapshot($actual, array $ignoredProperties = [], array $redactedProperties = []): void
{
$this->assertMatchesSnapshot($actual, new SnapshotJsonObjectDriver($ignoredProperties));
$this->assertMatchesSnapshot($actual, new SnapshotJsonObjectDriver($ignoredProperties, $redactedProperties));
}
}

0 comments on commit 974723b

Please sign in to comment.