From 684a9b6654b18542538fb4e3fda104f823044650 Mon Sep 17 00:00:00 2001 From: Rasso Hilber Date: Thu, 8 Aug 2024 11:59:40 +0200 Subject: [PATCH] Rename `jsonInAttr` to `jsonAttr` --- README.md | 18 +++++++++++++----- src/Attr.php | 10 +++++----- src/helpers.php | 6 +++--- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 9b8f36b..d3b09e5 100644 --- a/README.md +++ b/README.md @@ -43,15 +43,23 @@ Define your attributes in an associative way: ``` -## `jsonInAttr()` +## `jsonAttr()` Render JSON so that it is safe to be used inside an HTMLElement attribute: ```php /** Example: render an attribute to be used by Alpine.js */ -echo attr([ - 'x-data' => jsonInAttr([ - 'open' => 'true', +
jsonAttr([ + 'open' => true, + "message" => "This 'quote' is bold" ]) -]) +]) ?>> +
+``` + +..the output will look like this and can be consumed by JavaScript: + +```html +
``` \ No newline at end of file diff --git a/src/Attr.php b/src/Attr.php index 0c8a325..6fd9ed1 100644 --- a/src/Attr.php +++ b/src/Attr.php @@ -84,7 +84,7 @@ private static function sanitizeAttributeValue( /** remove double spaces and line breaks */ $value = preg_replace('/\s+/', ' ', $value); /** convert to entities */ - return self::htmlentitiesAgain($value); + return self::safeHtmlEntities($value); } /** @@ -109,7 +109,7 @@ private static function arrayToStyles( * * @see https://developer.wordpress.org/reference/functions/htmlentities2/ */ - private static function htmlentitiesAgain( + private static function safeHtmlEntities( string $text ): string { $translation_table = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES); @@ -126,14 +126,14 @@ private static function htmlentitiesAgain( } /** - * Convert a PHP array or object to a json string that's safe to be used in an attribute + * Convert an array or object to a JSON string that's safe to be used in an attribute */ - public static function jsonInAttr( + public static function jsonAttr( mixed $value = '' ): string { if (empty($value)) { return ''; } - return self::htmlentitiesAgain(json_encode($value, JSON_NUMERIC_CHECK)); + return self::safeHtmlEntities(json_encode($value, JSON_NUMERIC_CHECK)); } } diff --git a/src/helpers.php b/src/helpers.php index 345fc03..75f89a0 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -21,14 +21,14 @@ function attr( } -if (!function_exists('jsonInAttr')) { +if (!function_exists('jsonAttr')) { /** * Convert an object or array to JSON that's safe to be used inside a HTMLElement attribute */ - function jsonInAttr( + function jsonAttr( mixed $value = '' ) { - return Attr::jsonInAttr($value); + return Attr::jsonAttr($value); } }