Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 20 additions & 12 deletions src/Core/ViewHelper/TagBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ class TagBuilder
protected bool $forceClosingTag = false;

protected bool $ignoreEmptyAttributes = false;
/**
* Specifies whether a value is required for boolean attributes
*/
protected bool $requireAttributeValues = true;

/**
* Constructor
Expand Down Expand Up @@ -168,6 +172,11 @@ public function ignoreEmptyAttributes(bool $ignoreEmptyAttributes): void
}
}

public function requireAttributeValues(bool $requireAttributeValues): void
{
$this->requireAttributeValues = $requireAttributeValues;
}

/**
* Adds an attribute to the $attributes-collection
*
Expand Down Expand Up @@ -213,16 +222,6 @@ public function addAttribute(string $attributeName, $attributeValue, bool $escap
$this->addAttribute($attributeName . '-' . $name, $value, $escapeSpecialCharacters);
}
} else {
// This should probably also check for null, but we can't do that for now because of backwards compatibility
if ($attributeValue === false) {
$this->removeAttribute($attributeName);
return;
}

if ($attributeValue === true) {
$attributeValue = $attributeName;
}

if ($attributeValue instanceof \BackedEnum) {
$attributeValue = (string)$attributeValue->value;
} elseif ($attributeValue instanceof \UnitEnum) {
Expand All @@ -232,7 +231,8 @@ public function addAttribute(string $attributeName, $attributeValue, bool $escap
if (trim((string)$attributeValue) === '' && $this->ignoreEmptyAttributes) {
return;
}
if ($escapeSpecialCharacters) {
// Escape non-boolean values
if (!is_bool($attributeValue) && $escapeSpecialCharacters) {
$attributeValue = htmlspecialchars((string)$attributeValue);
}
$this->attributes[$attributeName] = $attributeValue;
Expand Down Expand Up @@ -289,7 +289,15 @@ public function render(): string
}
$output = '<' . $this->tagName;
foreach ($this->attributes as $attributeName => $attributeValue) {
$output .= ' ' . $attributeName . '="' . $attributeValue . '"';
if ($attributeValue === true) {
if ($this->requireAttributeValues) {
$output .= ' ' . $attributeName . '="' . $attributeName . '"';
} else {
$output .= ' ' . $attributeName;
}
} elseif ($attributeValue !== false) {
$output .= ' ' . $attributeName . '="' . $attributeValue . '"';
}
}
if ($this->hasContent() || $this->forceClosingTag) {
$output .= '>' . $this->content . '</' . $this->tagName . '>';
Expand Down