Dumper.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <[email protected]>
  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 <[email protected]>
  15. */
  16. class Dumper
  17. {
  18. /**
  19. * The amount of spaces to use for indentation of nested nodes.
  20. *
  21. * @var integer
  22. */
  23. protected $indentation = 4;
  24. /**
  25. * Sets the indentation.
  26. *
  27. * @param integer $num The amount of spaces to use for intendation 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 integer $inline The level where you switch to inline YAML
  38. * @param integer $indent The level of indentation (used internally)
  39. *
  40. * @return string The YAML representation of the PHP value
  41. */
  42. public function dump($input, $inline = 0, $indent = 0)
  43. {
  44. $output = '';
  45. $prefix = $indent ? str_repeat(' ', $indent) : '';
  46. if ($inline <= 0 || !is_array($input) || empty($input)) {
  47. $output .= $prefix.Inline::dump($input);
  48. } else {
  49. $isAHash = array_keys($input) !== range(0, count($input) - 1);
  50. foreach ($input as $key => $value) {
  51. $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
  52. $output .= sprintf('%s%s%s%s',
  53. $prefix,
  54. $isAHash ? Inline::dump($key).':' : '-',
  55. $willBeInlined ? ' ' : "\n",
  56. $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation)
  57. ).($willBeInlined ? "\n" : '');
  58. }
  59. }
  60. return $output;
  61. }
  62. }