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

ErrorResponseHandler::handleResponse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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