| 1 |
<?php |
| 2 |
|
| 3 |
namespace FL\Assistant\Controllers; |
| 4 |
|
| 5 |
use FL\Assistant\Data\Repository\LabelsRepository; |
| 6 |
use FL\Assistant\Data\Transformers\LabelsTransformer; |
| 7 |
use FL\Assistant\System\Contracts\ControllerAbstract; |
| 8 |
use WP_REST_Server; |
| 9 |
|
| 10 |
/** |
| 11 |
* REST API logic for notation labels. |
| 12 |
*/ |
| 13 |
class LabelsController extends ControllerAbstract { |
| 14 |
|
| 15 |
/** |
| 16 |
* @var LabelsRepository |
| 17 |
*/ |
| 18 |
protected $labels; |
| 19 |
protected $transformer; |
| 20 |
|
| 21 |
/** |
| 22 |
* LabelsController constructor. |
| 23 |
* |
| 24 |
* @param LabelsRepository $labels |
| 25 |
*/ |
| 26 |
public function __construct( LabelsRepository $labels, LabelsTransformer $transformer ) { |
| 27 |
$this->labels = $labels; |
| 28 |
$this->transformer = $transformer; |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Register routes. |
| 33 |
*/ |
| 34 |
public function register_routes() { |
| 35 |
$this->route( |
| 36 |
'/labels', [ |
| 37 |
[ |
| 38 |
'methods' => WP_REST_Server::READABLE, |
| 39 |
'callback' => [ $this, 'get_labels' ], |
| 40 |
'permission_callback' => function () { |
| 41 |
return current_user_can( 'edit_others_posts' ); |
| 42 |
}, |
| 43 |
], |
| 44 |
] |
| 45 |
); |
| 46 |
|
| 47 |
$this->route( |
| 48 |
'/labels/count', |
| 49 |
[ |
| 50 |
[ |
| 51 |
'methods' => WP_REST_Server::READABLE, |
| 52 |
'callback' => [ $this, 'label_counts' ], |
| 53 |
'permission_callback' => function () { |
| 54 |
return current_user_can( 'edit_others_posts' ); |
| 55 |
}, |
| 56 |
], |
| 57 |
] |
| 58 |
); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Returns all labels. |
| 63 |
* |
| 64 |
* @param \WP_REST_Request $request |
| 65 |
* |
| 66 |
* @return mixed|\WP_REST_Response |
| 67 |
*/ |
| 68 |
public function get_labels( \WP_REST_Request $request ) { |
| 69 |
$response = []; |
| 70 |
$terms = $this->labels->query( |
| 71 |
[ |
| 72 |
'hide_empty' => false, |
| 73 |
] |
| 74 |
)->get_terms(); |
| 75 |
|
| 76 |
foreach ( $terms as $term ) { |
| 77 |
$response[] = call_user_func( $this->transformer, $term ); |
| 78 |
} |
| 79 |
|
| 80 |
return rest_ensure_response( $response ); |
| 81 |
} |
| 82 |
|
| 83 |
/** |
| 84 |
* Returns an array of counts by label ID. |
| 85 |
*/ |
| 86 |
public function label_counts( $request ) { |
| 87 |
return rest_ensure_response( $this->labels->count() ); |
| 88 |
} |
| 89 |
} |
| 90 |
|