| 1 |
<?php |
| 2 |
|
| 3 |
namespace YayMailScoped\YayCommerce\AdminShell\Support; |
| 4 |
|
| 5 |
defined('ABSPATH') || exit; |
| 6 |
/** |
| 7 |
* Slug utilities. |
| 8 |
* |
| 9 |
* Plugin slugs can contain characters that are valid in wp_options keys |
| 10 |
* and URL paths but invalid as JavaScript identifiers (e.g. hyphens, '&'). |
| 11 |
* This helper sanitizes a slug for use as a JS variable name while the |
| 12 |
* original slug stays intact for option-key and REST-URL contexts. |
| 13 |
*/ |
| 14 |
class Slug |
| 15 |
{ |
| 16 |
/** |
| 17 |
* Convert a plugin slug into a valid JS identifier. |
| 18 |
* |
| 19 |
* Rules: |
| 20 |
* - Replace any char outside [A-Za-z0-9_] with '_' |
| 21 |
* - Collapse consecutive underscores |
| 22 |
* - Trim leading/trailing underscores |
| 23 |
* - Prefix '_' if the result starts with a digit |
| 24 |
* - Return '_' for empty / all-special input (never empty string) |
| 25 |
* |
| 26 |
* Idempotent: to_var_name( to_var_name( $x ) ) === to_var_name( $x ). |
| 27 |
*/ |
| 28 |
public static function to_var_name(string $slug): string |
| 29 |
{ |
| 30 |
$name = preg_replace('/[^A-Za-z0-9_]/', '_', $slug); |
| 31 |
$name = preg_replace('/_+/', '_', (string) $name); |
| 32 |
$name = trim((string) $name, '_'); |
| 33 |
if ('' === $name) { |
| 34 |
return '_'; |
| 35 |
} |
| 36 |
if (preg_match('/^\d/', $name)) { |
| 37 |
$name = '_' . $name; |
| 38 |
} |
| 39 |
return $name; |
| 40 |
} |
| 41 |
} |
| 42 |
|