MattermostApi::getChannel()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 1

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 1
eloc 12
c 4
b 0
f 0
nc 1
nop 1
dl 0
loc 21
ccs 13
cts 13
cp 1
crap 1
rs 9.8666
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of forecast.it.fill project.
7
 * (c) Patrick Jaja <[email protected]>
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace ForecastAutomation\MattermostClient\Business;
13
14
use ForecastAutomation\MattermostClient\Shared\Dto\MattermostConfigDto;
15
use ForecastAutomation\MattermostClient\Shared\Dto\MattermostPostsQueryDto;
16
use GuzzleHttp\Client;
17
use GuzzleHttp\Promise\Promise;
18
use GuzzleHttp\Promise\PromiseInterface;
19
20
class MattermostApi
21
{
22
    private const AUTH_API = '/api/v4/users/login';
23
    private const CHANNEL_API = '/api/v4/users/me/teams/%s/channels';
24
    private const POSTS_API = '/api/v4/channels/%s/posts';
25
26
    public static string $token = '';
27
28 2
    public function __construct(private Client $guzzleClient, private MattermostConfigDto $mattermostConfigDto)
29
    {
30 2
    }
31
32 1
    public function getChannel(array $channelFilterCollection): PromiseInterface
33
    {
34 1
        $this->auth();
35
36 1
        $wrapPromise = new Promise(function () use ($channelFilterCollection, &$wrapPromise) {
37 1
            $res = $this->guzzleClient->requestAsync(
38 1
                'GET',
39 1
                sprintf(self::CHANNEL_API, $this->mattermostConfigDto->teamId),
40
                [
41
                    'headers' => [
42 1
                        'Authorization' => 'Bearer '.static::$token,
43 1
                        'Content-Type' => 'application/json',
44
                    ],
45
                ]
46 1
            )->wait();
47
48 1
            $channelArray = json_decode((string) $res->getBody(), null, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_THROW_ON_ERROR);
49 1
            $wrapPromise->resolve($this->applyChannelFilter($channelArray, $channelFilterCollection));
50 1
        });
51
52 1
        return $wrapPromise;
53
    }
54
55 1
    public function getPosts(MattermostPostsQueryDto $postsQueryDto): PromiseInterface
56
    {
57 1
        $this->auth();
58
59 1
        $wrapPromise = new Promise(function () use ($postsQueryDto, &$wrapPromise) {
60 1
            $res = $this->guzzleClient->requestAsync(
61 1
                'GET',
62 1
                sprintf(self::POSTS_API, $postsQueryDto->channelId),
63
                [
64 1
                    'query' => ['since' => (int) $postsQueryDto->since->format('U') * 1000],
65
                    'headers' => [
66 1
                        'Authorization' => 'Bearer '.static::$token,
67 1
                        'Content-Type' => 'application/json',
68
                    ],
69
                ],
70 1
            )->wait();
71
72 1
            $wrapPromise->resolve(json_decode((string) $res->getBody(), true, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_THROW_ON_ERROR)['posts']);
73 1
        });
74
75 1
        return $wrapPromise;
76
    }
77
78 2
    private function auth(): string
79
    {
80 2
        if ('' !== static::$token) {
81 2
            return static::$token;
82
        }
83
        $res = $this->guzzleClient->request(
84
            'POST',
85
            self::AUTH_API,
86
            [
87
                'body' => json_encode(
88
                    [
89
                        'login_id' => $this->mattermostConfigDto->username,
90
                        'password' => $this->mattermostConfigDto->password,
91
                    ],
92
                    JSON_THROW_ON_ERROR
93
                ),
94
            ],
95
        );
96
        $token = $res->getHeader('token');
97
        if (0 === \count($token)) {
98
            throw new \Exception('could not auth to mattermost');
99
        }
100
        static::$token = $token[0];
101
102
        return static::$token;
103
    }
104
105 1
    private function applyChannelFilter(
106
        array $channelArray,
107
        array $channelFilterCollection
108
    ): array {
109 1
        foreach ($channelFilterCollection as $channelFilter) {
110 1
            $channelArray = $channelFilter->apply($channelArray);
111
        }
112
113 1
        return $channelArray;
114
    }
115
}
116