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/Http/Metricool/Entities/DistributionStatistics.php +95 -0 2.0.0 → 2.1.1 View file →
@@ -1,0 +1,95 @@
1 +<?php
2 +
3 +declare(strict_types=1);
4 +
5 +namespace Metricool\Http\Metricool\Entities;
6 +
7 +use Metricool\Vendor\Carbon\Carbon;
8 +use Metricool\Support\Helpers\Collection;
9 +use Metricool\Http\Metricool\DTOs\DistributionDTO;
10 +use Metricool\Http\Metricool\MetricoolClient;
11 +use Metricool\Http\Metricool\Traits\IsFilterable;
12 +use Metricool\Traits\IsHydratable;
13 +
14 +/**
15 + * API responses for distribution statistics include data on how various metrics
16 + * are distributed. Such as page views by country, referrer pages, or traffic
17 + * sources.
18 + */
19 +class DistributionStatistics
20 +{
21 + use IsFilterable;
22 + use IsHydratable;
23 +
24 + protected MetricoolClient $client;
25 + protected string $endpoint = 'stats/distribution/';
26 + protected string $metric;
27 +
28 + /**
29 + * The distribution statistics API is compatible with these metrics.
30 + */
31 + private array $metrics = [
32 + 'country',
33 + 'referers',
34 + 'sources',
35 + ];
36 +
37 + /**
38 + * Pass a compatible metric to the constructor: {@see metrics}
39 + * @throws \InvalidArgumentException
40 + */
41 + public function __construct(MetricoolClient $client, string $metric, bool $filterRequired = true)
42 + {
43 + if (!in_array($metric, $this->metrics)) {
44 + throw new \InvalidArgumentException(esc_html("Incompatible metric given: $metric"));
45 + }
46 +
47 + $this->metric = $metric;
48 + $this->client = $client;
49 + $this->endpoint .= $metric;
50 + $this->requiresFilter = $filterRequired;
51 +
52 + /**
53 + * The distribution statistics API need a filter by default to prevent
54 + * Internal Server errors on the remote server. We set the default
55 + * filters to the last 30 days.
56 + */
57 + $this->filters = [
58 + 'start' => Carbon::now()->subDays(30)->format('Ymd'),
59 + 'end' => Carbon::now()->format('Ymd'),
60 + ];
61 + }
62 +
63 + /**
64 + * @inheritDoc
65 + */
66 + protected function getAcceptedFilters(): array
67 + {
68 + return [
69 + 'start' => '/^\d+$/', // Just digits
70 + 'end' => '/^\d+$/', // Just digits
71 + 'country' => '/^[a-z]{2}$/', // ISO 3166-1 alpha-2 lowercase country code
72 + ];
73 + }
74 +
75 +
76 + /**
77 + * Hydrate every result into a DistributionDTO object
78 + */
79 + protected function hydrateItem($key, $item): DistributionDTO
80 + {
81 + return new DistributionDTO($this->metric, $key, $item);
82 + }
83 +
84 + /**
85 + * Fetch and return the distribution statistics data
86 + */
87 + public function get(): Collection
88 + {
89 + if ($this->requiresFilter && $this->filtered === false) {
90 + $this->filter($this->filters);
91 + }
92 +
93 + return $this->hydrateResults($this->client->get($this->endpoint));
94 + }
95 +}