RemexCompatFormatter.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace MediaWiki\Tidy;
  3. use RemexHtml\HTMLData;
  4. use RemexHtml\Serializer\HtmlFormatter;
  5. use RemexHtml\Serializer\SerializerNode;
  6. /**
  7. * @internal
  8. */
  9. class RemexCompatFormatter extends HtmlFormatter {
  10. private static $markedEmptyElements = [
  11. 'li' => true,
  12. 'p' => true,
  13. 'tr' => true,
  14. ];
  15. public function __construct( $options = [] ) {
  16. parent::__construct( $options );
  17. $this->attributeEscapes["\u{00A0}"] = '&#160;';
  18. unset( $this->attributeEscapes["&"] );
  19. $this->textEscapes["\u{00A0}"] = '&#160;';
  20. unset( $this->textEscapes["&"] );
  21. }
  22. public function startDocument( $fragmentNamespace, $fragmentName ) {
  23. return '';
  24. }
  25. public function element( SerializerNode $parent, SerializerNode $node, $contents ) {
  26. $data = $node->snData;
  27. if ( $data && $data->isPWrapper ) {
  28. if ( $data->nonblankNodeCount ) {
  29. return "<p>$contents</p>";
  30. } else {
  31. return $contents;
  32. }
  33. }
  34. $name = $node->name;
  35. $attrs = $node->attrs;
  36. if ( isset( self::$markedEmptyElements[$name] ) && $attrs->count() === 0
  37. && strspn( $contents, "\t\n\f\r " ) === strlen( $contents )
  38. ) {
  39. return "<{$name} class=\"mw-empty-elt\">$contents</{$name}>";
  40. }
  41. $s = "<$name";
  42. foreach ( $attrs->getValues() as $attrName => $attrValue ) {
  43. $encValue = strtr( $attrValue, $this->attributeEscapes );
  44. $s .= " $attrName=\"$encValue\"";
  45. }
  46. if ( $node->namespace === HTMLData::NS_HTML && isset( $this->voidElements[$name] ) ) {
  47. $s .= ' />';
  48. return $s;
  49. }
  50. $s .= '>';
  51. if ( $node->namespace === HTMLData::NS_HTML
  52. && isset( $contents[0] ) && $contents[0] === "\n"
  53. && isset( $this->prefixLfElements[$name] )
  54. ) {
  55. $s .= "\n$contents</$name>";
  56. } else {
  57. $s .= "$contents</$name>";
  58. }
  59. return $s;
  60. }
  61. }