Skip to content

Commit

Permalink
Rename jsonInAttr to jsonAttr
Browse files Browse the repository at this point in the history
  • Loading branch information
hirasso committed Aug 8, 2024
1 parent 3288cbb commit 684a9b6
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 13 deletions.
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,23 @@ Define your attributes in an associative way:
</button>
```

## `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',
<div <?= attr([
'x-data' => jsonAttr([
'open' => true,
"message" => "This 'quote' is <b>bold</b>"
])
])
]) ?>>
</div>
```

..the output will look like this and can be consumed by JavaScript:

```html
<div x-data="{&quot;open&quot;:true,&quot;message&quot;:&quot;This &#039;quote&#039; is &lt;b&gt;bold&lt;\/b&gt;&quot;}"></div>
```
10 changes: 5 additions & 5 deletions src/Attr.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand All @@ -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);
Expand All @@ -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));
}
}
6 changes: 3 additions & 3 deletions src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 684a9b6

Please sign in to comment.