verify-manually.php
90 lines
| 1 | <?php |
| 2 | |
| 3 | |
| 4 | namespace JFB_Modules\Verification\Rest_Api\Endpoints; |
| 5 | |
| 6 | use Jet_Form_Builder\Exceptions\Repository_Exception; |
| 7 | use JFB_Components\Rest_Api\Rest_Api_Endpoint_Base; |
| 8 | use JFB_Modules\Jobs\Module; |
| 9 | |
| 10 | // If this file is called directly, abort. |
| 11 | if ( ! defined( 'WPINC' ) ) { |
| 12 | die(); |
| 13 | } |
| 14 | |
| 15 | class Verify_Manually extends Rest_Api_Endpoint_Base { |
| 16 | |
| 17 | public static function get_rest_base() { |
| 18 | return 'verification/verify'; |
| 19 | } |
| 20 | |
| 21 | public static function get_methods() { |
| 22 | return \WP_REST_Server::CREATABLE; |
| 23 | } |
| 24 | |
| 25 | public function check_permission(): bool { |
| 26 | return current_user_can( 'manage_options' ); |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * @param \WP_REST_Request $request |
| 31 | * |
| 32 | * @return \WP_REST_Response |
| 33 | * @throws Repository_Exception |
| 34 | */ |
| 35 | public function run_callback( \WP_REST_Request $request ) { |
| 36 | $ids = array_map( 'absint', $request['checked'] ?? array() ); |
| 37 | |
| 38 | /** @var Module $jobs */ |
| 39 | $jobs = jet_form_builder()->module( 'jobs' ); |
| 40 | /** @var \JFB_Modules\Verification\Jobs\Verify_Manually $job */ |
| 41 | $job = $jobs->get( \JFB_Modules\Verification\Jobs\Verify_Manually::class ); |
| 42 | |
| 43 | $is_single = 1 === count( $ids ); |
| 44 | |
| 45 | foreach ( $ids as $id ) { |
| 46 | $job->set_args( array( $id, get_current_user_id() ) ); |
| 47 | // clear possible duplicates of the current job |
| 48 | $job->unschedule(); |
| 49 | |
| 50 | // check is exist running jobs |
| 51 | if ( $job->is_scheduled() ) { |
| 52 | continue; |
| 53 | } |
| 54 | |
| 55 | if ( $is_single ) { |
| 56 | $job->execute( $id, get_current_user_id() ); |
| 57 | break; |
| 58 | } else { |
| 59 | // add new job to queue |
| 60 | $job->schedule(); |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | $errors = $job->get_logs(); |
| 65 | |
| 66 | if ( ! empty( $errors ) ) { |
| 67 | return new \WP_REST_Response( |
| 68 | array( |
| 69 | 'message' => $errors[0], |
| 70 | ), |
| 71 | 400 |
| 72 | ); |
| 73 | } |
| 74 | |
| 75 | return new \WP_REST_Response( |
| 76 | array( |
| 77 | 'message' => $is_single |
| 78 | ? __( |
| 79 | 'This record has been verified.', |
| 80 | 'jet-form-builder' |
| 81 | ) |
| 82 | : __( |
| 83 | 'Checked records would be verified soon.', |
| 84 | 'jet-form-builder' |
| 85 | ), |
| 86 | ) |
| 87 | ); |
| 88 | } |
| 89 | } |
| 90 |