rest-validation-endpoint.php
81 lines
| 1 | <?php |
| 2 | |
| 3 | |
| 4 | namespace JFB_Modules\Validation\Rest_Api; |
| 5 | |
| 6 | use Jet_Form_Builder\Blocks\Block_Helper; |
| 7 | use Jet_Form_Builder\Classes\Arrayable\Array_Tools; |
| 8 | use Jet_Form_Builder\Exceptions\Repository_Exception; |
| 9 | use Jet_Form_Builder\Exceptions\Silence_Exception; |
| 10 | use Jet_Form_Builder\Request\Exceptions\Plain_Value_Exception; |
| 11 | use JFB_Modules\Block_Parsers\Field_Data_Parser; |
| 12 | use Jet_Form_Builder\Request\Request_Tools; |
| 13 | use JFB_Components\Rest_Api; |
| 14 | use JFB_Modules\Validation\Module; |
| 15 | use JFB_Modules\Validation\Handlers\Validation_Handler; |
| 16 | use WP_REST_Request; |
| 17 | use WP_REST_Response; |
| 18 | |
| 19 | |
| 20 | // If this file is called directly, abort. |
| 21 | if ( ! defined( 'WPINC' ) ) { |
| 22 | die; |
| 23 | } |
| 24 | |
| 25 | class Rest_Validation_Endpoint extends Rest_Api\Rest_Api_Endpoint_Base { |
| 26 | |
| 27 | const FIELD_KEY = '_jfb_validation_path'; |
| 28 | const RULE_INDEX_KEY = '_jfb_validation_rule_index'; |
| 29 | |
| 30 | public static function get_rest_base() { |
| 31 | return 'validate-field'; |
| 32 | } |
| 33 | |
| 34 | public static function get_methods() { |
| 35 | return \WP_REST_Server::CREATABLE; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * @param \WP_REST_Request $request |
| 40 | * |
| 41 | * @return \WP_REST_Response |
| 42 | * @throws Repository_Exception |
| 43 | */ |
| 44 | public function run_callback( \WP_REST_Request $request ) { |
| 45 | $body = $request->get_body_params(); |
| 46 | $result = Validation_Handler::validate( $body ); |
| 47 | return new WP_REST_Response( $result ); |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * @param \WP_REST_Request $request |
| 52 | * |
| 53 | * @return Field_Data_Parser |
| 54 | * @throws Plain_Value_Exception |
| 55 | * @throws Repository_Exception |
| 56 | */ |
| 57 | protected function get_parser( \WP_REST_Request $request ): Field_Data_Parser { |
| 58 | $body = $request->get_body_params(); |
| 59 | |
| 60 | $path = $body[ self::FIELD_KEY ] ?? false; |
| 61 | |
| 62 | $form_id = $body[ jet_fb_handler()->form_key ] ?? false; |
| 63 | |
| 64 | jet_fb_handler()->set_form_id( $form_id ); |
| 65 | |
| 66 | jet_fb_context()->set_request( $body ); |
| 67 | jet_fb_context()->set_files( Request_Tools::get_files( $request->get_file_params() ) ); |
| 68 | |
| 69 | // set fields with request |
| 70 | jet_fb_context()->apply( |
| 71 | Block_Helper::get_blocks_by_post( $form_id ) |
| 72 | ); |
| 73 | |
| 74 | return jet_fb_context()->resolve_parser( $path ); |
| 75 | } |
| 76 | |
| 77 | public function get_parser_public( \WP_REST_Request $request ) { |
| 78 | return $this->get_parser( $request ); |
| 79 | } |
| 80 | } |
| 81 |