You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.5 KiB

3 years ago
  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, int $filter = 0, string $message = '')
  39. {
  40. $this->assertSame($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message);
  41. }
  42. public function assertDumpMatchesFormat($expected, $data, int $filter = 0, string $message = '')
  43. {
  44. $this->assertStringMatchesFormat($this->prepareExpectation($expected, $filter), $this->getDump($data, null, $filter), $message);
  45. }
  46. protected function getDump($data, $key = null, int $filter = 0): ?string
  47. {
  48. if (null === $flags = $this->varDumperConfig['flags']) {
  49. $flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0;
  50. $flags |= getenv('DUMP_STRING_LENGTH') ? CliDumper::DUMP_STRING_LENGTH : 0;
  51. $flags |= getenv('DUMP_COMMA_SEPARATOR') ? CliDumper::DUMP_COMMA_SEPARATOR : 0;
  52. }
  53. $cloner = new VarCloner();
  54. $cloner->addCasters($this->varDumperConfig['casters']);
  55. $cloner->setMaxItems(-1);
  56. $dumper = new CliDumper(null, null, $flags);
  57. $dumper->setColors(false);
  58. $data = $cloner->cloneVar($data, $filter)->withRefHandles(false);
  59. if (null !== $key && null === $data = $data->seek($key)) {
  60. return null;
  61. }
  62. return rtrim($dumper->dump($data, true));
  63. }
  64. private function prepareExpectation($expected, int $filter): string
  65. {
  66. if (!\is_string($expected)) {
  67. $expected = $this->getDump($expected, null, $filter);
  68. }
  69. return rtrim($expected);
  70. }
  71. }