| 1 |
<?php |
| 2 |
namespace Elementor\Modules\Components\Utils; |
| 3 |
|
| 4 |
use Elementor\Plugin; |
| 5 |
use Elementor\Modules\AtomicWidgets\Elements\Base\Atomic_Element_Base; |
| 6 |
use Elementor\Modules\AtomicWidgets\Elements\Base\Atomic_Widget_Base; |
| 7 |
use Elementor\Modules\AtomicWidgets\Utils\Utils; |
| 8 |
use Elementor\Modules\AtomicWidgets\PropTypes\Contracts\Prop_Type; |
| 9 |
|
| 10 |
if ( ! defined( 'ABSPATH' ) ) { |
| 11 |
exit; // Exit if accessed directly. |
| 12 |
} |
| 13 |
|
| 14 |
class Format_Component_Elements_Id { |
| 15 |
public static function format( array $elements, array $path ) { |
| 16 |
return array_map( function( $element ) use ( $path ) { |
| 17 |
$origin_id = $element['id']; |
| 18 |
$nesting_path = [ ...$path, $origin_id ]; |
| 19 |
|
| 20 |
$element['id'] = self::hash_string( implode( '_', $nesting_path ), 7 ); |
| 21 |
$element['origin_id'] = $origin_id; |
| 22 |
$element['elements'] = self::format( $element['elements'], $nesting_path ); |
| 23 |
|
| 24 |
return $element; |
| 25 |
}, $elements ); |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* This is a copy of the hashString function in ts utils package. |
| 30 |
* It's important to keep it in synced with the ts implementation |
| 31 |
* to make component inner elements ids consistent between the editor and the frontend. |
| 32 |
* |
| 33 |
* @param string $str - The string to hash. |
| 34 |
* @param $length - The length of the hash to return, optional. |
| 35 |
* @return string - The hashed string. |
| 36 |
*/ |
| 37 |
public static function hash_string( string $str, ?int $length ): string { |
| 38 |
$hash_basis = 5381; |
| 39 |
|
| 40 |
$i = strlen( $str ); |
| 41 |
while ( $i > 0 ) { |
| 42 |
--$i; |
| 43 |
$hash_basis = ( $hash_basis * 33 ) ^ ord( $str[ $i ] ); |
| 44 |
// Keep hash within 32-bit range to match JavaScript bitwise operations. |
| 45 |
$hash_basis = $hash_basis & 0xFFFFFFFF; |
| 46 |
} |
| 47 |
|
| 48 |
$result = base_convert( (string) $hash_basis, 10, 36 ); |
| 49 |
|
| 50 |
if ( ! isset( $length ) ) { |
| 51 |
return $result; |
| 52 |
} |
| 53 |
|
| 54 |
$sliced = substr( $result, -$length ); |
| 55 |
return str_pad( $sliced, $length, '0', STR_PAD_LEFT ); |
| 56 |
} |
| 57 |
} |
| 58 |
|