| 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 |
|
| 15 |
public function __construct( array $schema ) { |
| 16 |
$this->schema = $schema; |
| 17 |
} |
| 18 |
|
| 19 |
public static function make( array $schema ): self { |
| 20 |
return new static( $schema ); |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* @param array $props |
| 25 |
* The key of each item represents the prop name (should match the schema), |
| 26 |
* and the value is the prop value to validate |
| 27 |
*/ |
| 28 |
public function validate( array $props ): Parse_Result { |
| 29 |
$result = Parse_Result::make(); |
| 30 |
|
| 31 |
$validated = []; |
| 32 |
|
| 33 |
foreach ( $this->schema as $key => $prop_type ) { |
| 34 |
if ( ! ( $prop_type instanceof Prop_Type ) ) { |
| 35 |
continue; |
| 36 |
} |
| 37 |
|
| 38 |
$value = $props[ $key ] ?? null; |
| 39 |
|
| 40 |
$is_valid = $prop_type->validate( $value ?? $prop_type->get_default() ); |
| 41 |
|
| 42 |
if ( ! $is_valid ) { |
| 43 |
$result->errors()->add( $key, 'invalid_value' ); |
| 44 |
|
| 45 |
continue; |
| 46 |
} |
| 47 |
|
| 48 |
if ( ! is_null( $value ) ) { |
| 49 |
$validated[ $key ] = $value; |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
return $result->wrap( $validated ); |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* @param array $props |
| 58 |
* The key of each item represents the prop name (should match the schema), |
| 59 |
* and the value is the prop value to sanitize |
| 60 |
*/ |
| 61 |
public function sanitize( array $props ): Parse_Result { |
| 62 |
$sanitized = []; |
| 63 |
|
| 64 |
foreach ( $this->schema as $key => $prop_type ) { |
| 65 |
if ( ! isset( $props[ $key ] ) ) { |
| 66 |
continue; |
| 67 |
} |
| 68 |
|
| 69 |
$sanitized[ $key ] = $prop_type->sanitize( $props[ $key ] ); |
| 70 |
} |
| 71 |
|
| 72 |
return Parse_Result::make()->wrap( $sanitized ); |
| 73 |
} |
| 74 |
|
| 75 |
/** |
| 76 |
* @param array $props |
| 77 |
* The key of each item represents the prop name (should match the schema), |
| 78 |
* and the value is the prop value to parse |
| 79 |
*/ |
| 80 |
public function parse( array $props ): Parse_Result { |
| 81 |
$validate_result = $this->validate( $props ); |
| 82 |
|
| 83 |
$sanitize_result = $this->sanitize( $validate_result->unwrap() ); |
| 84 |
|
| 85 |
$sanitize_result->errors()->merge( $validate_result->errors() ); |
| 86 |
|
| 87 |
return $sanitize_result; |
| 88 |
} |
| 89 |
} |
| 90 |
|