Completed
Push — master ( 007d53...6e7711 )
by Sébastien
06:15
created

Client::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Sebdesign\ArtisanCloudflare;
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<string,\Sebdesign\ArtisanCloudflare\Zone>  $zones
51
     * @return \Illuminate\Support\Collection<string,\Sebdesign\ArtisanCloudflare\Zone>
52
     */
53
    public function purge($zones)
54
    {
55
        return $zones->map(function (Zone $zone, $identifier) {
56
            return $this->delete($identifier, $zone);
57
        })->pipe(function ($promises) {
58
            return $this->settle($promises);
59
        })->wait();
60
    }
61
62
    /**
63
     * @param  string                             $identifier
64
     * @param  \Sebdesign\ArtisanCloudflare\Zone  $zone
65
     * @return \GuzzleHttp\Promise\PromiseInterface
66
     */
67
    protected function delete($identifier, Zone $zone)
68
    {
69
        return $this->client->deleteAsync("zones/{$identifier}/purge_cache", [
70
            \GuzzleHttp\RequestOptions::JSON => $zone,
71
        ]);
72
    }
73
74
    /**
75
     * Returns a promise that is fulfilled when all of the provided promises have
76
     * been fulfilled or rejected.
77
     *
78
     * The returned promise is fulfilled with a collection of results.
79
     *
80
     * @param  \Illuminate\Support\Collection<string,\GuzzleHttp\Promise\PromiseInterface> $promises
81
     * @return \GuzzleHttp\Promise\PromiseInterface
82
     */
83
    protected function settle(Collection $promises)
84
    {
85
        $results = new Collection();
86
87
        return Promise\each(
0 ignored issues
show
Deprecated Code introduced by
The function each() has been deprecated: 7.2 ( Ignorable by Annotation )

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

87
        return /** @scrutinizer ignore-deprecated */ Promise\each(

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
88
            $promises->getIterator(),
0 ignored issues
show
Bug introduced by
$promises->getIterator() of type ArrayIterator is incompatible with the type array expected by parameter $array of each(). ( Ignorable by Annotation )

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

88
            /** @scrutinizer ignore-type */ $promises->getIterator(),
Loading history...
89
            $this->onFulfilled($results),
0 ignored issues
show
Unused Code introduced by
The call to each() has too many arguments starting with $this->onFulfilled($results). ( Ignorable by Annotation )

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

89
        return /** @scrutinizer ignore-call */ Promise\each(

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

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