| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Handle request(ajax|api) call step by step |
| 5 |
* |
| 6 |
* Class LP_Handle_Steps |
| 7 |
* @author tungnx |
| 8 |
* @version 1.0.0 |
| 9 |
*/ |
| 10 |
class LP_Handle_Steps { |
| 11 |
/** |
| 12 |
* @var LP_Group_Step[] |
| 13 |
*/ |
| 14 |
public $group_steps = array(); |
| 15 |
|
| 16 |
/** |
| 17 |
* @param array $params | keys: steps, step, data. |
| 18 |
*/ |
| 19 |
public function handle( array $params ) { |
| 20 |
$response = new LP_REST_Response(); |
| 21 |
|
| 22 |
try { |
| 23 |
$steps = $params['steps'] ?? array(); |
| 24 |
|
| 25 |
if ( empty( $steps ) ) { |
| 26 |
throw new Exception( __( 'Invalid steps', 'learnpress' ) ); |
| 27 |
} |
| 28 |
|
| 29 |
$step = $params['step'] ?? ''; |
| 30 |
if ( empty( $step ) ) { |
| 31 |
throw new Exception( __( 'Invalid step', 'learnpress' ) ); |
| 32 |
} |
| 33 |
|
| 34 |
$data = $params['data'] ?? array(); |
| 35 |
|
| 36 |
/** |
| 37 |
* @var $response LP_Step |
| 38 |
*/ |
| 39 |
$response = $this->call_step( $step, $data ); |
| 40 |
|
| 41 |
// Next step or Finish. |
| 42 |
if ( 'finished' === $response->status ) { |
| 43 |
// Set param to clone table next. |
| 44 |
$index = array_search( $step, $steps, true ); |
| 45 |
++ $index; |
| 46 |
|
| 47 |
if ( ! empty( $steps[ $index ] ) ) { |
| 48 |
$response->status = 'success'; |
| 49 |
$response->name = $steps[ $index ]; |
| 50 |
$response->data = new stdClass(); |
| 51 |
} else { |
| 52 |
$response->status = 'finished'; |
| 53 |
} |
| 54 |
} |
| 55 |
} catch ( Exception $exception ) { |
| 56 |
$response->message = $exception->getMessage(); |
| 57 |
} |
| 58 |
|
| 59 |
wp_send_json( $response ); |
| 60 |
} |
| 61 |
|
| 62 |
/** |
| 63 |
* Call Step |
| 64 |
* |
| 65 |
* @param string $step . |
| 66 |
* @param array $data . |
| 67 |
* |
| 68 |
* @return false|mixed |
| 69 |
* @throws Exception . |
| 70 |
*/ |
| 71 |
public function call_step( string $step, $data = array() ) { |
| 72 |
$step_function = apply_filters( "lp-handle-steps/$step", array( $this, $step ) ); |
| 73 |
|
| 74 |
if ( is_callable( $step_function ) ) { |
| 75 |
return call_user_func( $step_function, $data ); |
| 76 |
} |
| 77 |
|
| 78 |
throw new Exception( __( 'Function not found', 'learnpress' ) . $step_function ); |
| 79 |
} |
| 80 |
} |
| 81 |
|