Slug.php
43 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WhatsappScoped\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 | * @internal |
| 14 | */ |
| 15 | class Slug |
| 16 | { |
| 17 | /** |
| 18 | * Convert a plugin slug into a valid JS identifier. |
| 19 | * |
| 20 | * Rules: |
| 21 | * - Replace any char outside [A-Za-z0-9_] with '_' |
| 22 | * - Collapse consecutive underscores |
| 23 | * - Trim leading/trailing underscores |
| 24 | * - Prefix '_' if the result starts with a digit |
| 25 | * - Return '_' for empty / all-special input (never empty string) |
| 26 | * |
| 27 | * Idempotent: to_var_name( to_var_name( $x ) ) === to_var_name( $x ). |
| 28 | */ |
| 29 | public static function to_var_name(string $slug) : string |
| 30 | { |
| 31 | $name = \preg_replace('/[^A-Za-z0-9_]/', '_', $slug); |
| 32 | $name = \preg_replace('/_+/', '_', (string) $name); |
| 33 | $name = \trim((string) $name, '_'); |
| 34 | if ('' === $name) { |
| 35 | return '_'; |
| 36 | } |
| 37 | if (\preg_match('/^\\d/', $name)) { |
| 38 | $name = '_' . $name; |
| 39 | } |
| 40 | return $name; |
| 41 | } |
| 42 | } |
| 43 |