| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\AtomicWidgets\Utils; |
| 4 |
|
| 5 |
if ( ! defined( 'ABSPATH' ) ) { |
| 6 |
exit; // Exit if accessed directly. |
| 7 |
} |
| 8 |
|
| 9 |
class Format_Element_Ids { |
| 10 |
public static function format( array $elements, array $path ): array { |
| 11 |
return array_map( function( $element ) use ( $path ) { |
| 12 |
$origin_id = $element['id']; |
| 13 |
$nesting_path = [ ...$path, $origin_id ]; |
| 14 |
|
| 15 |
$element['id'] = self::hash_string( implode( '_', $nesting_path ), 7 ); |
| 16 |
$element['origin_id'] = $origin_id; |
| 17 |
$element['elements'] = self::format( $element['elements'] ?? [], $nesting_path ); |
| 18 |
|
| 19 |
return $element; |
| 20 |
}, $elements ); |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Deterministic djb2-based hash kept in sync with the TypeScript implementation |
| 25 |
* in @elementor/utils (packages/packages/libs/utils/src/hash.ts) so that inner |
| 26 |
* element ids are consistent between the PHP render and the editor's JS layer. |
| 27 |
* |
| 28 |
* @param string $str String to hash. |
| 29 |
* @param int|null $length Optional desired output length. |
| 30 |
* @return string Base-36, lowercase, padded to $length when provided. |
| 31 |
*/ |
| 32 |
public static function hash_string( string $str, ?int $length ): string { |
| 33 |
$hash_basis = 5381; |
| 34 |
|
| 35 |
$i = strlen( $str ); |
| 36 |
while ( $i > 0 ) { |
| 37 |
--$i; |
| 38 |
$hash_basis = ( $hash_basis * 33 ) ^ ord( $str[ $i ] ); |
| 39 |
// Keep hash within 32-bit range to match JavaScript bitwise operations. |
| 40 |
$hash_basis = $hash_basis & 0xFFFFFFFF; |
| 41 |
} |
| 42 |
|
| 43 |
$result = base_convert( (string) $hash_basis, 10, 36 ); |
| 44 |
|
| 45 |
if ( ! isset( $length ) ) { |
| 46 |
return $result; |
| 47 |
} |
| 48 |
|
| 49 |
$sliced = substr( $result, -$length ); |
| 50 |
return str_pad( $sliced, $length, '0', STR_PAD_LEFT ); |
| 51 |
} |
| 52 |
} |
| 53 |
|