PluginProbe
Metricool – Social media and site statistics / trunk
Metricool – Social media and site statistics vtrunk
2.1.0 2.0.2 2.0.1 2.0.0 1.27 trunk
metricool / app / Features / TaskManagement / TaskManagementEndpoints.php

TaskManagementEndpoints.php in Metricool – Social media and site statistics trunk, at app/Features/TaskManagement/TaskManagementEndpoints.php

88 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Metricool\Features\TaskManagement;
6
7 if (!defined('ABSPATH')) {
8 exit;
9 }
10
11 use Metricool\Traits\HasRestAccess;
12 use Metricool\Traits\HasAllowlistControl;
13 use Metricool\Features\TaskManagement\Exceptions\DismissRequiredTaskException;
14
15 class TaskManagementEndpoints
16 {
17 use HasRestAccess;
18 use HasAllowlistControl;
19
20 private TaskManagementService $service;
21
22 public function __construct(TaskManagementService $service)
23 {
24 $this->service = $service;
25 }
26
27 public function register(): void
28 {
29 add_filter('metricool_rest_routes', [$this, 'addTaskRoutes']);
30 }
31
32 /**
33 * Add the task routes to the REST API.
34 */
35 public function addTaskRoutes(array $routes): array
36 {
37 $routes['get_tasks'] = [
38 'methods' => \WP_REST_Server::READABLE,
39 'callback' => [$this, 'getTasksCallback'],
40 ];
41
42 $routes['dismiss_task'] = [
43 'methods' => \WP_REST_Server::CREATABLE,
44 'callback' => [$this, 'dismissTaskCallback'],
45 ];
46
47 return $routes;
48 }
49
50 /**
51 * Return current tasks as a WP_REST_Response.
52 */
53 public function getTasksCallback(\WP_REST_Request $request): \WP_REST_Response
54 {
55 $allTasksAsArray = array_map(function ($task) {
56 return $task->toArray();
57 }, $this->service->getAllTasks(true));
58
59 return $this->sendHttpResponse(
60 array_values($allTasksAsArray) // Keys should be removed
61 );
62 }
63
64 /**
65 * Dismiss a task by taskId.
66 */
67 public function dismissTaskCallback(\WP_REST_Request $request): \WP_REST_Response
68 {
69 $storage = $this->retrieveHttpStorage($request);
70
71 $sanitizedTaskId = $storage->getTitle('taskId');
72 $task = $this->service->getTask($sanitizedTaskId);
73
74 if (!$task) {
75 return $this->sendHttpErrorResponse(__('Task not found', 'metricool'), null, 404);
76 }
77
78 // Attempt to dismiss the task
79 try {
80 $this->service->dismissTask($task->getId());
81 } catch (DismissRequiredTaskException $e) {
82 return $this->sendHttpErrorResponse(__('This task cannot be dismissed because it is required', 'metricool'));
83 }
84
85 return $this->sendHttpResponse(['taskId' => $sanitizedTaskId], true, __('Task dismissed successfully', 'metricool'));
86 }
87 }
88