Skip to content

HtmlString for handling of both HTML and plain text strings #5982

@dtdesign

Description

@dtdesign

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.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions