Skip to content

Add PhpUnit rich diff for JSON string comparison #159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
43 changes: 41 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,38 @@ private function createMatcher() : Matcher

return $factory->createMatcher();
}

/**
* {@inheritdoc}
*/
protected function fail($other, $description, ComparisonFailure $comparisonFailure = null): void
{
if (null === $comparisonFailure
&& \is_string($other)
&& \class_exists(Json::class)
) {
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);
}
}