ResponseConverter   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 14
lcom 0
cbo 4
dl 0
loc 64
ccs 24
cts 24
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
C convert() 0 22 10
A convertToArray() 0 4 1
A convertToSimpleXml() 0 9 3
1
<?php
2
3
namespace Happyr\LinkedIn\Http;
4
5
use Happyr\LinkedIn\Exception\InvalidArgumentException;
6
use Happyr\LinkedIn\Exception\LinkedInTransferException;
7
use Psr\Http\Message\ResponseInterface;
8
9
class ResponseConverter
10
{
11
    /**
12
     * Convert a PSR-7 response to a data type you want to work with.
13
     *
14
     * @param ResponseInterface $response
15
     * @param string            $requestFormat
16
     * @param string            $dataType
17
     *
18
     * @return ResponseInterface|\Psr\Http\Message\StreamInterface|\SimpleXMLElement|string
19
     *
20
     * @throws InvalidArgumentException
21
     * @throws LinkedInTransferException
22
     */
23 5
    public static function convert(ResponseInterface $response, $requestFormat, $dataType)
24
    {
25 5
        if (($requestFormat === 'json' && $dataType === 'simple_xml') ||
26 5
            ($requestFormat === 'xml' && $dataType === 'array')) {
27 2
            throw new InvalidArgumentException('Can not use reponse data format "%s" with the request format "%s".', $dataType, $requestFormat);
28
        }
29
30
        switch ($dataType) {
31 3
            case 'array':
32 2
                return self::convertToArray($response);
33 2
            case 'string':
34 1
                return $response->getBody()->__toString();
35 2
            case 'simple_xml':
36 1
                return self::convertToSimpleXml($response);
37 2
            case 'stream':
38 1
                return $response->getBody();
39 2
            case 'psr7':
40 1
                return $response;
41 1
            default:
42 1
                throw new InvalidArgumentException('Format "%s" is not supported', $dataType);
43 1
        }
44
    }
45
46
    /**
47
     * @param ResponseInterface $response
48
     *
49
     * @return string
50
     */
51 5
    public static function convertToArray(ResponseInterface $response)
52
    {
53 5
        return json_decode($response->getBody(), true);
54
    }
55
56
    /**
57
     * @param ResponseInterface $response
58
     *
59
     * @return \SimpleXMLElement
60
     *
61
     * @throws LinkedInTransferException
62
     */
63 3
    public static function convertToSimpleXml(ResponseInterface $response)
64
    {
65 3
        $body = $response->getBody();
66
        try {
67 3
            return new \SimpleXMLElement((string) $body ?: '<root />');
68 1
        } catch (\Exception $e) {
69 1
            throw new LinkedInTransferException('Unable to parse response body into XML.');
70
        }
71
    }
72
}
73