Completed
Pull Request — dev (#11)
by
unknown
04:51
created

JsonEncoder::encode()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 8.8571
cc 6
eloc 11
nc 4
nop 1
crap 6
1
<?php
2
3
namespace Vectorface\SnappyRouter\Encoder;
4
5
use Vectorface\SnappyRouter\Response\AbstractResponse;
6
use Vectorface\SnappyRouter\Exception\EncoderException;
7
8
/**
9
 * Encodes the response in the JSON format.
10
 * @copyright Copyright (c) 2014, VectorFace, Inc.
11
 * @author Dan Bruce <[email protected]>
12
 */
13
class JsonEncoder extends AbstractEncoder
14
{
15
    /**
16
     * @param AbstractResponse $response The response to be encoded.
17
     * @return (string) Returns the response encoded as a string.
18
     */
19 10
    public function encode(AbstractResponse $response)
20
    {
21 10
        $responseObject = $response->getResponseObject();
22 10
        if (null === $responseObject || is_array($responseObject) || is_scalar($responseObject)) {
23 6
            return json_encode($responseObject);
24 5
        } elseif (is_object($responseObject)) {
25 4
            if (method_exists($responseObject, 'jsonSerialize')) {
26 1
                return json_encode($responseObject->jsonSerialize());
27
            } else {
28 3
                return json_encode(get_object_vars($responseObject));
29
            }
30
        } else {
31 1
            throw new EncoderException('Unable to encode response as JSON.');
32
        }
33
    }
34
}
35