FormValidationService.php
95 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Form; |
| 4 | |
| 5 | /** |
| 6 | * Handles server-side form validation of gutenberg blocks. |
| 7 | */ |
| 8 | class FormValidationService { |
| 9 | /** |
| 10 | * Holds the parsed blocks. |
| 11 | * |
| 12 | * @var array |
| 13 | */ |
| 14 | protected $blocks = []; |
| 15 | |
| 16 | /** |
| 17 | * The form post content. |
| 18 | * |
| 19 | * @var string |
| 20 | */ |
| 21 | protected $content = ''; |
| 22 | |
| 23 | /** |
| 24 | * Params to validate. |
| 25 | * |
| 26 | * @var array |
| 27 | */ |
| 28 | protected $params = []; |
| 29 | |
| 30 | /** |
| 31 | * Get things going. |
| 32 | * |
| 33 | * @param string $content Post content. |
| 34 | * @param array $params Params to validate. |
| 35 | */ |
| 36 | public function __construct( $content, $params = [] ) { |
| 37 | $this->content = $content; |
| 38 | $this->params = $params; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Validate the form submission. |
| 43 | * |
| 44 | * @return true|WP_Error |
| 45 | */ |
| 46 | public function validate() { |
| 47 | $this->blocks = parse_blocks( $this->content ); |
| 48 | return true; |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Find required blocks recursively. |
| 53 | */ |
| 54 | public function findRequiredBlocks() { |
| 55 | return $this->getNestedBlocksWhere( 'required', true ); |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Get nested block with a specific attribute/value pair. |
| 60 | * |
| 61 | * @param string $attribute Attribute name. |
| 62 | * @param any $value The value. |
| 63 | * @return array |
| 64 | */ |
| 65 | protected function getNestedBlocksWhere( $attribute, $value ) { |
| 66 | $blocks_with_requirements = $this->getNestedBlockWithAttribute( $this->blocks, 'required' ); |
| 67 | return array_filter( |
| 68 | $blocks_with_requirements, |
| 69 | function( $block ) use ( $attribute, $value ) { |
| 70 | return $block['attrs'][ $attribute ] === $value; |
| 71 | } |
| 72 | ); |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * Get nested values from an array |
| 77 | * |
| 78 | * @param array $array Array to search. |
| 79 | * @param string $nested_key Nested key to search for. |
| 80 | * @return array |
| 81 | */ |
| 82 | protected function getNestedBlockWithAttribute( array $array, $nested_key ) { |
| 83 | $return = array(); |
| 84 | array_walk_recursive( |
| 85 | $array, |
| 86 | function( $a, $key ) use ( &$return, $nested_key ) { |
| 87 | if ( $nested_key === $key ) { |
| 88 | $return[] = $a; |
| 89 | } |
| 90 | } |
| 91 | ); |
| 92 | return $return; |
| 93 | } |
| 94 | } |
| 95 |