|
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
|
|
|
|