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
|
|
|
* |
64
|
|
|
* @throws SlackApiException |
65
|
|
|
*/ |
66
|
|
|
public function handleResponse(ResponseInterface $response): void |
67
|
|
|
{ |
68
|
|
|
$code = $response->getStatusCode(); |
69
|
|
|
$phrase = $response->getReasonPhrase(); |
70
|
|
|
$body = $response->getBody()->__toString(); |
71
|
|
|
|
72
|
|
|
if (isset(self::ERROR_TO_EXCEPTION_MAPPING[$code][$phrase][$body])) { |
73
|
|
|
$exceptionClass = self::ERROR_TO_EXCEPTION_MAPPING[$code][$phrase][$body]; |
74
|
|
|
throw new $exceptionClass($body, $code); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|