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