ObjectComparator.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of sebastian/comparator.
  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. namespace SebastianBergmann\Comparator;
  11. use function assert;
  12. use function in_array;
  13. use function is_object;
  14. use function sprintf;
  15. use function substr_replace;
  16. use SebastianBergmann\Exporter\Exporter;
  17. class ObjectComparator extends ArrayComparator
  18. {
  19. public function accepts(mixed $expected, mixed $actual): bool
  20. {
  21. return is_object($expected) && is_object($actual);
  22. }
  23. /**
  24. * @throws ComparisonFailure
  25. */
  26. public function assertEquals(mixed $expected, mixed $actual, float $delta = 0.0, bool $canonicalize = false, bool $ignoreCase = false, array &$processed = []): void
  27. {
  28. assert(is_object($expected));
  29. assert(is_object($actual));
  30. if ($actual::class !== $expected::class) {
  31. $exporter = new Exporter;
  32. throw new ComparisonFailure(
  33. $expected,
  34. $actual,
  35. $exporter->export($expected),
  36. $exporter->export($actual),
  37. sprintf(
  38. '%s is not instance of expected class "%s".',
  39. $exporter->export($actual),
  40. $expected::class
  41. )
  42. );
  43. }
  44. // don't compare twice to allow for cyclic dependencies
  45. if (in_array([$actual, $expected], $processed, true) ||
  46. in_array([$expected, $actual], $processed, true)) {
  47. return;
  48. }
  49. $processed[] = [$actual, $expected];
  50. // don't compare objects if they are identical
  51. // this helps to avoid the error "maximum function nesting level reached"
  52. // CAUTION: this conditional clause is not tested
  53. if ($actual !== $expected) {
  54. try {
  55. parent::assertEquals(
  56. $this->toArray($expected),
  57. $this->toArray($actual),
  58. $delta,
  59. $canonicalize,
  60. $ignoreCase,
  61. $processed
  62. );
  63. } catch (ComparisonFailure $e) {
  64. throw new ComparisonFailure(
  65. $expected,
  66. $actual,
  67. // replace "Array" with "MyClass object"
  68. substr_replace($e->getExpectedAsString(), $expected::class . ' Object', 0, 5),
  69. substr_replace($e->getActualAsString(), $actual::class . ' Object', 0, 5),
  70. 'Failed asserting that two objects are equal.'
  71. );
  72. }
  73. }
  74. }
  75. protected function toArray(object $object): array
  76. {
  77. return (new Exporter)->toArray($object);
  78. }
  79. }