PluginProbe
Metricool – Social media and site statistics / 2.0.2
Metricool – Social media and site statistics v2.0.2
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 2.0.2, at app/Features/TaskManagement/TaskManagementEndpoints.php

92 lines 2.4 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 if ($this->adminAccessAllowed() === false) {
38 return $routes;
39 }
40
41 $routes['get_tasks'] = [
42 'methods' => \WP_REST_Server::READABLE,
43 'callback' => [$this, 'getTasksCallback'],
44 ];
45
46 $routes['dismiss_task'] = [
47 'methods' => \WP_REST_Server::CREATABLE,
48 'callback' => [$this, 'dismissTaskCallback'],
49 ];
50
51 return $routes;
52 }
53
54 /**
55 * Return current tasks as a WP_REST_Response.
56 */
57 public function getTasksCallback(\WP_REST_Request $request): \WP_REST_Response
58 {
59 $allTasksAsArray = array_map(function ($task) {
60 return $task->toArray();
61 }, $this->service->getAllTasks(true));
62
63 return $this->sendHttpResponse(
64 array_values($allTasksAsArray) // Keys should be removed
65 );
66 }
67
68 /**
69 * Dismiss a task by taskId.
70 */
71 public function dismissTaskCallback(\WP_REST_Request $request): \WP_REST_Response
72 {
73 $storage = $this->retrieveHttpStorage($request);
74
75 $sanitizedTaskId = $storage->getTitle('taskId');
76 $task = $this->service->getTask($sanitizedTaskId);
77
78 if (!$task) {
79 return $this->sendHttpErrorResponse(__('Task not found', 'metricool'), null, 404);
80 }
81
82 // Attempt to dismiss the task
83 try {
84 $this->service->dismissTask($task->getId());
85 } catch (DismissRequiredTaskException $e) {
86 return $this->sendHttpErrorResponse(__('This task cannot be dismissed because it is required', 'metricool'));
87 }
88
89 return $this->sendHttpResponse(['taskId' => $sanitizedTaskId], true, __('Task dismissed successfully', 'metricool'));
90 }
91 }
92