Passed
Push — main ( 9d419d...ad76dd )
by Jonathan
11:53
created

MatomoStatsService::httpHandler()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 4
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
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\HandlerStack;
22
use GuzzleHttp\RequestOptions;
23
use GuzzleHttp\Exception\GuzzleException;
24
use MyArtJaub\Webtrees\Module\WelcomeBlock\WelcomeBlockModule;
25
26
/**
27
 * Service for retrieving Matomo statistics
28
 *
29
 */
30
class MatomoStatsService
31
{
32
    protected ?HandlerStack $handler = null;
33
34
    /**
35
     * Set or get the http handler for the service
36
     *
37
     * @param HandlerStack $handler
38
     * @return HandlerStack
39
     */
40
    public function httpHandler(HandlerStack $handler = null): HandlerStack
41
    {
42
        if ($this->handler === null) {
43
            $this->handler = HandlerStack::create();
44
        }
45
        if ($handler !== null) {
46
            $this->handler = $handler;
47
        }
48
        return $this->handler;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->handler could return the type null which is incompatible with the type-hinted return GuzzleHttp\HandlerStack. Consider adding an additional type-check to rule them out.
Loading history...
49
    }
50
51
    /**
52
     * Returns the number of visits for the current year (up to the day before).
53
     * That statistic is cached for the day, to avoid unecessary calls to Matomo API.
54
     *
55
     * @param WelcomeBlockModule $module
56
     * @param int $block_id
57
     * @return int|NULL
58
     */
59
    public function visitsThisYear(WelcomeBlockModule $module, int $block_id): ?int
60
    {
61
        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...
62
            $module->name() . '-matomovisits-yearly-' . $block_id,
63
            function () use ($module, $block_id): ?int {
64
                $visits_year = $this->visits($module, $block_id, 'year');
65
                if ($visits_year === null) {
66
                    return null;
67
                }
68
                $visits_today = (int) $this->visits($module, $block_id, 'day');
69
70
                return $visits_year - $visits_today;
71
            },
72
            Carbon::now()->addDay()->startOfDay()->diffInSeconds(Carbon::now()) // Valid until midnight
73
        );
74
    }
75
76
    /**
77
     * Returns the number of visits for the current day.
78
     *
79
     * @param WelcomeBlockModule $module
80
     * @param int $block_id
81
     * @return int|NULL
82
     */
83
    public function visitsToday(WelcomeBlockModule $module, int $block_id): ?int
84
    {
85
        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...
86
            $module->name() . '-matomovisits-daily-' . $block_id,
87
            function () use ($module, $block_id): ?int {
88
                return $this->visits($module, $block_id, 'day');
89
            }
90
        );
91
    }
92
93
    /**
94
     * Invoke the Matomo API to retrieve the number of visits over a period.
95
     *
96
     * @param WelcomeBlockModule $module
97
     * @param int $block_id
98
     * @param string $period
99
     * @return int|NULL
100
     */
101
    protected function visits(WelcomeBlockModule $module, int $block_id, string $period): ?int
102
    {
103
        $settings = $module->matomoSettings($block_id);
104
105
        if (
106
            $settings['matomo_enabled'] === true
107
            && mb_strlen($settings['matomo_url']) > 0
108
            && mb_strlen($settings['matomo_token']) > 0
109
            && $settings['matomo_siteid'] > 0
110
        ) {
111
            try {
112
                $http_client = new Client([
113
                    RequestOptions::TIMEOUT => 30,
114
                    'handler'   => $this->handler
115
                ]);
116
117
                $response = $http_client->get($settings['matomo_url'], [
118
                    'query' =>  [
119
                        'module'    =>  'API',
120
                        'method'    =>  'VisitsSummary.getVisits',
121
                        'idSite'    =>  $settings['matomo_siteid'],
122
                        'period'    =>  $period,
123
                        'date'      =>  'today',
124
                        'token_auth' =>  $settings['matomo_token'],
125
                        'format'    =>  'json'
126
                    ]
127
                ]);
128
129
                if ($response->getStatusCode() === StatusCodeInterface::STATUS_OK) {
130
                    $result = json_decode((string) $response->getBody(), true)['value'] ?? null;
131
                    if ($result !== null) {
132
                        return (int)$result;
133
                    }
134
                }
135
            } catch (GuzzleException $ex) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
136
            }
137
        }
138
139
        return null;
140
    }
141
}
142