Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
dtdesign opened this issue Aug 23, 2024 · 0 comments
Open

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

dtdesign opened this issue Aug 23, 2024 · 0 comments
Labels

Comments

@dtdesign
Copy link
Member

dtdesign commented Aug 23, 2024

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.

@dtdesign dtdesign changed the title EncodedString for handling of both HTML and plain text strings HtmlString for handling of both HTML and plain text strings Aug 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: No status
Development

No branches or pull requests

1 participant