Dumper.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 $output;
  21. private $dumper;
  22. private $cloner;
  23. private $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 ?? $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 ?? $this->cloner = new VarCloner())->cloneVar($var)->withRefHandles(false), true));
  34. };
  35. } else {
  36. $this->handler = function ($var): string {
  37. switch (true) {
  38. case null === $var:
  39. return 'null';
  40. case true === $var:
  41. return 'true';
  42. case false === $var:
  43. return 'false';
  44. case \is_string($var):
  45. return '"'.$var.'"';
  46. default:
  47. return rtrim(print_r($var, true));
  48. }
  49. };
  50. }
  51. }
  52. public function __invoke($var): string
  53. {
  54. return ($this->handler)($var);
  55. }
  56. }