| 1 |
<?php namespace TierPricingTable\Addons\CustomColumns\API; |
| 2 |
|
| 3 |
use TierPricingTable\Addons\CustomColumns\CustomColumnsManager; |
| 4 |
|
| 5 |
class CustomColumnsEndpoints { |
| 6 |
|
| 7 |
const NAMESPACE = 'tier-pricing-table/features/custom-columns/v1'; |
| 8 |
|
| 9 |
public function __construct() { |
| 10 |
add_action( 'rest_api_init', array( $this, 'registerRoutes' ) ); |
| 11 |
} |
| 12 |
|
| 13 |
public function registerRoutes() { |
| 14 |
|
| 15 |
$columnsManager = CustomColumnsManager::getInstance(); |
| 16 |
|
| 17 |
register_rest_route( self::NAMESPACE, '/columns', array( |
| 18 |
array( |
| 19 |
'methods' => 'GET', |
| 20 |
'callback' => function () use ( $columnsManager ) { |
| 21 |
$rawColumns = $columnsManager->getRawColumns(); |
| 22 |
|
| 23 |
$columnsArray = array(); |
| 24 |
foreach ( $rawColumns as $slug => $data ) { |
| 25 |
$columnsArray[] = array( |
| 26 |
'slug' => $slug, |
| 27 |
'name' => $data['name'] ?? '', |
| 28 |
'type' => $data['type'] ?? 'text', |
| 29 |
'data_type' => $data['data_type'] ?? 'text' |
| 30 |
); |
| 31 |
} |
| 32 |
|
| 33 |
return rest_ensure_response( $columnsArray ); |
| 34 |
}, |
| 35 |
'permission_callback' => function () { |
| 36 |
return current_user_can( 'manage_options' ); |
| 37 |
}, |
| 38 |
), |
| 39 |
array( |
| 40 |
'methods' => 'POST', |
| 41 |
'callback' => function ( $request ) use ( $columnsManager ) { |
| 42 |
$columnsPayload = $request->get_param( 'columns' ); |
| 43 |
|
| 44 |
if ( ! is_array( $columnsPayload ) ) { |
| 45 |
return rest_ensure_response( array( 'success' => false, 'message' => 'Invalid data format' ) ); |
| 46 |
} |
| 47 |
|
| 48 |
$columnsToSave = array(); |
| 49 |
foreach ( $columnsPayload as $col ) { |
| 50 |
if ( isset( $col['slug'] ) && isset( $col['name'] ) && isset( $col['type'] ) ) { |
| 51 |
$columnsToSave[ sanitize_key( $col['slug'] ) ] = array( |
| 52 |
'name' => sanitize_text_field( $col['name'] ), |
| 53 |
'type' => sanitize_text_field( $col['type'] ), |
| 54 |
'data_type' => isset($col['data_type']) ? sanitize_text_field( $col['data_type'] ) : 'text' |
| 55 |
); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
$columnsManager->updateRawColumns( $columnsToSave ); |
| 60 |
|
| 61 |
return rest_ensure_response( array( 'success' => true ) ); |
| 62 |
}, |
| 63 |
'permission_callback' => function () { |
| 64 |
return current_user_can( 'manage_options' ); |
| 65 |
}, |
| 66 |
), |
| 67 |
) ); |
| 68 |
} |
| 69 |
} |
| 70 |
|