exceptions
3 years ago
fields
3 years ago
field-data-parser.php
3 years ago
file-uploader.php
3 years ago
form-request-router.php
3 years ago
parser-context.php
3 years ago
parser-manager.php
3 years ago
request-handler.php
3 years ago
request-router.php
3 years ago
request-tools.php
3 years ago
request-router.php
87 lines
| 1 | <?php |
| 2 | |
| 3 | |
| 4 | namespace Jet_Form_Builder\Request; |
| 5 | |
| 6 | use Jet_Form_Builder\Exceptions\Not_Router_Request; |
| 7 | |
| 8 | abstract class Request_Router { |
| 9 | |
| 10 | abstract protected function get_hook_name(): string; |
| 11 | |
| 12 | abstract protected function get_hook_value(): string; |
| 13 | |
| 14 | /** |
| 15 | * @throws Not_Router_Request |
| 16 | */ |
| 17 | protected function is_request(): Request_Router { |
| 18 | // phpcs:ignore WordPress.Security.NonceVerification.Recommended |
| 19 | $hook_value = sanitize_text_field( wp_unslash( $_REQUEST[ $this->get_hook_name() ] ?? '' ) ); |
| 20 | |
| 21 | if ( $this->get_hook_value() !== $hook_value ) { |
| 22 | throw new Not_Router_Request( 'Request is not matched' ); |
| 23 | } |
| 24 | |
| 25 | return $this; |
| 26 | } |
| 27 | |
| 28 | protected function get_method(): string { |
| 29 | // phpcs:ignore WordPress.Security.NonceVerification.Recommended |
| 30 | return sanitize_text_field( wp_unslash( $_REQUEST['method'] ?? '' ) ); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * @throws Not_Router_Request |
| 35 | */ |
| 36 | public static function listen(): Request_Router { |
| 37 | $listener = ( new static() )->is_request(); |
| 38 | $method = $listener->get_method(); |
| 39 | |
| 40 | $listener->is_method( $method ); |
| 41 | |
| 42 | if ( 'ajax' === $method ) { |
| 43 | define( 'DOING_AJAX', true ); |
| 44 | |
| 45 | add_action( 'parse_request', array( $listener, 'setup_ajax_request' ) ); |
| 46 | } |
| 47 | |
| 48 | return $listener; |
| 49 | } |
| 50 | |
| 51 | |
| 52 | /** |
| 53 | * @param string $method |
| 54 | * |
| 55 | * @return Request_Router |
| 56 | * @throws Not_Router_Request |
| 57 | */ |
| 58 | private function is_method( string $method ): Request_Router { |
| 59 | if ( ! in_array( $method, array( 'reload', 'ajax' ), true ) ) { |
| 60 | throw new Not_Router_Request( 'Request METHOD is not matched' ); |
| 61 | } |
| 62 | |
| 63 | return $this; |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Setup front referrer |
| 68 | * |
| 69 | * @param \WP $wp |
| 70 | * |
| 71 | * @return never-return |
| 72 | */ |
| 73 | public function setup_ajax_request( \WP $wp ) { |
| 74 | $wp->query_posts(); |
| 75 | $wp->register_globals(); |
| 76 | |
| 77 | if ( is_user_logged_in() ) { |
| 78 | do_action( 'wp_ajax_' . $this->get_hook_name() ); |
| 79 | } else { |
| 80 | do_action( 'wp_ajax_nopriv_' . $this->get_hook_name() ); |
| 81 | } |
| 82 | |
| 83 | die(); |
| 84 | } |
| 85 | |
| 86 | } |
| 87 |