Dumper.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.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.potencier@symfony-project.com>
  15. */
  16. class Dumper
  17. {
  18. /**
  19. * Dumps a PHP value to YAML.
  20. *
  21. * @param mixed $input The PHP value
  22. * @param integer $inline The level where you switch to inline YAML
  23. * @param integer $indent The level of indentation (used internally)
  24. *
  25. * @return string The YAML representation of the PHP value
  26. */
  27. public function dump($input, $inline = 0, $indent = 0)
  28. {
  29. $output = '';
  30. $prefix = $indent ? str_repeat(' ', $indent) : '';
  31. if ($inline <= 0 || !is_array($input) || empty($input)) {
  32. $output .= $prefix.Inline::dump($input);
  33. } else {
  34. $isAHash = array_keys($input) !== range(0, count($input) - 1);
  35. foreach ($input as $key => $value) {
  36. $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
  37. $output .= sprintf('%s%s%s%s',
  38. $prefix,
  39. $isAHash ? Inline::dump($key).':' : '-',
  40. $willBeInlined ? ' ' : "\n",
  41. $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + 2)
  42. ).($willBeInlined ? "\n" : '');
  43. }
  44. }
  45. return $output;
  46. }
  47. }