Passed
Pull Request — master (#51)
by Youri
02:27
created

ErrorResponseHandler   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 45
rs 10
c 0
b 0
f 0
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A handleResponse() 0 9 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Nexylan packages.
7
 *
8
 * (c) Nexylan SAS <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Nexy\Slack;
15
16
use Nexy\Slack\Exception\ActionProhibitedException;
17
use Nexy\Slack\Exception\ChannelIsArchivedException;
18
use Nexy\Slack\Exception\ChannelNotFoundException;
19
use Nexy\Slack\Exception\InvalidPayloadException;
20
use Nexy\Slack\Exception\RollupErrorException;
21
use Nexy\Slack\Exception\SlackApiException;
22
use Nexy\Slack\Exception\UserNotFoundException;
23
24
use Psr\Http\Message\ResponseInterface;
25
26
class ErrorResponseHandler
27
{
28
    // Mapping based on: "https://api.slack.com/changelog/2016-05-17-changes-to-errors-for-incoming-webhooks"
29
    private const ERROR_TO_EXCEPTION_MAPPING = [
30
        400 => [
31
            'Bad Request' => [
32
                'invalid_payload' => InvalidPayloadException::class,
33
                'user_not_found' => UserNotFoundException::class,
34
            ]
35
        ],
36
        403 => [
37
            'Forbidden' => [
38
                'action_prohibited' => ActionProhibitedException::class
39
            ]
40
        ],
41
        404 => [
42
            'Not Found' => [
43
                'channel_not_found' => ChannelNotFoundException::class
44
            ]
45
        ],
46
        410 => [
47
            'Gone' => [
48
                'channel_is_archived' => ChannelIsArchivedException::class
49
            ]
50
        ],
51
        500 => [
52
            'Server Error' => [
53
                'rollup_error' => RollupErrorException::class
54
            ]
55
        ]
56
    ];
57
58
    /**
59
     * @param ResponseInterface $response
60
     * @throws SlackApiException
61
     */
62
    public function handleResponse(ResponseInterface $response): void
63
    {
64
        $code = $response->getStatusCode();
65
        $phrase = $response->getReasonPhrase();
66
        $body = $response->getBody()->__toString();
67
68
        if (isset(self::ERROR_TO_EXCEPTION_MAPPING[$code][$phrase][$body])) {
69
            $exceptionClass = self::ERROR_TO_EXCEPTION_MAPPING[$code][$phrase][$body];
70
            throw new $exceptionClass($body, $code);
71
        }
72
    }
73
}
74