← All changes
|
app/Features/Notifications/NotificationsEndpoints.php
+57
-0
2.0.0
→
2.1.1
View file →
| @@ -1,0 +1,57 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace Metricool\Features\Notifications; | |
| 6 | + | |
| 7 | +if (!defined('ABSPATH')) { | |
| 8 | + exit; | |
| 9 | +} | |
| 10 | + | |
| 11 | +use Metricool\Traits\HasRestAccess; | |
| 12 | +use Metricool\Traits\HasAllowlistControl; | |
| 13 | + | |
| 14 | +class NotificationsEndpoints | |
| 15 | +{ | |
| 16 | + use HasRestAccess; | |
| 17 | + use HasAllowlistControl; | |
| 18 | + | |
| 19 | + private NotificationsService $service; | |
| 20 | + | |
| 21 | + public function __construct(NotificationsService $service) | |
| 22 | + { | |
| 23 | + $this->service = $service; | |
| 24 | + } | |
| 25 | + | |
| 26 | + public function register(): void | |
| 27 | + { | |
| 28 | + add_filter('metricool_rest_routes', [$this, 'addNotificationRoutes']); | |
| 29 | + } | |
| 30 | + | |
| 31 | + /** | |
| 32 | + * Add the Notification routes to the REST API. | |
| 33 | + */ | |
| 34 | + public function addNotificationRoutes(array $routes): array | |
| 35 | + { | |
| 36 | + $routes['get_notices'] = [ | |
| 37 | + 'methods' => \WP_REST_Server::READABLE, | |
| 38 | + 'callback' => [$this, 'getNoticesCallback'], | |
| 39 | + ]; | |
| 40 | + | |
| 41 | + return $routes; | |
| 42 | + } | |
| 43 | + | |
| 44 | + /** | |
| 45 | + * Return current Notices as a WP_REST_Response. | |
| 46 | + */ | |
| 47 | + public function getNoticesCallback(\WP_REST_Request $request): \WP_REST_Response | |
| 48 | + { | |
| 49 | + $allNoticesAsArray = array_map(function ($notice) { | |
| 50 | + return $notice->toArray(); | |
| 51 | + }, $this->service->getAllNotices()); | |
| 52 | + | |
| 53 | + return $this->sendHttpResponse( | |
| 54 | + array_values($allNoticesAsArray) // Keys should be removed | |
| 55 | + ); | |
| 56 | + } | |
| 57 | +} | |