Writer.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sabre\Xml;
  4. use XMLWriter;
  5. /**
  6. * The XML Writer class.
  7. *
  8. * This class works exactly as PHP's built-in XMLWriter, with a few additions.
  9. *
  10. * Namespaces can be registered beforehand, globally. When the first element is
  11. * written, namespaces will automatically be declared.
  12. *
  13. * The writeAttribute, startElement and writeElement can now take a
  14. * clark-notation element name (example: {http://www.w3.org/2005/Atom}link).
  15. *
  16. * If, when writing the namespace is a known one a prefix will automatically be
  17. * selected, otherwise a random prefix will be generated.
  18. *
  19. * Instead of standard string values, the writer can take Element classes (as
  20. * defined by this library) to delegate the serialization.
  21. *
  22. * The write() method can take array structures to quickly write out simple xml
  23. * trees.
  24. *
  25. * @copyright Copyright (C) 2009-2015 fruux GmbH (https://fruux.com/).
  26. * @author Evert Pot (http://evertpot.com/)
  27. * @license http://sabre.io/license/ Modified BSD License
  28. */
  29. class Writer extends \XMLWriter
  30. {
  31. use ContextStackTrait;
  32. /**
  33. * Any namespace that the writer is asked to write, will be added here.
  34. *
  35. * Any of these elements will get a new namespace definition *every single
  36. * time* they are used, but this array allows the writer to make sure that
  37. * the prefixes are consistent anyway.
  38. *
  39. * @var array
  40. */
  41. protected $adhocNamespaces = [];
  42. /**
  43. * When the first element is written, this flag is set to true.
  44. *
  45. * This ensures that the namespaces in the namespaces map are only written
  46. * once.
  47. *
  48. * @var bool
  49. */
  50. protected $namespacesWritten = false;
  51. /**
  52. * Writes a value to the output stream.
  53. *
  54. * The following values are supported:
  55. * 1. Scalar values will be written as-is, as text.
  56. * 2. Null values will be skipped (resulting in a short xml tag).
  57. * 3. If a value is an instance of an Element class, writing will be
  58. * delegated to the object.
  59. * 4. If a value is an array, two formats are supported.
  60. *
  61. * Array format 1:
  62. * [
  63. * "{namespace}name1" => "..",
  64. * "{namespace}name2" => "..",
  65. * ]
  66. *
  67. * One element will be created for each key in this array. The values of
  68. * this array support any format this method supports (this method is
  69. * called recursively).
  70. *
  71. * Array format 2:
  72. *
  73. * [
  74. * [
  75. * "name" => "{namespace}name1"
  76. * "value" => "..",
  77. * "attributes" => [
  78. * "attr" => "attribute value",
  79. * ]
  80. * ],
  81. * [
  82. * "name" => "{namespace}name1"
  83. * "value" => "..",
  84. * "attributes" => [
  85. * "attr" => "attribute value",
  86. * ]
  87. * ]
  88. * ]
  89. */
  90. public function write($value)
  91. {
  92. Serializer\standardSerializer($this, $value);
  93. }
  94. /**
  95. * Opens a new element.
  96. *
  97. * You can either just use a local elementname, or you can use clark-
  98. * notation to start a new element.
  99. *
  100. * Example:
  101. *
  102. * $writer->startElement('{http://www.w3.org/2005/Atom}entry');
  103. *
  104. * Would result in something like:
  105. *
  106. * <entry xmlns="http://w3.org/2005/Atom">
  107. *
  108. * Note: this function doesn't have the string typehint, because PHP's
  109. * XMLWriter::startElement doesn't either.
  110. *
  111. * @param string $name
  112. */
  113. public function startElement($name): bool
  114. {
  115. if ('{' === $name[0]) {
  116. list($namespace, $localName) =
  117. Service::parseClarkNotation($name);
  118. if (array_key_exists($namespace, $this->namespaceMap)) {
  119. $result = $this->startElementNS(
  120. '' === $this->namespaceMap[$namespace] ? null : $this->namespaceMap[$namespace],
  121. $localName,
  122. null
  123. );
  124. } else {
  125. // An empty namespace means it's the global namespace. This is
  126. // allowed, but it mustn't get a prefix.
  127. if ('' === $namespace || null === $namespace) {
  128. $result = $this->startElement($localName);
  129. $this->writeAttribute('xmlns', '');
  130. } else {
  131. if (!isset($this->adhocNamespaces[$namespace])) {
  132. $this->adhocNamespaces[$namespace] = 'x'.(count($this->adhocNamespaces) + 1);
  133. }
  134. $result = $this->startElementNS($this->adhocNamespaces[$namespace], $localName, $namespace);
  135. }
  136. }
  137. } else {
  138. $result = parent::startElement($name);
  139. }
  140. if (!$this->namespacesWritten) {
  141. foreach ($this->namespaceMap as $namespace => $prefix) {
  142. $this->writeAttribute($prefix ? 'xmlns:'.$prefix : 'xmlns', $namespace);
  143. }
  144. $this->namespacesWritten = true;
  145. }
  146. return $result;
  147. }
  148. /**
  149. * Write a full element tag and it's contents.
  150. *
  151. * This method automatically closes the element as well.
  152. *
  153. * The element name may be specified in clark-notation.
  154. *
  155. * Examples:
  156. *
  157. * $writer->writeElement('{http://www.w3.org/2005/Atom}author',null);
  158. * becomes:
  159. * <author xmlns="http://www.w3.org/2005" />
  160. *
  161. * $writer->writeElement('{http://www.w3.org/2005/Atom}author', [
  162. * '{http://www.w3.org/2005/Atom}name' => 'Evert Pot',
  163. * ]);
  164. * becomes:
  165. * <author xmlns="http://www.w3.org/2005" /><name>Evert Pot</name></author>
  166. *
  167. * Note: this function doesn't have the string typehint, because PHP's
  168. * XMLWriter::startElement doesn't either.
  169. *
  170. * @param array|string|object|null $content
  171. */
  172. public function writeElement($name, $content = null): bool
  173. {
  174. $this->startElement($name);
  175. if (!is_null($content)) {
  176. $this->write($content);
  177. }
  178. $this->endElement();
  179. return true;
  180. }
  181. /**
  182. * Writes a list of attributes.
  183. *
  184. * Attributes are specified as a key->value array.
  185. *
  186. * The key is an attribute name. If the key is a 'localName', the current
  187. * xml namespace is assumed. If it's a 'clark notation key', this namespace
  188. * will be used instead.
  189. */
  190. public function writeAttributes(array $attributes)
  191. {
  192. foreach ($attributes as $name => $value) {
  193. $this->writeAttribute($name, $value);
  194. }
  195. }
  196. /**
  197. * Writes a new attribute.
  198. *
  199. * The name may be specified in clark-notation.
  200. *
  201. * Returns true when successful.
  202. *
  203. * Note: this function doesn't have typehints, because for some reason
  204. * PHP's XMLWriter::writeAttribute doesn't either.
  205. *
  206. * @param string $name
  207. * @param string $value
  208. */
  209. public function writeAttribute($name, $value): bool
  210. {
  211. if ('{' !== $name[0]) {
  212. return parent::writeAttribute($name, $value);
  213. }
  214. list(
  215. $namespace,
  216. $localName
  217. ) = Service::parseClarkNotation($name);
  218. if (array_key_exists($namespace, $this->namespaceMap)) {
  219. // It's an attribute with a namespace we know
  220. return $this->writeAttribute(
  221. $this->namespaceMap[$namespace].':'.$localName,
  222. $value
  223. );
  224. }
  225. // We don't know the namespace, we must add it in-line
  226. if (!isset($this->adhocNamespaces[$namespace])) {
  227. $this->adhocNamespaces[$namespace] = 'x'.(count($this->adhocNamespaces) + 1);
  228. }
  229. return $this->writeAttributeNS(
  230. $this->adhocNamespaces[$namespace],
  231. $localName,
  232. $namespace,
  233. $value
  234. );
  235. }
  236. }