MountebankExceptionFactory::createInstance()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 4
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Meare\Juggler\Exception;
4
5
6
use Meare\Juggler\Exception\Mountebank\MountebankException;
7
8
class MountebankExceptionFactory
9
{
10
    const ERROR_BAD_DATA = 'bad data';
11
    const ERROR_INVALID_INJECTION = 'invalid injection';
12
    const ERROR_RESOURCE_CONFLICT = 'resource conflict';
13
    const ERROR_INSUFFICIENT_ACCESS = 'insufficient access';
14
    const ERROR_INVALID_PROXY = 'invalid proxy';
15
    const ERROR_NO_SUCH_RESOURCE = 'no such resource';
16
    const ERROR_INVALID_JSON = 'invalid JSON';
17
18
    /**
19
     * @var array
20
     */
21
    private $errorMap = [
22
        self::ERROR_BAD_DATA            => Mountebank\BadDataException::class,
23
        self::ERROR_INVALID_INJECTION   => Mountebank\InvalidInjectionException::class,
24
        self::ERROR_RESOURCE_CONFLICT   => Mountebank\ResourceConflictException::class,
25
        self::ERROR_INSUFFICIENT_ACCESS => Mountebank\InsufficientAccessException::class,
26
        self::ERROR_INVALID_PROXY       => Mountebank\InvalidProxyException::class,
27
        self::ERROR_NO_SUCH_RESOURCE    => Mountebank\NoSuchResourceException::class,
28
        self::ERROR_INVALID_JSON        => Mountebank\InvalidJsonException::class,
29
    ];
30
31
    /**
32
     * Takes first error from mountebank response and wraps it into according MountebankException
33
     *
34
     * @param string $response_body
35
     * @return MountebankException
36
     */
37 1
    public function createInstanceFromMountebankResponse($response_body)
38
    {
39 1
        $errors = \GuzzleHttp\json_decode($response_body, true)['errors'];
40 1
        $first_error = reset($errors);
41
42 1
        return $this->createInstance(
43 1
            $first_error['code'],
44 1
            $first_error['message'],
45 1
            isset($first_error['source']) ? $first_error['source'] : null,
46 1
            isset($first_error['data']) ? $first_error['data'] : null
47 1
        );
48
    }
49
50
    /**
51
     * @param string $error_code
52
     * @param string $message
53
     * @param string $source
54
     * @param string $data
55
     * @return MountebankException
56
     */
57 2
    public function createInstance($error_code, $message, $source = null, $data = null)
58
    {
59 2
        if (!isset($this->errorMap[$error_code])) {
60 1
            throw new \InvalidArgumentException('Unable to instantiate MountebankException; ' .
61 1
                "no class found for mountebank error code '$error_code'");
62
        }
63 1
        $exception_class = $this->errorMap[$error_code];
64
65 1
        return new $exception_class($message, $source, $data);
66
    }
67
}
68