Passed
Push — feature/code-analysis ( e964aa...4fe35d )
by Jonathan
14:33
created

MatomoStatsService   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 90
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 38
dl 0
loc 90
rs 10
c 0
b 0
f 0
wmc 11

3 Methods

Rating   Name   Duplication   Size   Complexity  
A visitsToday() 0 6 1
B visits() 0 38 8
A visitsThisYear() 0 14 2
1
<?php
2
3
/**
4
 * webtrees-lib: MyArtJaub library for webtrees
5
 *
6
 * @package MyArtJaub\Webtrees
7
 * @subpackage WelcomeBlock
8
 * @author Jonathan Jaubart <[email protected]>
9
 * @copyright Copyright (c) 2020-2022, Jonathan Jaubart
10
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 3
11
 */
12
13
declare(strict_types=1);
14
15
namespace MyArtJaub\Webtrees\Module\WelcomeBlock\Services;
16
17
use Carbon\Carbon;
18
use Fig\Http\Message\StatusCodeInterface;
19
use Fisharebest\Webtrees\Registry;
20
use GuzzleHttp\Client;
21
use GuzzleHttp\RequestOptions;
22
use GuzzleHttp\Exception\GuzzleException;
23
use MyArtJaub\Webtrees\Module\WelcomeBlock\WelcomeBlockModule;
24
25
/**
26
 * Service for retrieving Matomo statistics
27
 *
28
 */
29
class MatomoStatsService
30
{
31
    /**
32
     * Returns the number of visits for the current year (up to the day before).
33
     * That statistic is cached for the day, to avoid unecessary calls to Matomo API.
34
     *
35
     * @param WelcomeBlockModule $module
36
     * @param int $block_id
37
     * @return int|NULL
38
     */
39
    public function visitsThisYear(WelcomeBlockModule $module, int $block_id): ?int
40
    {
41
        return Registry::cache()->file()->remember(
0 ignored issues
show
Bug Best Practice introduced by
The expression return Fisharebest\Webtr...(Carbon\Carbon::now())) returns the type Fisharebest\Webtrees\T which is incompatible with the type-hinted return integer|null.
Loading history...
42
            $module->name() . '-matomovisits-yearly-' . $block_id,
43
            function () use ($module, $block_id): ?int {
44
                $visits_year = $this->visits($module, $block_id, 'year');
45
                if ($visits_year === null) {
46
                    return null;
47
                }
48
                $visits_today = (int) $this->visits($module, $block_id, 'day');
49
50
                return $visits_year - $visits_today;
51
            },
52
            Carbon::now()->addDay()->startOfDay()->diffInSeconds(Carbon::now()) // Valid until midnight
53
        );
54
    }
55
56
    /**
57
     * Returns the number of visits for the current day.
58
     *
59
     * @param WelcomeBlockModule $module
60
     * @param int $block_id
61
     * @return int|NULL
62
     */
63
    public function visitsToday(WelcomeBlockModule $module, int $block_id): ?int
64
    {
65
        return Registry::cache()->array()->remember(
0 ignored issues
show
Bug Best Practice introduced by
The expression return Fisharebest\Webtr...ion(...) { /* ... */ }) returns the type Fisharebest\Webtrees\T which is incompatible with the type-hinted return integer|null.
Loading history...
66
            $module->name() . '-matomovisits-daily-' . $block_id,
67
            function () use ($module, $block_id): ?int {
68
                return $this->visits($module, $block_id, 'day');
69
            }
70
        );
71
    }
72
73
    /**
74
     * Invoke the Matomo API to retrieve the number of visits over a period.
75
     *
76
     * @param WelcomeBlockModule $module
77
     * @param int $block_id
78
     * @param string $period
79
     * @return int|NULL
80
     */
81
    protected function visits(WelcomeBlockModule $module, int $block_id, string $period): ?int
82
    {
83
        $settings = $module->matomoSettings($block_id);
84
85
        if (
86
            $settings['matomo_enabled'] === true
87
            && mb_strlen($settings['matomo_url']) > 0
88
            && mb_strlen($settings['matomo_token']) > 0
89
            && $settings['matomo_siteid'] > 0
90
        ) {
91
            try {
92
                $http_client = new Client([
93
                    RequestOptions::TIMEOUT => 30
94
                ]);
95
96
                $response = $http_client->get($settings['matomo_url'], [
97
                    'query' =>  [
98
                        'module'    =>  'API',
99
                        'method'    =>  'VisitsSummary.getVisits',
100
                        'idSite'    =>  $settings['matomo_siteid'],
101
                        'period'    =>  $period,
102
                        'date'      =>  'today',
103
                        'token_auth' =>  $settings['matomo_token'],
104
                        'format'    =>  'json'
105
                    ]
106
                ]);
107
108
                if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
109
                    $result = json_decode((string) $response->getBody(), true)['value'] ?? null;
110
                    if ($result !== null) {
111
                        return (int)$result;
112
                    }
113
                }
114
            } catch (GuzzleException $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
115
            }
116
        }
117
118
        return null;
119
    }
120
}
121