VarDumperTestTrait.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\VarDumper\Test;
  11. use Symfony\Component\VarDumper\Cloner\VarCloner;
  12. use Symfony\Component\VarDumper\Dumper\CliDumper;
  13. /**
  14. * @author Nicolas Grekas <p@tchwork.com>
  15. */
  16. trait VarDumperTestTrait
  17. {
  18. /**
  19. * @internal
  20. */
  21. private array $varDumperConfig = [
  22. 'casters' => [],
  23. 'flags' => null,
  24. ];
  25. /**
  26. * @param array<string, callable> $casters
  27. */
  28. protected function setUpVarDumper(array $casters, ?int $flags = null): void
  29. {
  30. $this->varDumperConfig['casters'] = $casters;
  31. $this->varDumperConfig['flags'] = $flags;
  32. }
  33. /**
  34. * @after
  35. */
  36. protected function tearDownVarDumper(): void
  37. {
  38. $this->varDumperConfig['casters'] = [];
  39. $this->varDumperConfig['flags'] = null;
  40. }
  41. public function assertDumpEquals(mixed $expected, mixed $data, int $filter = 0, string $message = '')
  42. {
  43. $this->assertSame($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message);
  44. }
  45. public function assertDumpMatchesFormat(mixed $expected, mixed $data, int $filter = 0, string $message = '')
  46. {
  47. $this->assertStringMatchesFormat($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message);
  48. }
  49. protected function getDump(mixed $data, string|int|null $key = null, int $filter = 0): ?string
  50. {
  51. if (null === $flags = $this->varDumperConfig['flags']) {
  52. $flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0;
  53. $flags |= getenv('DUMP_STRING_LENGTH') ? CliDumper::DUMP_STRING_LENGTH : 0;
  54. $flags |= getenv('DUMP_COMMA_SEPARATOR') ? CliDumper::DUMP_COMMA_SEPARATOR : 0;
  55. }
  56. $cloner = new VarCloner();
  57. $cloner->addCasters($this->varDumperConfig['casters']);
  58. $cloner->setMaxItems(-1);
  59. $dumper = new CliDumper(null, null, $flags);
  60. $dumper->setColors(false);
  61. $data = $cloner->cloneVar($data, $filter)->withRefHandles(false);
  62. if (null !== $key && null === $data = $data->seek($key)) {
  63. return null;
  64. }
  65. return rtrim($dumper->dump($data, true));
  66. }
  67. private function prepareExpectation(mixed $expected, int $filter): string
  68. {
  69. if (!\is_string($expected)) {
  70. $expected = $this->getDump($expected, null, $filter);
  71. }
  72. return rtrim($expected);
  73. }
  74. }