Skip to content

Commit

Permalink
Add PhpUnit rich diff for JSON string comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
B-Galati committed Aug 1, 2019
1 parent 5030f99 commit 30bd512
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"require": {
"php": ">=7.0.0",
"ext-filter": "*",
"ext-json": "*",
"coduo/php-to-string": "^2",
"symfony/property-access": "^2.3|^3.0|^4.0",
"symfony/expression-language": "^2.3|^3.0|^4.0",
Expand Down
40 changes: 38 additions & 2 deletions src/PHPUnit/PHPMatcherConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
use Coduo\PHPMatcher\Factory\SimpleFactory;
use Coduo\PHPMatcher\Matcher;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Util\Json;
use SebastianBergmann\Comparator\ComparisonFailure;

final class PHPMatcherConstraint extends Constraint
{
private $pattern;

private $matcher;
private $lastValue;

public function __construct(string $pattern)
{
Expand All @@ -24,6 +26,9 @@ public function __construct(string $pattern)
$this->matcher = $this->createMatcher();
}

/**
* {@inheritdoc}
*/
public function toString() : string
{
return 'matches the pattern';
Expand All @@ -36,7 +41,7 @@ protected function additionalFailureDescription($other) : string

protected function matches($value) : bool
{
return $this->matcher->match($value, $this->pattern);
return $this->matcher->match($this->lastValue = $value, $this->pattern);
}

private function createMatcher() : Matcher
Expand All @@ -45,4 +50,35 @@ private function createMatcher() : Matcher

return $factory->createMatcher();
}

/**
* {@inheritdoc}
*/
protected function fail($other, $description, ComparisonFailure $comparisonFailure = null): void
{
if (null === $comparisonFailure && is_string($other)) {
list($error) = Json::canonicalize($other);

if ($error) {
parent::fail($other, $description);
}

list($error) = Json::canonicalize($this->pattern);

if ($error) {
parent::fail($other, $description);
}

$comparisonFailure = new ComparisonFailure(
\json_decode($this->pattern),
\json_decode($other),
Json::prettify($this->pattern),
Json::prettify($other),
false,
'Failed asserting that the pattern matches the given value.'
);
}

parent::fail($other, $description, $comparisonFailure);
}
}

0 comments on commit 30bd512

Please sign in to comment.