Passed
Pull Request — master (#51)
by Youri
01:35
created

ErrorResponseHandler   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 2
eloc 24
c 4
b 0
f 0
dl 0
loc 49
rs 10

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
use Psr\Http\Message\ResponseInterface;
24
25
class ErrorResponseHandler
26
{
27
    /**
28
     * @see https://api.slack.com/changelog/2016-05-17-changes-to-errors-for-incoming-webhooks
29
     */
30
    private const ERROR_TO_EXCEPTION_MAPPING = [
31
        400 => [
32
            'Bad Request' => [
33
                'invalid_payload' => InvalidPayloadException::class,
34
                'user_not_found' => UserNotFoundException::class,
35
            ]
36
        ],
37
        403 => [
38
            'Forbidden' => [
39
                'action_prohibited' => ActionProhibitedException::class
40
            ]
41
        ],
42
        404 => [
43
            'Not Found' => [
44
                'channel_not_found' => ChannelNotFoundException::class
45
            ]
46
        ],
47
        410 => [
48
            'Gone' => [
49
                'channel_is_archived' => ChannelIsArchivedException::class
50
            ]
51
        ],
52
        500 => [
53
            'Server Error' => [
54
                'rollup_error' => RollupErrorException::class
55
            ]
56
        ]
57
    ];
58
59
    /**
60
     * Throw exception if there is an API error, do nothing otherwise
61
     *
62
     * @param ResponseInterface $response
63
     * @throws SlackApiException
64
     */
65
    public function handleResponse(ResponseInterface $response): void
66
    {
67
        $code = $response->getStatusCode();
68
        $phrase = $response->getReasonPhrase();
69
        $body = $response->getBody()->__toString();
70
71
        if (isset(self::ERROR_TO_EXCEPTION_MAPPING[$code][$phrase][$body])) {
72
            $exceptionClass = self::ERROR_TO_EXCEPTION_MAPPING[$code][$phrase][$body];
73
            throw new $exceptionClass($body, $code);
74
        }
75
    }
76
}
77