Dumper.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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\Yaml;
  11. /**
  12. * Dumper dumps PHP variables to YAML strings.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Dumper
  17. {
  18. /**
  19. * The amount of spaces to use for indentation of nested nodes.
  20. *
  21. * @var int
  22. */
  23. protected $indentation = 4;
  24. /**
  25. * Sets the indentation.
  26. *
  27. * @param int $num The amount of spaces to use for indentation of nested nodes.
  28. */
  29. public function setIndentation($num)
  30. {
  31. $this->indentation = (int) $num;
  32. }
  33. /**
  34. * Dumps a PHP value to YAML.
  35. *
  36. * @param mixed $input The PHP value
  37. * @param int $inline The level where you switch to inline YAML
  38. * @param int $indent The level of indentation (used internally)
  39. * @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  40. * @param bool $objectSupport true if object support is enabled, false otherwise
  41. *
  42. * @return string The YAML representation of the PHP value
  43. */
  44. public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false)
  45. {
  46. $output = '';
  47. $prefix = $indent ? str_repeat(' ', $indent) : '';
  48. if ($inline <= 0 || !is_array($input) || empty($input)) {
  49. $output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport);
  50. } else {
  51. $isAHash = array_keys($input) !== range(0, count($input) - 1);
  52. foreach ($input as $key => $value) {
  53. $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
  54. $output .= sprintf('%s%s%s%s',
  55. $prefix,
  56. $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-',
  57. $willBeInlined ? ' ' : "\n",
  58. $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport)
  59. ).($willBeInlined ? "\n" : '');
  60. }
  61. }
  62. return $output;
  63. }
  64. }