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 arrays for equality.
16 class ArrayComparator extends Comparator
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_array($expected) && is_array($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())
50 $expString = $actString = "Array (\n";
53 foreach ($expected as $key => $value) {
54 unset($remaining[$key]);
56 if (!array_key_exists($key, $actual)) {
57 $expString .= sprintf(
59 $this->exporter->export($key),
60 $this->exporter->shortenedExport($value)
69 $comparator = $this->factory->getComparatorFor($value, $actual[$key]);
70 $comparator->assertEquals($value, $actual[$key], $delta, $canonicalize, $ignoreCase, $processed);
72 $expString .= sprintf(
74 $this->exporter->export($key),
75 $this->exporter->shortenedExport($value)
77 $actString .= sprintf(
79 $this->exporter->export($key),
80 $this->exporter->shortenedExport($actual[$key])
82 } catch (ComparisonFailure $e) {
83 $expString .= sprintf(
85 $this->exporter->export($key),
86 $e->getExpectedAsString()
87 ? $this->indent($e->getExpectedAsString())
88 : $this->exporter->shortenedExport($e->getExpected())
91 $actString .= sprintf(
93 $this->exporter->export($key),
94 $e->getActualAsString()
95 ? $this->indent($e->getActualAsString())
96 : $this->exporter->shortenedExport($e->getActual())
103 foreach ($remaining as $key => $value) {
104 $actString .= sprintf(
106 $this->exporter->export($key),
107 $this->exporter->shortenedExport($value)
117 throw new ComparisonFailure(
123 'Failed asserting that two arrays are equal.'
128 protected function indent($lines)
130 return trim(str_replace("\n", "\n ", $lines));