| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\AtomicWidgets\Validators; |
| 4 |
|
| 5 |
if ( ! defined( 'ABSPATH' ) ) { |
| 6 |
exit; // Exit if accessed directly. |
| 7 |
} |
| 8 |
|
| 9 |
class Styles_Validator { |
| 10 |
const VALID_STATES = [ |
| 11 |
'hover', |
| 12 |
'active', |
| 13 |
'focus', |
| 14 |
null, |
| 15 |
]; |
| 16 |
|
| 17 |
private array $schema; |
| 18 |
|
| 19 |
private array $errors_bag = []; |
| 20 |
|
| 21 |
public function __construct( array $schema ) { |
| 22 |
$this->schema = $schema; |
| 23 |
} |
| 24 |
|
| 25 |
public static function make( array $schema ): self { |
| 26 |
return new static( $schema ); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* @param array $styles |
| 31 |
* The key of each item represents the style id, |
| 32 |
* and the value is the style object to validate |
| 33 |
* |
| 34 |
* @return array{ |
| 35 |
* 0: bool, |
| 36 |
* 1: array<string, mixed>, |
| 37 |
* 2: array<string> |
| 38 |
* } |
| 39 |
*/ |
| 40 |
public function validate( array $styles ): array { |
| 41 |
foreach ( $styles as $style_id => $style ) { |
| 42 |
if ( ! isset( $style['id'] ) || ! is_string( $style['id'] ) ) { |
| 43 |
$this->errors_bag[] = 'id'; |
| 44 |
$styles[ $style_id ] = []; |
| 45 |
continue; |
| 46 |
} |
| 47 |
|
| 48 |
foreach ( $style['variants'] as $variant_index => $variant ) { |
| 49 |
if ( ! isset( $variant['meta'] ) ) { |
| 50 |
$this->errors_bag[] = 'meta'; |
| 51 |
continue; |
| 52 |
} |
| 53 |
|
| 54 |
$this->validate_meta( $variant['meta'] ); |
| 55 |
|
| 56 |
[,$validated_props, $variant_errors] = Props_Validator::make( $this->schema )->validate( $variant['props'] ); |
| 57 |
$styles[ $style_id ]['variants'][ $variant_index ]['props'] = $validated_props; |
| 58 |
|
| 59 |
$this->errors_bag = array_merge( $this->errors_bag, $variant_errors ); |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
$is_valid = empty( $this->errors_bag ); |
| 64 |
|
| 65 |
return [ |
| 66 |
$is_valid, |
| 67 |
$styles, |
| 68 |
$this->errors_bag, |
| 69 |
]; |
| 70 |
} |
| 71 |
|
| 72 |
public function validate_meta( $meta ) { |
| 73 |
if ( ! is_array( $meta ) ) { |
| 74 |
$this->errors_bag[] = 'meta'; |
| 75 |
} |
| 76 |
|
| 77 |
if ( ! array_key_exists( 'state', $meta ) || ! in_array( $meta['state'], self::VALID_STATES, true ) ) { |
| 78 |
$this->errors_bag[] = 'meta'; |
| 79 |
} |
| 80 |
|
| 81 |
// TODO: Validate breakpoint based on the existing breakpoints in the system [EDS-528] |
| 82 |
if ( ! isset( $meta['breakpoint'] ) || ! is_string( $meta['breakpoint'] ) ) { |
| 83 |
$this->errors_bag[] = 'meta'; |
| 84 |
} |
| 85 |
} |
| 86 |
} |
| 87 |
|