1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace OpenStack\Common\Transport; |
4
|
|
|
|
5
|
|
|
use function GuzzleHttp\Psr7\uri_for; |
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
7
|
|
|
use Psr\Http\Message\UriInterface; |
8
|
|
|
|
9
|
|
|
class Utils |
10
|
|
|
{ |
11
|
102 |
|
public static function jsonDecode(ResponseInterface $response) |
12
|
|
|
{ |
13
|
|
|
$jsonErrors = [ |
14
|
102 |
|
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded', |
15
|
102 |
|
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch', |
16
|
102 |
|
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found', |
17
|
102 |
|
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON', |
18
|
102 |
|
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded' |
19
|
102 |
|
]; |
20
|
|
|
|
21
|
102 |
|
$data = json_decode((string) $response->getBody(), true); |
22
|
|
|
|
23
|
102 |
|
if (JSON_ERROR_NONE !== json_last_error()) { |
24
|
1 |
|
$last = json_last_error(); |
25
|
1 |
|
throw new \InvalidArgumentException( |
26
|
1 |
|
'Unable to parse JSON data: ' . (isset($jsonErrors[$last]) ? $jsonErrors[$last] : 'Unknown error') |
27
|
1 |
|
); |
28
|
|
|
} |
29
|
|
|
|
30
|
101 |
|
return $data; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Method for flattening a nested array. |
35
|
|
|
* |
36
|
|
|
* @param array $data The nested array |
37
|
|
|
* @param null $key The key to extract |
38
|
|
|
* |
39
|
|
|
* @return array |
40
|
|
|
*/ |
41
|
82 |
|
public static function flattenJson($data, $key = null) |
42
|
|
|
{ |
43
|
82 |
|
return (!empty($data) && $key && isset($data[$key])) ? $data[$key] : $data; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Method for normalize an URL string. |
48
|
|
|
* |
49
|
|
|
* Append the http:// prefix if not present, and add a |
50
|
|
|
* closing url separator when missing. |
51
|
|
|
* |
52
|
|
|
* @param string $url The url representation. |
53
|
|
|
* |
54
|
|
|
* @return string |
55
|
|
|
*/ |
56
|
6 |
|
public static function normalizeUrl($url) |
57
|
|
|
{ |
58
|
6 |
|
if (strpos($url, 'http') === false) { |
59
|
6 |
|
$url = 'http://' . $url; |
60
|
6 |
|
} |
61
|
|
|
|
62
|
6 |
|
return rtrim($url, '/') . '/'; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Add an unlimited list of paths to a given URI. |
67
|
|
|
* |
68
|
|
|
* @param UriInterface $uri |
69
|
|
|
* @param ...$paths |
70
|
|
|
* |
71
|
|
|
* @return UriInterface |
72
|
|
|
*/ |
73
|
2 |
|
public static function addPaths(UriInterface $uri, ...$paths) |
74
|
|
|
{ |
75
|
2 |
|
return uri_for(rtrim((string) $uri, '/') . '/' . implode('/', $paths)); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|