| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\AtomicWidgets\Parsers; |
| 4 |
|
| 5 |
use Elementor\Modules\AtomicWidgets\PropTypes\Contracts\Prop_Type; |
| 6 |
|
| 7 |
if ( ! defined( 'ABSPATH' ) ) { |
| 8 |
exit; // Exit if accessed directly. |
| 9 |
} |
| 10 |
|
| 11 |
class Props_Parser { |
| 12 |
|
| 13 |
private array $schema; |
| 14 |
private array $errors_bag = []; |
| 15 |
|
| 16 |
public function __construct( array $schema ) { |
| 17 |
$this->schema = $schema; |
| 18 |
} |
| 19 |
|
| 20 |
public static function make( array $schema ): self { |
| 21 |
return new static( $schema ); |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* @param array $props |
| 26 |
* The key of each item represents the prop name (should match the schema), |
| 27 |
* and the value is the prop value to validate |
| 28 |
* |
| 29 |
* @return array{ |
| 30 |
* 0: bool, |
| 31 |
* 1: array<string, mixed>, |
| 32 |
* 2: array<string> |
| 33 |
* } |
| 34 |
*/ |
| 35 |
public function validate( array $props ): array { |
| 36 |
$validated = []; |
| 37 |
|
| 38 |
foreach ( $this->schema as $key => $prop_type ) { |
| 39 |
if ( ! ( $prop_type instanceof Prop_Type ) ) { |
| 40 |
continue; |
| 41 |
} |
| 42 |
|
| 43 |
$value = $props[ $key ] ?? null; |
| 44 |
|
| 45 |
$is_valid = $prop_type->validate( $value ?? $prop_type->get_default() ); |
| 46 |
|
| 47 |
if ( ! $is_valid ) { |
| 48 |
$this->errors_bag[] = $key; |
| 49 |
|
| 50 |
continue; |
| 51 |
} |
| 52 |
|
| 53 |
if ( ! is_null( $value ) ) { |
| 54 |
$validated[ $key ] = $value; |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
$is_valid = empty( $this->errors_bag ); |
| 59 |
|
| 60 |
return [ |
| 61 |
$is_valid, |
| 62 |
$validated, |
| 63 |
$this->errors_bag, |
| 64 |
]; |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* @param array $props |
| 69 |
* The key of each item represents the prop name (should match the schema), |
| 70 |
* and the value is the prop value to sanitize |
| 71 |
* |
| 72 |
* @return array<string, mixed> |
| 73 |
*/ |
| 74 |
public function sanitize( array $props ): array { |
| 75 |
$sanitized = []; |
| 76 |
|
| 77 |
foreach ( $this->schema as $key => $prop_type ) { |
| 78 |
if ( ! isset( $props[ $key ] ) ) { |
| 79 |
continue; |
| 80 |
} |
| 81 |
|
| 82 |
$sanitized[ $key ] = $prop_type->sanitize( $props[ $key ] ); |
| 83 |
} |
| 84 |
|
| 85 |
return $sanitized; |
| 86 |
} |
| 87 |
|
| 88 |
/** |
| 89 |
* @param array $props |
| 90 |
* The key of each item represents the prop name (should match the schema), |
| 91 |
* and the value is the prop value to parse |
| 92 |
* |
| 93 |
* @return array{ |
| 94 |
* 0: bool, |
| 95 |
* 1: array<string, mixed>, |
| 96 |
* 2: array<string> |
| 97 |
* } |
| 98 |
*/ |
| 99 |
public function parse( array $props ): array { |
| 100 |
[ $is_valid, $validated, $errors_bag ] = $this->validate( $props ); |
| 101 |
|
| 102 |
return [ |
| 103 |
$is_valid, |
| 104 |
$this->sanitize( $validated ), |
| 105 |
$errors_bag, |
| 106 |
]; |
| 107 |
} |
| 108 |
} |
| 109 |
|