| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\AtomicWidgets\Validators; |
| 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_Validator { |
| 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 ( $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 |
|