Issues (9)

src/Client.php (1 issue)

1
<?php
2
3
namespace Cion\LaravelCloudflare;
4
5
use GuzzleHttp\Promise;
6
use Psr\Log\LoggerInterface;
7
use Illuminate\Support\Collection;
8
use GuzzleHttp\Client as GuzzleClient;
9
use Psr\Http\Message\ResponseInterface;
10
use GuzzleHttp\Exception\ClientException;
11
use GuzzleHttp\Exception\RequestException;
12
13
class Client
14
{
15
    /**
16
     * Base URI.
17
     */
18
    const BASE_URI = 'https://api.cloudflare.com/client/v4/';
19
20
    /**
21
     * @var \GuzzleHttp\Client
22
     */
23
    protected $client;
24
25
    /**
26
     * @var \Psr\Log\LoggerInterface
27
     */
28
    protected $logger;
29
30
    /**
31
     * Constructor.
32
     *
33
     * @param \GuzzleHttp\Client       $client
34
     * @param \Psr\Log\LoggerInterface $logger
35
     */
36
    public function __construct(GuzzleClient $client, LoggerInterface $logger)
37
    {
38
        $this->client = $client;
39
        $this->logger = $logger;
40
    }
41
42
    /**
43
     * Delete all the given zones with their parameters.
44
     *
45
     * All the requests are asynchronous and sent concurrently.
46
     *
47
     * The promise waits until all the promises have been resolved or rejected
48
     * and returns the results of each request.
49
     *
50
     * @param  \Illuminate\Support\Collection|array[]  $parameters
51
     * @return \Illuminate\Support\Collection|\stdClass[]
52
     */
53
    public function purge(Collection $parameters)
54
    {
55
        $promises = $parameters->map(function ($parameters, $identifier) {
56
            return $this->client->deleteAsync("zones/{$identifier}/purge_cache", [
57
                \GuzzleHttp\RequestOptions::JSON => $parameters,
58
            ]);
59
        });
60
61
        return $this->settle($promises)->wait();
62
    }
63
64
    /**
65
     * Returns a promise that is fulfilled when all of the provided promises have
66
     * been fulfilled or rejected.
67
     *
68
     * The returned promise is fulfilled with a collection of results.
69
     *
70
     * @param  \Illuminate\Support\Collection|\GuzzleHttp\Promise\PromiseInterface[] $promises
71
     * @return \GuzzleHttp\Promise\PromiseInterface
72
     */
73
    protected function settle(Collection $promises)
74
    {
75
        $results = collect();
76
77
        return Promise\each(
78
            $promises->toArray(),
0 ignored issues
show
$promises->toArray() cannot be passed to each() as the parameter $array expects a reference. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

78
            /** @scrutinizer ignore-type */ $promises->toArray(),
Loading history...
79
            $this->onFulfilled($results),
80
            $this->onRejected($results)
81
        )->then(function () use ($results) {
82
            return $results;
83
        });
84
    }
85
86
    /**
87
     * Put the body of the fulfilled promise into the results.
88
     *
89
     * @param  \Illuminate\Support\Collection|object[] $results
90
     * @return \Closure
91
     */
92
    protected function onFulfilled(Collection $results)
93
    {
94
        return function ($response, $identifier) use ($results) {
95
            return $results->put($identifier, $this->getBody($response));
96
        };
97
    }
98
99
    /**
100
     * Handle the rejected promise and put the errors into the results.
101
     *
102
     * @param  \Illuminate\Support\Collection|object[] $results
103
     * @return \Closure
104
     */
105
    protected function onRejected(Collection $results)
106
    {
107
        return function ($reason, $identifier) use ($results) {
108
            $this->logger->error($reason->getMessage(), [
109
                'zone' => $identifier,
110
                'exception' => $reason,
111
            ]);
112
113
            return $results->put($identifier, $this->handleException($reason));
114
        };
115
    }
116
117
    /**
118
     * Transform a request exception into a result object.
119
     *
120
     * @param  \GuzzleHttp\Exception\RequestException $e
121
     * @return \stdClass
122
     */
123
    protected function handleException(RequestException $e)
124
    {
125
        if ($e->hasResponse()) {
126
            /** @var \Psr\Http\Message\ResponseInterface $response */
127
            $response = $e->getResponse();
128
129
            if ($e instanceof ClientException) {
130
                return $this->getBody($response);
131
            }
132
133
            $message = (string) $response->getBody();
134
        } else {
135
            $message = $e->getMessage();
136
        }
137
138
        $result = [
139
            'success' => false,
140
            'errors' => [
141
                (object) [
142
                    'code' => $e->getCode(),
143
                    'message' => $message,
144
                ],
145
            ],
146
        ];
147
148
        return (object) $result;
149
    }
150
151
    /**
152
     * Transform the response body into a result object.
153
     *
154
     * @param  \Psr\Http\Message\ResponseInterface $response
155
     * @return \stdClass
156
     */
157
    protected function getBody(ResponseInterface $response)
158
    {
159
        return json_decode($response->getBody(), false);
160
    }
161
162
    /**
163
     * Get the Guzzle client.
164
     *
165
     * @return \GuzzleHttp\ClientInterface
166
     */
167
    public function getClient()
168
    {
169
        return $this->client;
170
    }
171
}
172