Dumper.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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\Console\Helper;
  11. use Symfony\Component\Console\Output\OutputInterface;
  12. use Symfony\Component\VarDumper\Cloner\ClonerInterface;
  13. use Symfony\Component\VarDumper\Cloner\VarCloner;
  14. use Symfony\Component\VarDumper\Dumper\CliDumper;
  15. /**
  16. * @author Roland Franssen <franssen.roland@gmail.com>
  17. */
  18. final class Dumper
  19. {
  20. private OutputInterface $output;
  21. private ?CliDumper $dumper;
  22. private ?ClonerInterface $cloner;
  23. private \Closure $handler;
  24. public function __construct(OutputInterface $output, ?CliDumper $dumper = null, ?ClonerInterface $cloner = null)
  25. {
  26. $this->output = $output;
  27. $this->dumper = $dumper;
  28. $this->cloner = $cloner;
  29. if (class_exists(CliDumper::class)) {
  30. $this->handler = function ($var): string {
  31. $dumper = $this->dumper ??= new CliDumper(null, null, CliDumper::DUMP_LIGHT_ARRAY | CliDumper::DUMP_COMMA_SEPARATOR);
  32. $dumper->setColors($this->output->isDecorated());
  33. return rtrim($dumper->dump(($this->cloner ??= new VarCloner())->cloneVar($var)->withRefHandles(false), true));
  34. };
  35. } else {
  36. $this->handler = fn ($var): string => match (true) {
  37. null === $var => 'null',
  38. true === $var => 'true',
  39. false === $var => 'false',
  40. \is_string($var) => '"'.$var.'"',
  41. default => rtrim(print_r($var, true)),
  42. };
  43. }
  44. }
  45. public function __invoke(mixed $var): string
  46. {
  47. return ($this->handler)($var);
  48. }
  49. }