One repeating issue with the handling of strings passed to a function is that it is not always clear if the content has been encoded already and is safe for output. When in doubt we encode the string which can cause intended HTML to be encoded or already encoded strings to be encoded twice.
There is also the inverse case where an API previously only expected regular strings but now should also allow safe HTML to be used. This often leads to separate API methods or additional parameters, which is both cumbersome and error-prone.
<?php
use wcf\util\StringUtil;
final class HtmlString implements \Stringable
{
private function __construct(
private readonly string $value
) {}
public static function fromText(string $value): self
{
return new self(
StringUtil::encodeHTML($value),
);
}
public static function fromSafeHtml(string $value): self
{
return new self($value);
}
public function __toString(): string
{
return $this->value;
}
}
This moves the responsibility of properly encoding the value to the callee. The two distinct methods fromText() and fromSafeHtml() provide the necessary guardrails to prevent accidental misuse.
One repeating issue with the handling of strings passed to a function is that it is not always clear if the content has been encoded already and is safe for output. When in doubt we encode the string which can cause intended HTML to be encoded or already encoded strings to be encoded twice.
There is also the inverse case where an API previously only expected regular strings but now should also allow safe HTML to be used. This often leads to separate API methods or additional parameters, which is both cumbersome and error-prone.
This moves the responsibility of properly encoding the value to the callee. The two distinct methods
fromText()andfromSafeHtml()provide the necessary guardrails to prevent accidental misuse.