onboarding-builder.php
| 1 | <?php |
| 2 | |
| 3 | namespace JFB_Modules\Shortcode; |
| 4 | |
| 5 | use JFB_Modules\Onboarding\Builders\Exceptions\Use_Form_Exception; |
| 6 | use JFB_Modules\Onboarding\Builders\Interfaces\Builder_Create_Page_Interface; |
| 7 | use JFB_Modules\Onboarding\Builders\Interfaces\Builder_Interface; |
| 8 | use JFB_Modules\Onboarding\Builders\Interfaces\Builder_Update_Page_Interface; |
| 9 | |
| 10 | class Onboarding_Builder { |
| 11 | |
| 12 | public function init_hooks() { |
| 13 | add_action( 'jet-form-builder/use-form', array( $this, 'handle_use' ) ); |
| 14 | } |
| 15 | |
| 16 | /** |
| 17 | * @param Builder_Create_Page_Interface|Builder_Update_Page_Interface $builder |
| 18 | * |
| 19 | * @return void |
| 20 | * @throws Use_Form_Exception |
| 21 | */ |
| 22 | public function handle_use( Builder_Interface $builder ) { |
| 23 | if ( 'shortcode' !== $builder->get_builder_type() ) { |
| 24 | return; |
| 25 | } |
| 26 | |
| 27 | if ( $builder instanceof Builder_Update_Page_Interface ) { |
| 28 | $this->update( $builder ); |
| 29 | |
| 30 | return; |
| 31 | } |
| 32 | |
| 33 | $this->create( $builder ); |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * @return void |
| 38 | * @throws Use_Form_Exception |
| 39 | */ |
| 40 | public function create( Builder_Create_Page_Interface $create_page ) { |
| 41 | $post_id = wp_insert_post( |
| 42 | array( |
| 43 | 'post_title' => $create_page->get_title(), |
| 44 | 'post_type' => 'page', |
| 45 | 'post_status' => 'draft', |
| 46 | ), |
| 47 | true |
| 48 | ); |
| 49 | |
| 50 | if ( is_wp_error( $post_id ) ) { |
| 51 | // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped |
| 52 | throw new Use_Form_Exception( $post_id->get_error_message() ); |
| 53 | } |
| 54 | |
| 55 | $create_page->set_redirect_url( get_edit_post_link( $post_id, false ) ); |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * @param Builder_Update_Page_Interface $update_page |
| 60 | * |
| 61 | * @return void |
| 62 | * @throws Use_Form_Exception |
| 63 | */ |
| 64 | public function update( Builder_Update_Page_Interface $update_page ) { |
| 65 | $page = get_post( $update_page->get_page_id() ); |
| 66 | |
| 67 | if ( ! ( $page instanceof \WP_Post ) ) { |
| 68 | throw new Use_Form_Exception( 'Undefined page' ); |
| 69 | } |
| 70 | |
| 71 | $update_page->set_redirect_url( |
| 72 | get_edit_post_link( $update_page->get_page_id(), false ) |
| 73 | ); |
| 74 | } |
| 75 | } |
| 76 |