JsonContains.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Codeception\PHPUnit\Constraint;
  3. use SebastianBergmann\Comparator\ComparisonFailure;
  4. use SebastianBergmann\Comparator\ArrayComparator;
  5. use SebastianBergmann\Comparator\Factory;
  6. use Codeception\Util\JsonArray;
  7. class JsonContains extends \PHPUnit\Framework\Constraint\Constraint
  8. {
  9. /**
  10. * @var
  11. */
  12. protected $expected;
  13. public function __construct(array $expected)
  14. {
  15. parent::__construct();
  16. $this->expected = $expected;
  17. }
  18. /**
  19. * Evaluates the constraint for parameter $other. Returns true if the
  20. * constraint is met, false otherwise.
  21. *
  22. * @param mixed $other Value or object to evaluate.
  23. *
  24. * @return bool
  25. */
  26. protected function matches($other)
  27. {
  28. $jsonResponseArray = new JsonArray($other);
  29. if (!is_array($jsonResponseArray->toArray())) {
  30. throw new \PHPUnit\Framework\AssertionFailedError('JSON response is not an array: ' . $other);
  31. }
  32. if ($jsonResponseArray->containsArray($this->expected)) {
  33. return true;
  34. }
  35. $comparator = new ArrayComparator();
  36. $comparator->setFactory(new Factory);
  37. try {
  38. $comparator->assertEquals($this->expected, $jsonResponseArray->toArray());
  39. } catch (ComparisonFailure $failure) {
  40. throw new \PHPUnit\Framework\ExpectationFailedException(
  41. "Response JSON does not contain the provided JSON\n",
  42. $failure
  43. );
  44. }
  45. }
  46. /**
  47. * Returns a string representation of the constraint.
  48. *
  49. * @return string
  50. */
  51. public function toString()
  52. {
  53. //unused
  54. return '';
  55. }
  56. protected function failureDescription($other)
  57. {
  58. //unused
  59. return '';
  60. }
  61. }