Skip to content

Commit

Permalink
Output is default flow, simplify late escape.
Browse files Browse the repository at this point in the history
  • Loading branch information
remcotolsma committed Oct 5, 2023
1 parent 5543e10 commit ca6a81e
Showing 1 changed file with 38 additions and 24 deletions.
62 changes: 38 additions & 24 deletions src/Element.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,44 +86,58 @@ public function is_void_element(): bool {
* @return string
*/
public function render() {
$result = '<' . $this->tag;
\ob_start();

if ( \count( $this->attributes ) > 0 ) {
$result .= ' ';
$this->output();

$atts = [];
$output = \ob_get_clean();

foreach ( $this->attributes as $name => $value ) {
$atts[] = '' . $name . '="' . \esc_attr( (string) $value ) . '"';
}
if ( false === $output ) {
throw new \Exception( 'Output buffering is not active.' );
}

$result .= \implode( ' ', $atts );
return $output;
}

/**
* Output.
*
* @return void
*/
public function output() {
echo '<', \tag_escape( $this->tag );

foreach ( $this->attributes as $name => $value ) {
/**
* Attribute name escape.
*
* There is currently not a specific escape function for HTML attributes.
*
* @link https://core.trac.wordpress.org/ticket/43010
* @link https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
*/
echo ' ', \esc_html( $name ), '="', \esc_attr( (string) $value ), '"';
}

if ( $this->is_void_element() ) {
$result .= ' />';
echo ' />';

return $result;
return;
}

$result .= '>';
echo '>';

foreach ( $this->children as $child ) {
$result .= $child;
}

$result .= '</' . $this->tag . '>';
if ( $child instanceof self ) {

Check failure on line 131 in src/Element.php

View workflow job for this annotation

GitHub Actions / phpstan / phpstan

Instanceof between string and Pronamic\WordPress\Html\Element will always evaluate to false.
$child->output();
}

return $result;
}
if ( \is_string( $child ) ) {
echo \esc_html( $child );
}
}

/**
* Print output.
*
* @return int
*/
public function output() {
return print $this->render();
echo '</', \tag_escape( $this->tag ), '>';
}

/**
Expand Down

0 comments on commit ca6a81e

Please sign in to comment.