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 / Http / Endpoints / ConnectedNetworksEndpoint.php

ConnectedNetworksEndpoint.php in Metricool – Social media and site statistics trunk, at app/Http/Endpoints/ConnectedNetworksEndpoint.php

89 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\Http\Endpoints;
6
7 use Metricool\Vendor\GuzzleHttp\Exception\GuzzleException;
8 use Metricool\Http\Endpoints\Responses\ConnectedNetworksResponse;
9 use Metricool\Http\Metricool\MetricoolApi;
10 use Metricool\Interfaces\SingleEndpointInterface;
11 use Metricool\Services\DashboardService;
12 use Metricool\Traits\HasAllowlistControl;
13 use Metricool\Traits\HasRestAccess;
14
15 class ConnectedNetworksEndpoint implements SingleEndpointInterface
16 {
17 use HasRestAccess;
18 use HasAllowlistControl;
19
20 public const ROUTE = 'connected_networks';
21
22 public MetricoolApi $metricoolApi;
23 public DashboardService $dashboard;
24
25 public function __construct(MetricoolApi $metricoolApi, DashboardService $dashboard)
26 {
27 $this->metricoolApi = $metricoolApi;
28 $this->dashboard = $dashboard;
29 }
30
31 /**
32 * @inheritDoc
33 */
34 public function registerRoute(): string
35 {
36 return self::ROUTE;
37 }
38
39 /**
40 * Only enable this endpoint when onboarding is completed
41 */
42 public function enabled(): bool
43 {
44 return $this->dashboard->isOnboardingCompleted();
45 }
46
47 /**
48 * @inheritDoc
49 */
50 public function registerArguments(): array
51 {
52 return [
53 'methods' => \WP_REST_Server::READABLE,
54 'callback' => [$this, 'callback'],
55 'middleware' => ['metricool:auth', 'metricool:blog_id'],
56 ];
57 }
58
59 /**
60 * Return the brands related to the user
61 *
62 * GET /wp-json/metricool/v1/connected_networks
63 */
64 public function callback(\WP_REST_Request $request): \WP_REST_Response
65 {
66 try {
67 $response = $this->buildResponse($request);
68 } catch (\Exception $e) {
69 return $this->sendHttpErrorResponse(__('Failed to load brands data', 'metricool'), $e->getMessage(), $e->getCode());
70 }
71
72 return $this->sendHttpResponse($response);
73 }
74
75 /**
76 * Build the specific ConnectedNetworksResponse response for the endpoint.
77 * This response returns just the brand names that are connected to the user.
78 * Filtering it server side prevents client-side complexity.
79 * @throws GuzzleException
80 */
81 public function buildResponse(\WP_REST_Request $request): array
82 {
83 $connectedBrand = $this->metricoolApi->connectedBrands()->get();
84 $response = new ConnectedNetworksResponse($connectedBrand);
85
86 return $response->body();
87 }
88 }
89