Passed
Push — master ( c86b68...6e4e21 )
by Patrick
01:30 queued 12s
created

MattermostApi::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 2
dl 0
loc 2
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
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, 512, 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 1
        $wrapPromise = new Promise(function () use ($postsQueryDto, &$wrapPromise) {
59 1
            $res = $this->guzzleClient->requestAsync(
60 1
                'GET',
61 1
                sprintf(self::POSTS_API, $postsQueryDto->channelId),
62
                [
63 1
                    'query' => ['since' => (int) $postsQueryDto->since->format('U') * 1000],
64
                    'headers' => [
65 1
                        'Authorization' => 'Bearer '.static::$token,
66 1
                        'Content-Type' => 'application/json',
67
                    ],
68
                ],
69 1
            )->wait();
70
71 1
            $wrapPromise->resolve(json_decode((string) $res->getBody(), true, 512, JSON_THROW_ON_ERROR)['posts']);
72 1
        });
73
74 1
        return $wrapPromise;
75
    }
76
77 2
    private function auth(): string
78
    {
79 2
        if ('' !== static::$token) {
80 2
            return static::$token;
81
        }
82
        $res = $this->guzzleClient->request(
83
            'POST',
84
            self::AUTH_API,
85
            [
86
                'body' => json_encode(
87
                    [
88
                        'login_id' => $this->mattermostConfigDto->username,
89
                        'password' => $this->mattermostConfigDto->password,
90
                    ],
91
                    JSON_THROW_ON_ERROR
92
                ),
93
            ],
94
        );
95
        $token = $res->getHeader('token');
96
        if (0 === \count($token)) {
97
            throw new \Exception('could not auth to mattermost');
98
        }
99
        static::$token = $token[0];
100
101
        return static::$token;
102
    }
103
104 1
    private function applyChannelFilter(
105
        array $channelArray,
106
        array $channelFilterCollection
107
    ): array {
108 1
        foreach ($channelFilterCollection as $channelFilter) {
109 1
            $channelArray = $channelFilter->apply($channelArray);
110
        }
111
112 1
        return $channelArray;
113
    }
114
}
115