Skip to content

Commit

Permalink
Simpler seeJsonContains logic.
Browse files Browse the repository at this point in the history
Hat tip to Taylor Otwell.
  • Loading branch information
JeffreyWay committed May 6, 2015
1 parent 27037a3 commit 4f4eed7
Showing 1 changed file with 19 additions and 61 deletions.
80 changes: 19 additions & 61 deletions src/Extensions/Traits/ApiRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,80 +167,38 @@ protected function seeJsonEquals($expected)
*/
protected function seeJsonContains($expected)
{
$response = $this->response();
$json = json_decode($response, true);

// If we have a collection of results, we'll sift through each array
// in the collection, and check to see if there's a match.
$response = json_decode($this->response(), true);

if (! isset($json[0])) {
$json = [$json];
}
$this->sortJson($expected);
$this->sortJson($response);

$containsFragment = array_reduce($json, function ($carry, $array) use ($expected) {
if ($carry) {
return $carry;
foreach ($expected as $key => $value) {
if ( ! str_contains(json_encode($response), trim(json_encode([$key => $value]), '{}'))) {
$this->fail(sprintf(
"Dang! Expected %s to exist in %s, but nope. Ideas?",
json_encode($expected), json_encode($response)
));
}

return $this->jsonHasFragment($expected, $array);
});

$this->assertTrue($containsFragment, sprintf(
"Dang! Expected %s to exist in %s, but nope. Ideas?",
json_encode($expected), $response
));

return $this;
}

/**
* Determine if the given fragment is contained with a decoded set of JSON.
*
* @param array $fragment
* @param array $json
* @return boolean
*/
protected function jsonHasFragment(array $fragment, $json)
{
$hasMatch = @array_intersect($json, $fragment) == $fragment;

if (! $hasMatch) {
$hasMatch = $this->searchJsonFor($fragment, $json);
}

return $hasMatch;
}

/**
* Search through an associative array for a given fragment.
* Sort a JSON response, for easy assertions and comparisons.
*
* @param array $fragment
* @param array $json
* @return boolean
* @param array &$array
* @return array
*/
protected function searchJsonFor($fragment, $json)
protected function sortJson(&$array)
{
foreach ($json as $key => $value) {

// We'll do a handful of checks to see if the user's
// given array matches the JSON from the response.

if (is_array($value)) {
if ($this->searchJsonFor($fragment, $value)) {
return true;
}

if (@array_intersect($value, $fragment) == $fragment) {
return true;
}
}

if ($fragment == [$key => $value]) {
return true;
foreach ($array as &$value) {
if (is_array($value) && isset($value[0])) {
sort($value);
} elseif (is_array($value)) {
$this->sortJson($value);
}
}

return false;
return ksort($array);
}

/**
Expand Down

0 comments on commit 4f4eed7

Please sign in to comment.