forked from deployphp/recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudflare.php
86 lines (66 loc) · 2.19 KB
/
cloudflare.php
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
84
85
86
<?php
/* (c) David Jordan / CyberDuck <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Deployer;
desc('Clearing Cloudflare Cache');
task('deploy:cloudflare', function () {
$config = get('cloudflare', []);
//validate config and set headers
if (!empty($config['service_key'])) {
$headers = [
'X-Auth-User-Service-Key' => $config['service_key']
];
} elseif (!empty($config['email']) && !empty($config['api_key'])) {
$headers = [
'X-Auth-Key' => $config['api_key'],
'X-Auth-Email' => $config['email']
];
} else {
throw new \RuntimeException("Set a service key or email / api key");
}
$headers['Content-Type'] = 'application/json';
if (empty($config['domain'])) {
throw new RuntimeException("Set a domain");
}
$makeRequest = function ($url, $opts = []) use ($headers) {
$ch = curl_init("https://api.cloudflare.com/client/v4/$url");
foreach($headers as $key => $value){
$parsedHeaders[] = "$key: $value";
}
curl_setopt_array($ch, [
CURLOPT_HTTPHEADER => $parsedHeaders,
CURLOPT_RETURNTRANSFER => true
]);
curl_setopt_array($ch, $opts);
$res = curl_exec($ch);
if (curl_errno($ch)) {
throw new \RuntimeException("Error making curl request (result: $res)");
}
curl_close($ch);
return $res;
};
// get the mysterious zone id from Cloud Flare
$zones = json_decode($makeRequest(
"zones?name={$config['domain']}"
), true);
if (empty($zones['success']) || !empty($zones['errors'])) {
throw new \RuntimeException("Problem with zone data");
} else {
$zoneId = current($zones['result'])['id'];
}
// make purge request
$makeRequest(
"zones/$zoneId/purge_cache",
[
CURLOPT_CUSTOMREQUEST => 'DELETE',
CURLOPT_POSTFIELDS => json_encode(
[
'purge_everything' => true
]
),
]
);
});