Completed
Pull Request — feature/app (#5)
by Yo
02:07
created

CustomExceptionCreator::createFor()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 3
nop 1
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 4
rs 9.2
c 0
b 0
f 0
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 3
    public function createFor(\Exception $exception) : JsonRpcExceptionInterface
24
    {
25 3
        $errorCode = (int) $exception->getCode();
26 3
        if ($errorCode < self::MIN_VALID_ERROR_CODE || $errorCode > self::MAX_VALID_ERROR_CODE) {
27 1
            return new JsonRpcInternalErrorException($exception);
28
        }
29
30 2
        $data = [];
31
32 2
        if ($exception->getPrevious()) {
33 1
            $data[self::ERROR_DATA_PREVIOUS_KEY] = $exception->getPrevious();
34
        }
35
36 2
        return new JsonRpcException($errorCode, $exception->getMessage(), $data);
37
    }
38
}
39