VarDumperTestTrait.php 2.5 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 $varDumperConfig = [
  22. 'casters' => [],
  23. 'flags' => null,
  24. ];
  25. protected function setUpVarDumper(array $casters, int $flags = null): void
  26. {
  27. $this->varDumperConfig['casters'] = $casters;
  28. $this->varDumperConfig['flags'] = $flags;
  29. }
  30. /**
  31. * @after
  32. */
  33. protected function tearDownVarDumper(): void
  34. {
  35. $this->varDumperConfig['casters'] = [];
  36. $this->varDumperConfig['flags'] = null;
  37. }
  38. public function assertDumpEquals($expected, $data, $filter = 0, $message = '')
  39. {
  40. $this->assertSame($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message);
  41. }
  42. public function assertDumpMatchesFormat($expected, $data, $filter = 0, $message = '')
  43. {
  44. $this->assertStringMatchesFormat($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message);
  45. }
  46. /**
  47. * @return string|null
  48. */
  49. protected function getDump($data, $key = null, $filter = 0)
  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($expected, int $filter): string
  68. {
  69. if (!\is_string($expected)) {
  70. $expected = $this->getDump($expected, null, $filter);
  71. }
  72. return rtrim($expected);
  73. }
  74. }