Completed
Push — release/1.0.0 ( eaae36...93eb3c )
by Yo
07:15 queued 05:10
created

CustomExceptionCreator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
B createFor() 0 17 5
1
<?php
2
namespace Yoanm\JsonRpcServer\App\Creator;
3
4
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcException;
5
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcExceptionInterface;
6
use Yoanm\JsonRpcServer\Domain\Exception\JsonRpcInternalErrorException;
7
8
/**
9
 * Class CustomExceptionCreator
10
 */
11
class CustomExceptionCreator
12
{
13
    const MAX_VALID_ERROR_CODE = -32000;
14
    const MIN_VALID_ERROR_CODE = -32099;
15
16
    const ERROR_DATA_PREVIOUS_KEY = 'previous';
17
18
    /**
19
     * @param \Exception $exception
20
     *
21
     * @return JsonRpcExceptionInterface
22
     */
23 4
    public function createFor(\Exception $exception) : JsonRpcExceptionInterface
24
    {
25 4
        if ($exception instanceof JsonRpcExceptionInterface) {
26 1
            return $exception;
27
        }
28 3
        $errorCode = (int) $exception->getCode();
29 3
        if ($errorCode < self::MIN_VALID_ERROR_CODE || $errorCode > self::MAX_VALID_ERROR_CODE) {
30 1
            return new JsonRpcInternalErrorException($exception);
31
        }
32
33 2
        $data = [];
34
35 2
        if ($exception->getPrevious()) {
36 1
            $data[self::ERROR_DATA_PREVIOUS_KEY] = $exception->getPrevious()->getMessage();
37
        }
38
39 2
        return new JsonRpcException($errorCode, $exception->getMessage(), $data);
40
    }
41
}
42