| 1 |
<?php |
| 2 |
/** |
| 3 |
* Abstract api class |
| 4 |
* |
| 5 |
* @package Timetics |
| 6 |
*/ |
| 7 |
namespace Timetics\Base; |
| 8 |
|
| 9 |
defined( 'ABSPATH' ) || exit; |
| 10 |
|
| 11 |
use WP_Error; |
| 12 |
|
| 13 |
/** |
| 14 |
* Abstract class Api. |
| 15 |
* |
| 16 |
* @since 1.0.0 |
| 17 |
*/ |
| 18 |
abstract class Api extends \WP_REST_Controller { |
| 19 |
|
| 20 |
/** |
| 21 |
* Api Constructor function. |
| 22 |
* |
| 23 |
* @since 1.0.0 |
| 24 |
* |
| 25 |
* @return void |
| 26 |
*/ |
| 27 |
public function __construct() { |
| 28 |
add_action( 'rest_api_init', [ $this, 'register_routes' ] ); |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Register routes |
| 33 |
* |
| 34 |
* @since 1.0.0 |
| 35 |
* |
| 36 |
* @return void |
| 37 |
*/ |
| 38 |
public function register_routes() { |
| 39 |
// Need to override the function on child class. |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Validate input fields. |
| 44 |
* |
| 45 |
* @since 1.0.0 |
| 46 |
* |
| 47 |
* @param array $data Accepts data in array format. |
| 48 |
* @param array $fields Optional. Default empty array. |
| 49 |
* |
| 50 |
* @return bool | WP_error |
| 51 |
*/ |
| 52 |
public function validate( $data, $fields = [] ) { |
| 53 |
$error = new WP_Error(); |
| 54 |
|
| 55 |
foreach ( $fields as $field ) { |
| 56 |
if ( empty( $data[ $field ] ) ) { |
| 57 |
/* translators: Error Message */ |
| 58 |
$error->add( $field . '_error', sprintf( esc_html__( '%s can\'t be empty', 'timetics' ), $field ) ); |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
if ( ! empty( $error->errors ) ) { |
| 63 |
return $error; |
| 64 |
} |
| 65 |
|
| 66 |
return true; |
| 67 |
} |
| 68 |
|
| 69 |
} |
| 70 |
|