/vendor/phpunit/phpunit/src/Framework/Constraint/IsJson.php

https://bitbucket.org/alan_cordova/api-sb-map · PHP · 75 lines · 34 code · 7 blank · 34 comment · 3 complexity · f6b0e10a1b4632b4a5f9d945354b4685 MD5 · raw file

  1. <?php
  2. /*
  3. * This file is part of PHPUnit.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Constraint that asserts that a string is valid JSON.
  12. */
  13. class PHPUnit_Framework_Constraint_IsJson extends PHPUnit_Framework_Constraint
  14. {
  15. /**
  16. * Evaluates the constraint for parameter $other. Returns true if the
  17. * constraint is met, false otherwise.
  18. *
  19. * @param mixed $other Value or object to evaluate.
  20. *
  21. * @return bool
  22. */
  23. protected function matches($other)
  24. {
  25. if ($other === '') {
  26. return false;
  27. }
  28. json_decode($other);
  29. if (json_last_error()) {
  30. return false;
  31. }
  32. return true;
  33. }
  34. /**
  35. * Returns the description of the failure
  36. *
  37. * The beginning of failure messages is "Failed asserting that" in most
  38. * cases. This method should return the second part of that sentence.
  39. *
  40. * @param mixed $other Evaluated value or object.
  41. *
  42. * @return string
  43. */
  44. protected function failureDescription($other)
  45. {
  46. if ($other === '') {
  47. return 'an empty string is valid JSON';
  48. }
  49. json_decode($other);
  50. $error = PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider::determineJsonError(
  51. json_last_error()
  52. );
  53. return sprintf(
  54. '%s is valid JSON (%s)',
  55. $this->exporter->shortenedExport($other),
  56. $error
  57. );
  58. }
  59. /**
  60. * Returns a string representation of the constraint.
  61. *
  62. * @return string
  63. */
  64. public function toString()
  65. {
  66. return 'is valid JSON';
  67. }
  68. }