Dumper.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. use Symfony\Component\Yaml\Tag\TaggedValue;
  12. /**
  13. * Dumper dumps PHP variables to YAML strings.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. *
  17. * @final
  18. */
  19. class Dumper
  20. {
  21. /**
  22. * @param int $indentation The amount of spaces to use for indentation of nested nodes
  23. */
  24. public function __construct(private int $indentation = 4)
  25. {
  26. if ($indentation < 1) {
  27. throw new \InvalidArgumentException('The indentation must be greater than zero.');
  28. }
  29. }
  30. /**
  31. * Dumps a PHP value to YAML.
  32. *
  33. * @param mixed $input The PHP value
  34. * @param int $inline The level where you switch to inline YAML
  35. * @param int $indent The level of indentation (used internally)
  36. * @param int-mask-of<Yaml::DUMP_*> $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
  37. */
  38. public function dump(mixed $input, int $inline = 0, int $indent = 0, int $flags = 0): string
  39. {
  40. if ($flags & Yaml::DUMP_NULL_AS_EMPTY && $flags & Yaml::DUMP_NULL_AS_TILDE) {
  41. throw new \InvalidArgumentException('The Yaml::DUMP_NULL_AS_EMPTY and Yaml::DUMP_NULL_AS_TILDE flags cannot be used together.');
  42. }
  43. return $this->doDump($input, $inline, $indent, $flags);
  44. }
  45. private function doDump(mixed $input, int $inline = 0, int $indent = 0, int $flags = 0, int $nestingLevel = 0): string
  46. {
  47. $output = '';
  48. $prefix = $indent ? str_repeat(' ', $indent) : '';
  49. $dumpObjectAsInlineMap = true;
  50. if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($input instanceof \ArrayObject || $input instanceof \stdClass)) {
  51. $dumpObjectAsInlineMap = !(array) $input;
  52. }
  53. if ($inline <= 0 || (!\is_array($input) && !$input instanceof TaggedValue && $dumpObjectAsInlineMap) || !$input) {
  54. $output .= $prefix.Inline::dump($input, $flags, 0 === $nestingLevel);
  55. } elseif ($input instanceof TaggedValue) {
  56. $output .= $this->dumpTaggedValue($input, $inline, $indent, $flags, $prefix, $nestingLevel);
  57. } else {
  58. $dumpAsMap = Inline::isHash($input);
  59. $compactNestedMapping = Yaml::DUMP_COMPACT_NESTED_MAPPING & $flags && !$dumpAsMap;
  60. foreach ($input as $key => $value) {
  61. if ('' !== $output && "\n" !== $output[-1]) {
  62. $output .= "\n";
  63. }
  64. if (\is_int($key) && Yaml::DUMP_NUMERIC_KEY_AS_STRING & $flags) {
  65. $key = (string) $key;
  66. }
  67. if (Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && \is_string($value) && str_contains($value, "\n") && !str_contains($value, "\r")) {
  68. $blockIndentationIndicator = $this->getBlockIndentationIndicator($value);
  69. if (isset($value[-2]) && "\n" === $value[-2] && "\n" === $value[-1]) {
  70. $blockChompingIndicator = '+';
  71. } elseif ("\n" === $value[-1]) {
  72. $blockChompingIndicator = '';
  73. } else {
  74. $blockChompingIndicator = '-';
  75. }
  76. $output .= \sprintf('%s%s%s |%s%s', $prefix, $dumpAsMap ? Inline::dump($key, $flags).':' : '-', '', $blockIndentationIndicator, $blockChompingIndicator);
  77. foreach (explode("\n", $value) as $row) {
  78. if ('' === $row) {
  79. $output .= "\n";
  80. } else {
  81. $output .= \sprintf("\n%s%s%s", $prefix, str_repeat(' ', $this->indentation), $row);
  82. }
  83. }
  84. continue;
  85. }
  86. if ($value instanceof TaggedValue) {
  87. $output .= \sprintf('%s%s !%s', $prefix, $dumpAsMap ? Inline::dump($key, $flags).':' : '-', $value->getTag());
  88. if (Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && \is_string($value->getValue()) && str_contains($value->getValue(), "\n") && !str_contains($value->getValue(), "\r\n")) {
  89. $blockIndentationIndicator = $this->getBlockIndentationIndicator($value->getValue());
  90. $output .= \sprintf(' |%s', $blockIndentationIndicator);
  91. foreach (explode("\n", $value->getValue()) as $row) {
  92. $output .= \sprintf("\n%s%s%s", $prefix, str_repeat(' ', $this->indentation), $row);
  93. }
  94. continue;
  95. }
  96. if ($inline - 1 <= 0 || null === $value->getValue() || \is_scalar($value->getValue())) {
  97. $output .= ' '.$this->doDump($value->getValue(), $inline - 1, 0, $flags, $nestingLevel + 1)."\n";
  98. } else {
  99. $output .= "\n";
  100. $output .= $this->doDump($value->getValue(), $inline - 1, $dumpAsMap ? $indent + $this->indentation : $indent + 2, $flags, $nestingLevel + 1);
  101. }
  102. continue;
  103. }
  104. $dumpObjectAsInlineMap = true;
  105. if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \ArrayObject || $value instanceof \stdClass)) {
  106. $dumpObjectAsInlineMap = !(array) $value;
  107. }
  108. $willBeInlined = $inline - 1 <= 0 || !\is_array($value) && $dumpObjectAsInlineMap || !$value;
  109. $output .= \sprintf('%s%s%s%s',
  110. $prefix,
  111. $dumpAsMap ? Inline::dump($key, $flags).':' : '-',
  112. $willBeInlined || ($compactNestedMapping && \is_array($value) && Inline::isHash($value)) ? ' ' : "\n",
  113. $compactNestedMapping && \is_array($value) && Inline::isHash($value) ? substr($this->doDump($value, $inline - 1, $indent + 2, $flags, $nestingLevel + 1), $indent + 2) : $this->doDump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $flags, $nestingLevel + 1)
  114. ).($willBeInlined ? "\n" : '');
  115. }
  116. }
  117. return $output;
  118. }
  119. private function dumpTaggedValue(TaggedValue $value, int $inline, int $indent, int $flags, string $prefix, int $nestingLevel): string
  120. {
  121. $output = \sprintf('%s!%s', $prefix ? $prefix.' ' : '', $value->getTag());
  122. if (Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && \is_string($value->getValue()) && str_contains($value->getValue(), "\n") && !str_contains($value->getValue(), "\r\n")) {
  123. $blockIndentationIndicator = $this->getBlockIndentationIndicator($value->getValue());
  124. $output .= \sprintf(' |%s', $blockIndentationIndicator);
  125. foreach (explode("\n", $value->getValue()) as $row) {
  126. $output .= \sprintf("\n%s%s%s", $prefix, str_repeat(' ', $this->indentation), $row);
  127. }
  128. return $output;
  129. }
  130. if ($inline - 1 <= 0 || null === $value->getValue() || \is_scalar($value->getValue())) {
  131. return $output.' '.$this->doDump($value->getValue(), $inline - 1, 0, $flags, $nestingLevel + 1)."\n";
  132. }
  133. return $output."\n".$this->doDump($value->getValue(), $inline - 1, $indent, $flags, $nestingLevel + 1);
  134. }
  135. private function getBlockIndentationIndicator(string $value): string
  136. {
  137. $lines = explode("\n", $value);
  138. // If the first line (that is neither empty nor contains only spaces)
  139. // starts with a space character, the spec requires a block indentation indicator
  140. // http://www.yaml.org/spec/1.2/spec.html#id2793979
  141. foreach ($lines as $line) {
  142. if ('' !== trim($line, ' ')) {
  143. return str_starts_with($line, ' ') ? (string) $this->indentation : '';
  144. }
  145. }
  146. return '';
  147. }
  148. }