3 * This file is part of the Comparator package.
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace SebastianBergmann\Comparator;
14 * Compares objects for equality.
16 class ObjectComparator extends ArrayComparator
19 * Returns whether the comparator can compare two values.
21 * @param mixed $expected The first value to compare
22 * @param mixed $actual The second value to compare
25 public function accepts($expected, $actual)
27 return is_object($expected) && is_object($actual);
31 * Asserts that two values are equal.
33 * @param mixed $expected First value to compare
34 * @param mixed $actual Second value to compare
35 * @param float $delta Allowed numerical distance between two values to consider them equal
36 * @param bool $canonicalize Arrays are sorted before comparison when set to true
37 * @param bool $ignoreCase Case is ignored when set to true
38 * @param array $processed List of already processed elements (used to prevent infinite recursion)
40 * @throws ComparisonFailure
42 public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false, array &$processed = array())
44 if (get_class($actual) !== get_class($expected)) {
45 throw new ComparisonFailure(
48 $this->exporter->export($expected),
49 $this->exporter->export($actual),
52 '%s is not instance of expected class "%s".',
53 $this->exporter->export($actual),
59 // don't compare twice to allow for cyclic dependencies
60 if (in_array(array($actual, $expected), $processed, true) ||
61 in_array(array($expected, $actual), $processed, true)) {
65 $processed[] = array($actual, $expected);
67 // don't compare objects if they are identical
68 // this helps to avoid the error "maximum function nesting level reached"
69 // CAUTION: this conditional clause is not tested
70 if ($actual !== $expected) {
73 $this->toArray($expected),
74 $this->toArray($actual),
80 } catch (ComparisonFailure $e) {
81 throw new ComparisonFailure(
84 // replace "Array" with "MyClass object"
85 substr_replace($e->getExpectedAsString(), get_class($expected) . ' Object', 0, 5),
86 substr_replace($e->getActualAsString(), get_class($actual) . ' Object', 0, 5),
88 'Failed asserting that two objects are equal.'
95 * Converts an object to an array containing all of its private, protected
96 * and public properties.
98 * @param object $object
101 protected function toArray($object)
103 return $this->exporter->toArray($object);