Dumper.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. if ($num < 1) {
  32. throw new \InvalidArgumentException('The indentation must be greater than zero.');
  33. }
  34. $this->indentation = (int) $num;
  35. }
  36. /**
  37. * Dumps a PHP value to YAML.
  38. *
  39. * @param mixed $input The PHP value
  40. * @param int $inline The level where you switch to inline YAML
  41. * @param int $indent The level of indentation (used internally)
  42. * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  43. * @param bool $objectSupport True if object support is enabled, false otherwise
  44. *
  45. * @return string The YAML representation of the PHP value
  46. */
  47. public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false)
  48. {
  49. $output = '';
  50. $prefix = $indent ? str_repeat(' ', $indent) : '';
  51. if ($inline <= 0 || !\is_array($input) || empty($input)) {
  52. $output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport);
  53. } else {
  54. $isAHash = Inline::isHash($input);
  55. foreach ($input as $key => $value) {
  56. $willBeInlined = $inline - 1 <= 0 || !\is_array($value) || empty($value);
  57. $output .= sprintf('%s%s%s%s',
  58. $prefix,
  59. $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-',
  60. $willBeInlined ? ' ' : "\n",
  61. $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport)
  62. ).($willBeInlined ? "\n" : '');
  63. }
  64. }
  65. return $output;
  66. }
  67. }