ErrorExceptionPlugin::handleRequest()   A
last analyzed

Complexity

Conditions 5
Paths 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.2568
c 0
b 0
f 0
cc 5
nc 1
nop 3
1
<?php
2
namespace SafeCrow\Plugin;
3
4
use Http\Client\Common\Plugin;
5
use Http\Promise\Promise;
6
use Psr\Http\Message\RequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use SafeCrow\Exception\CustomErrorException;
9
use SafeCrow\Exception\NotFoundResultException;
10
use SafeCrow\Exception\UndefinedResultException;
11
12
class ErrorExceptionPlugin implements Plugin
13
{
14
    /**
15
     * @var int
16
     */
17
    const STATUS_OK = 200;
18
19
    /**
20
     * @var int
21
     */
22
    const STATUS_NOT_FOUND = 404;
23
24
    /**
25
     * @var int
26
     */
27
    const STATUS_ERROR = 418;
28
29
30
    /**
31
     * @param RequestInterface $request
32
     * @param callable         $next
33
     * @param callable         $first
34
     * @return Promise
35
     */
36
    public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
37
    {
38
        return $next($request)->then(function (ResponseInterface $response) {
39
            switch ($response->getStatusCode()) {
40
                case self::STATUS_OK:
41
                    return $response;
42
                case self::STATUS_NOT_FOUND:
43
                    throw new NotFoundResultException('Result not found.');
44
                case self::STATUS_ERROR:
45
                    $result = json_decode($response->getBody(), true);
46
                    $errors = (array) reset($result['errors']);
47
48
                    foreach ($errors as $field => $error) {
49
                        $errors[$field] = "Field `{$field}` has error `{$error}`";
50
                    }
51
52
                    throw new CustomErrorException(implode(', ', $errors));
53
            }
54
55
            throw new UndefinedResultException(sprintf('Undefined result. Response Status: %s.', $response->getStatusCode()));
56
        });
57
    }
58
}
59