Test Failed
Branch develop (f5dd78)
by Ludwig
04:37
created

Client.php (2 issues)

1
<?php
2
3
/*
4
 * This file is part of the CwdPowerDNS Client
5
 *
6
 * (c) 2018 cwd.at GmbH <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cwd\PowerDNSClient;
15
16
use GuzzleHttp\Psr7\Request;
17
use Http\Client\HttpClient;
18
use Http\Discovery\HttpClientDiscovery;
19
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
20
use Symfony\Component\Serializer\Encoder\JsonEncoder;
21
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
22
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
23
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
24
use Symfony\Component\Serializer\Serializer;
25
use GuzzleHttp\Client as GuzzleClient;
26
27
class Client
28
{
29
    private $basePath = 'api/v1';
30
    private $serverId = 'localhost';
0 ignored issues
show
The private property $serverId is not used, and could be removed.
Loading history...
31
    private $apiKey;
32
33
    /** @var HttpClient */
34
    private $client;
35
36
    /** @var Serializer */
37
    private $serializer;
38
39
    public function __construct($apiHost, $apiKey, ?GuzzleClient $client = null)
40
    {
41
        if (null === $client) {
42
            $this->client = HttpClientDiscovery::find();
43
        }
44
        $this->apiKey = $apiKey;
45
        $this->apiUri = sprintf('%s/%s', $apiHost, $this->basePath);
0 ignored issues
show
Bug Best Practice introduced by
The property apiUri does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
46
47
        $normalizer = new ObjectNormalizer(null, new CamelCaseToSnakeCaseNameConverter(), null, new ReflectionExtractor());
48
        $this->serializer = new Serializer([new DateTimeNormalizer(), $normalizer], ['json' => new JsonEncoder()]);
49
    }
50
51
    /**
52
     * @param string|null     $payload
53
     * @param int|string|null $id
54
     * @param string          $endpoint
55
     * @param string|null     $hydrationClass
56
     * @param bool            $isList
57
     * @param string          $method
58
     *
59
     * @throws \Http\Client\Exception
60
     * @throws \LogicException
61
     *
62
     * @return mixed
63
     */
64
    public function call($payload = null, $uri, $hydrationClass = null, $isList = false, $method = 'GET', array $queryParams = [])
65
    {
66
        $uri = sprintf('%s/%s?%s', $this->apiUri, $uri, http_build_query($queryParams));
67
        $uri = rtrim($uri, '/');
68
69
        $request = new Request($method, $uri, [
70
            'X-API-Key' => $this->apiKey,
71
            'Content-Type' => 'application/json',
72
        ], $payload);
73
74
        $response = $this->client->sendRequest($request);
75
        $responseBody = $response->getBody()->getContents();
76
        $responseData = json_decode($responseBody);
77
78
        //if (getenv('DEBUG')) {
79
        //    dump([$uri, $method, isset($responseData->error) ? $responseData->error : [], $response->getStatusCode()]);
80
        //}
81
82
        if ($response->getStatusCode() >= 300 && isset($responseData->error)) {
83
            throw new \LogicException(sprintf('Error on %s request %s: %s', $method, $uri, $responseData->error));
84
        } elseif ($response->getStatusCode() >= 300) {
85
            $message = isset($responseData->message) ?? 'Unknown';
86
            throw new \Exception(sprintf('Error on request %s: %s', $response->getStatusCode(), $message));
87
        }
88
89
        if (null !== $hydrationClass && class_exists($hydrationClass)) {
90
            return $this->denormalizeObject($hydrationClass, $responseData, $isList);
91
        } elseif (null !== $hydrationClass && !class_exists($hydrationClass)) {
92
            throw new \Exception(sprintf('HydrationClass (%s) does not exist', $hydrationClass));
93
        }
94
95
        return $responseData;
96
    }
97
98
    public function denormalizeObject($hydrationClass, $dataObject, $isList = false)
99
    {
100
        if (!$isList) {
101
            $dataObject = [$dataObject];
102
        }
103
104
        $result = [];
105
106
        foreach ($dataObject as $data) {
107
            $result[] = $this->serializer->denormalize($data, $hydrationClass, null, [
108
                ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true,
109
            ]);
110
        }
111
112
        if ($isList) {
113
            return $result;
114
        }
115
116
        return current($result);
117
    }
118
119
    /**
120
     * @return Serializer
121
     */
122
    public function getSerializer(): Serializer
123
    {
124
        return $this->serializer;
125
    }
126
}
127