-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathResolver.php
More file actions
83 lines (76 loc) · 2.68 KB
/
Resolver.php
File metadata and controls
83 lines (76 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
namespace Platformsh\Client\Model\Ref;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Psr7\Utils;
class Resolver
{
private ClientInterface $client;
private string $baseUrl;
/**
* @param ClientInterface $client An authenticated Guzzle HTTP client.
* @param string $baseUrl The API base URL (for making URLs absolute).
*/
public function __construct(ClientInterface $client, string $baseUrl)
{
$this->client = $client;
$this->baseUrl = $baseUrl;
}
/**
* Resolves HAL reference links in resource data.
*
* @param array $data
* Data from a resource or collection, containing HAL links.
*
* @return array
* The $data modified.
*/
public function resolveReferences(array $data): array
{
if (! isset($data['_links'])) {
return $data;
}
foreach ($data['_links'] as $key => $link) {
if (str_starts_with($key, 'ref:') && \count($parts = \explode(':', $key, 3)) === 3) {
$set = $parts[1];
$linkUri = Utils::uriFor($link['href']);
$absoluteUrl = Utils::uriFor($this->baseUrl)->withPath($linkUri->getPath())->withQuery($linkUri->getQuery());
if (! isset($data['ref:' . $set])) {
$data['ref:' . $set] = [];
}
$data['ref:' . $set] += \GuzzleHttp\Utils::jsonDecode((string) $this->client->get($absoluteUrl)->getBody(), true);
unset($data['_links'][$key]);
}
}
// Transform arrays into objects.
if (isset($data['ref:users'])) {
foreach ($data['ref:users'] as &$item) {
if ($item !== null && ! $item instanceof UserRef) {
$item = UserRef::fromData($item);
}
}
}
if (isset($data['ref:organizations'])) {
foreach ($data['ref:organizations'] as &$item) {
if ($item !== null && ! $item instanceof OrganizationRef) {
$item = OrganizationRef::fromData($item);
}
}
}
if (isset($data['ref:projects'])) {
foreach ($data['ref:projects'] as &$item) {
if ($item !== null && ! $item instanceof ProjectRef) {
$item = ProjectRef::fromData($item);
}
}
}
if (isset($data['ref:teams'])) {
foreach ($data['ref:teams'] as &$item) {
if ($item !== null && ! $item instanceof TeamRef) {
$item = TeamRef::fromData($item);
}
}
}
return $data;
}
}