| 1 |
<?php |
| 2 |
namespace Depicter\Html; |
| 3 |
|
| 4 |
use Averta\WordPress\Utility\JSON; |
| 5 |
use TypeRocket\Html\Tag as TypeRocketTag; |
| 6 |
|
| 7 |
class Tag extends TypeRocketTag |
| 8 |
{ |
| 9 |
|
| 10 |
const ALLOWED_EMPTY_ATTRIBUTES = ['alt']; |
| 11 |
|
| 12 |
/** |
| 13 |
* Html constructor. |
| 14 |
* |
| 15 |
* @param string $tag |
| 16 |
* @param array|null $attributes |
| 17 |
* @param string|Tag|Html|array|null $nest |
| 18 |
*/ |
| 19 |
public function __construct( $tag, $attributes = null, $nest = null) |
| 20 |
{ |
| 21 |
parent::__construct( $tag, $attributes, $nest ); |
| 22 |
|
| 23 |
// Adding 'meta', 'link' and 'source' to close tags list |
| 24 |
if( in_array( $this->tag, ['img', 'br', 'hr', 'input', 'meta', 'link', 'source'] ) ) { |
| 25 |
$this->closed = true; |
| 26 |
} |
| 27 |
|
| 28 |
return $this; |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Get the opening tag in string form |
| 33 |
* |
| 34 |
* @return string |
| 35 |
*/ |
| 36 |
public function open() { |
| 37 |
$openTag = "<{$this->tag}"; |
| 38 |
|
| 39 |
foreach($this->attr as $attribute => $value) { |
| 40 |
if ( JSON::isJson( $value ) ) { |
| 41 |
$value = htmlentities( str_replace( '"', "'", $value ), ENT_NOQUOTES, 'UTF-8'); |
| 42 |
} elseif( in_array( $attribute, ['href'] ) ) { |
| 43 |
$value = esc_url_raw( $value ); |
| 44 |
} elseif ( ! in_array( $attribute, ['data-src', 'src', 'data-srcset'] ) ) { |
| 45 |
$value = trim( esc_attr( $value ) ); |
| 46 |
} |
| 47 |
|
| 48 |
if( in_array( $attribute, static::ALLOWED_EMPTY_ATTRIBUTES ) && empty( $value ) ) { |
| 49 |
$value = '=""'; |
| 50 |
} else { |
| 51 |
$value = $value !== '' ? "=\"{$value}\"" : ''; |
| 52 |
} |
| 53 |
|
| 54 |
$openTag .= " {$attribute}{$value}"; |
| 55 |
} |
| 56 |
|
| 57 |
$openTag .= $this->closed ? " />" : ">"; |
| 58 |
|
| 59 |
return $openTag; |
| 60 |
} |
| 61 |
|
| 62 |
} |
| 63 |
|