Files

41 lines
1.5 KiB
PHP
Raw Permalink Normal View History

<?php
declare( strict_types=1 );
namespace StreamGoals\Alerts;
/** Renders the custom alert message. Output is plain text: no tags, no control characters, length-capped. */
final class Template {
public const MAX = 200;
public static function clean( string $s ): string {
$s = strip_tags( $s );
$s = (string) preg_replace( '/[\x00-\x1F\x7F\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}\x{FEFF}]+/u', ' ', $s );
$s = str_replace( array( '<', '>' ), '', $s );
return trim( (string) preg_replace( '/\s+/u', ' ', $s ) );
}
/**
* Tokens: {name} {amount} {reward} (case-insensitive). Unknown tokens are dropped. Substituted values are never
* re-scanned for tokens. Empty template (or empty result) returns '' meaning "use the default text".
*/
public static function render( string $template, string $name, string $amount, string $reward, int $max = self::MAX ): string {
$tpl = self::clean( $template );
if ( '' === $tpl ) {
return '';
}
$name = self::clean( $name );
$vals = array(
'name' => '' === $name ? 'Anonymous' : mb_substr( $name, 0, 60 ),
'amount' => mb_substr( self::clean( $amount ), 0, 30 ),
'reward' => mb_substr( self::clean( $reward ), 0, 80 ),
);
$out = (string) preg_replace_callback(
'/\{([A-Za-z_]{1,20})\}/',
static fn( array $m ): string => $vals[ strtolower( $m[1] ) ] ?? '',
$tpl
);
$out = trim( (string) preg_replace( '/\s+/u', ' ', $out ) );
return mb_substr( $out, 0, max( 1, $max ) );
}
}