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/** 12 * Asserts whether or not two JSON objects are equal. 13 */ 14class PHPUnit_Framework_Constraint_JsonMatches extends PHPUnit_Framework_Constraint 15{ 16 /** 17 * @var string 18 */ 19 protected $value; 20 21 /** 22 * Creates a new constraint. 23 * 24 * @param string $value 25 */ 26 public function __construct($value) 27 { 28 parent::__construct(); 29 $this->value = $value; 30 } 31 32 /** 33 * Evaluates the constraint for parameter $other. Returns true if the 34 * constraint is met, false otherwise. 35 * 36 * This method can be overridden to implement the evaluation algorithm. 37 * 38 * @param mixed $other Value or object to evaluate. 39 * 40 * @return bool 41 */ 42 protected function matches($other) 43 { 44 $decodedOther = json_decode($other); 45 if (json_last_error()) { 46 return false; 47 } 48 49 $decodedValue = json_decode($this->value); 50 if (json_last_error()) { 51 return false; 52 } 53 54 return $decodedOther == $decodedValue; 55 } 56 57 /** 58 * Returns a string representation of the object. 59 * 60 * @return string 61 */ 62 public function toString() 63 { 64 return sprintf( 65 'matches JSON string "%s"', 66 $this->value 67 ); 68 } 69} 70