PluginProbe
Metricool – Social media and site statistics / 2.1.1
Metricool – Social media and site statistics v2.1.1
2.1.1 2.1.0 2.0.2 2.0.1 2.0.0 1.27 trunk
← All changes | app/Services/MetricoolAccountService.php +87 -0 2.0.1 → 2.1.1 View file →
@@ -1,0 +1,87 @@
1 +<?php
2 +
3 +declare(strict_types=1);
4 +
5 +namespace Metricool\Services;
6 +
7 +use Metricool\Http\Metricool\MetricoolApi;
8 +use Metricool\Support\Helpers\Event;
9 +use Throwable;
10 +
11 +/**
12 + * Service that is responsible for getting the account information
13 + * (premium, user details, etc) of the user that is currently authenticated
14 + * with the Metricool API
15 + */
16 +class MetricoolAccountService
17 +{
18 + public const METRICOOL_USER_OPTION = 'metricool_user';
19 +
20 + private ?array $user;
21 + private MetricoolApi $metricool;
22 +
23 + public function __construct(MetricoolApi $metricool)
24 + {
25 + $this->metricool = $metricool;
26 + $this->user = get_option(self::METRICOOL_USER_OPTION, null);
27 + }
28 +
29 + /**
30 + * Attempts to fetch account from LeadInfo, return the stale data on error
31 + * @return array Account details from api
32 + * @uses EVENT::METRICOOL_USER_UPDATED
33 + */
34 + public function fetch(): array
35 + {
36 + try {
37 + $user = $this->metricool->user()->get();
38 + } catch (Throwable $e) {
39 + return $this->accountData();
40 + }
41 +
42 + $this->storeUser($user);
43 +
44 + Event::dispatch(EVENT::METRICOOL_USER_UPDATED, $user);
45 +
46 + return $this->accountData();
47 + }
48 +
49 + /**
50 + * Return the Metricool user
51 + */
52 + public function getUser(): ?array
53 + {
54 + return $this->user;
55 + }
56 +
57 + /**
58 + * Stores the Metricool user in the database
59 + */
60 + public function storeUser(array $user): void
61 + {
62 + $this->user = $user;
63 + update_option(self::METRICOOL_USER_OPTION, $user, false);
64 + }
65 +
66 + /**
67 + * Returns if the account is a paid / premium account
68 + */
69 + public function isPremium(): bool
70 + {
71 + return isset($this->user['subscription']['plan']['id'])
72 + && $this->user['subscription']['plan']['id'] !== 'FREE';
73 + }
74 +
75 + /**
76 + * Returns a serialized version of the account of this user to be used in the front-end
77 + */
78 + public function accountData(): array
79 + {
80 + return [
81 + 'user_id' => $this->metricool->getUserId(),
82 + 'blog_id' => $this->metricool->getBlogId(),
83 + 'is_premium' => $this->isPremium(),
84 + 'user' => $this->getUser(),
85 + ];
86 + }
87 +}