Completed
Push — master ( 877393...5ce7ef )
by Florian
14:57 queued 13:27
created

SectionIO::flushURL()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.864

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 2
cts 5
cp 0.4
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.864
1
<?php
2
3
class SectionIO extends Object implements Flushable
4
{
5
    private static $flush_on_dev_build = true;
6
7
    private static $sitetree_flush_strategy = 'single';
8
9
    private static $api_url = 'https://aperture.section.io/api/v1';
10
    private static $account_id = '';
11
    private static $application_id = '';
12
    private static $environment_name = '';
13
    private static $proxy_name = '';
14
    private static $username = '';
15
    private static $password = '';
16
    private static $verify_ssl = true;
17
18
    /**
19
     * Implementation of Flushable::flush()
20
     * Is triggered on dev/build and ?flush=1.
21
     */
22 1
    public static function flush()
23
    {
24 1
        if (Config::inst()->get('SectionIO', 'flush_on_dev_build')) {
25 1
            return static::flushAll();
26
        }
27
28 1
        return;
29
    }
30
31 3
    public static function flushAll()
32
    {
33 3
        $exp = 'obj.http.x-url ~ /';
34
35 3
        return static::performFlush($exp);
36
    }
37
38 1
    public static function flushImage($imageID)
39
    {
40 1
        $image = Image::get()->byID($imageID);
41 1
        if ($image && $image->exists()) {
42 1
            $exp = 'obj.http.x-url ~ "^/'.preg_quote($image->getFilename()).'$"'; // image itself
43 1
            $exp    .= ' || obj.http.x-url ~ "^/'.preg_quote($image->Parent()->getFilename())
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on DataObject. Did you maybe mean parentClass()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
44 1
                    .'_resampled/(.*)\-'.preg_quote($image->Name).'$"'; // resampled versions
45 1
            return static::performFlush($exp);
46
        }
47
48
        return false;
49
    }
50
51 1
    public static function flushFile($fileID)
52
    {
53 1
        $file = File::get()->byID($fileID);
54 1
        if ($file && $file->exists()) {
55 1
            $exp = 'obj.http.x-url ~ "^/'.preg_quote($file->getFilename()).'$"';
56 1
            return static::performFlush($exp);
57
        }
58
59
        return false;
60
    }
61
62 1
    public static function flushSiteTree($sitetreeID)
63
    {
64 1
        $sitetree = SiteTree::get()->byID($sitetreeID);
65 1
        if ($sitetree && $sitetree->exists()) {
66 1
            $strategy = Config::inst()->get('SectionIO', 'sitetree_flush_strategy');
67
            switch ($strategy) {
68
69 1
                case 'single':
70 1
                    $exp = 'obj.http.content-type ~ "'.preg_quote('text/html').'"';
71 1
                    $exp .= ' && obj.http.x-url ~ "^'.preg_quote($sitetree->Link()).'$"';
72 1
                    break;
73
74 1
                case 'parents':
75 1
                    $exp = 'obj.http.content-type ~ "'.preg_quote('text/html').'"';
76 1
                    $exp .= ' && (obj.http.x-url ~ "^'.preg_quote($sitetree->Link()).'$"';
77 1
                    $parent = $sitetree->getParent();
78 1
                    while ($parent && $parent->exists()) {
79 1
                        $exp .= ' || obj.http.x-url ~ "^'.preg_quote($parent->Link()).'$"';
80 1
                        $parent = $parent->getParent();
81 1
                    }
82 1
                    $exp .= ')';
83 1
                    break;
84
85 1
                case 'all':
86 1
                    $exp = 'obj.http.content-type ~ "'.preg_quote('text/html').'"';
87 1
                    break;
88
89 1
                case 'everyting':
90 1
                default:
91 1
                    $exp = 'obj.http.x-url ~ /';
92 1
                    break;
93
94 1
            }
95
96 1
            return static::performFlush($exp);
97
        }
98
99
        return false;
100
    }
101
    
102 6
    public static function flushURL($url) {
103 6
        if ($url) {
104
            $exp = 'obj.http.x-url ~ "^'.preg_quote($url).'$"';
105
            return static::performFlush($exp);
106
        }
107
        return false;
108
    }
109
110
    protected static function performFlush($banExpression)
111
    {
112
        $success = true;
113
        $urls = static::getUrls();
114
        // config loaded successfully
115
		if (static::checkConfig()) {
116
			if (count($urls) > 0) {
117
				foreach ($urls as $url) {
118
119
					// get restful service object
120
					$service = static::getService($url, $banExpression);
121
122
					// prepare headers
123
					$headers = static::getHeaders();
124
125
					// prepare curl options
126
					$options = static::getOptions();
127
128
					// call API
129
					$conn = $service->request(null, 'POST', null, $headers, $options);
130
131
					if ($conn->isError()) {
132
						SS_Log::log('SectionIO::performFlush :: '.$conn->getStatusCode().' : '.$conn->getStatusDescription().' : '.$url, SS_Log::ERR);
133
						$success = $success && false;
134
					} else {
135
						SS_Log::log('SectionIO::performFlush :: ban successful. url: '.$url."; ban expression: '".$banExpression."'", SS_Log::NOTICE);
136
					}
137
				}
138
			} else {
139
				SS_Log::log('SectionIO::performFlush :: no URLs loaded for ban.', SS_Log::ERR);
140
			}
141
		}
142
		
143
        return $success;
144
    }
145
146 6
    protected static function getService($url, $banExpression)
147
    {
148
        // prepare API call
149 6
        $service = new RestfulService(
150 6
            $url,
151
            0 // expiry time 0: do not cache the API call
152 6
        );
153
        // set basic auth
154 6
        $username = Config::inst()->get('SectionIO', 'username');
155 6
        $password = Config::inst()->get('SectionIO', 'password');
156 6
        $service->basicAuth($username, $password);
157
        // set query string (ban expression)
158 6
        $service->setQueryString(array(
159 6
            'banExpression' => $banExpression,
160 6
        ));
161
162 6
        return $service;
163
    }
164
165 6
    protected static function getOptions()
166
    {
167
        // prepare curl options for ssl verification
168 6
        if (Config::inst()->get('SectionIO', 'verify_ssl')) {
169
            return array(
170
                CURLOPT_SSL_VERIFYPEER => 0,
171
                CURLOPT_SSL_VERIFYHOST => 0,
172
            );
173
        }
174 6
        return array();
175
    }
176
177 6
    protected static function getHeaders()
178
    {
179
        $headers = array(
180 6
            'Content-Type: application/json',
181 6
            'Accept: application/json',
182 6
        );
183
184 6
        return $headers;
185
    }
186
187 6
    protected static function getUrls()
188
    {
189 6
        $urls = array();
190
191 6
        if (static::checkConfig()) {
192 6
            $api_url = Config::inst()->get('SectionIO', 'api_url');
193 6
            $account_id = Config::inst()->get('SectionIO', 'account_id');
194 6
            $application_id = Config::inst()->get('SectionIO', 'application_id');
195 6
            $application_ids = array();
196 6
            if (is_string($application_id)) {
197 6
                $application_ids = preg_split("/[\s,]+/", $application_id);
198 6
            } elseif (is_array($application_id)) {
199
                $application_ids = $application_id;
200
            }
201 6
            $environment_name = Config::inst()->get('SectionIO', 'environment_name');
202 6
            $proxy_name = Config::inst()->get('SectionIO', 'proxy_name');
203
204 6
            foreach ($application_ids as $appid) {
205
                // build API URL: /account/{accountId}/application/{applicationId}/environment/{environmentName}/proxy/{proxyName}/state
206 6
                $urls[] = Controller::join_links(
207 6
                    $api_url,
208 6
                    'account',
209 6
                    $account_id,
210 6
                    'application',
211 6
                    $appid,
212 6
                    'environment',
213 6
                    $environment_name,
214 6
                    'proxy',
215 6
                    $proxy_name,
216
                    'state'
217 6
                );
218 6
            }
219 6
        }
220
221 6
        return $urls;
222
    }
223
224 6
    protected static function checkConfig()
225
    {
226 6
        $missing = array();
227
        // check config
228 6
        $api_url = Config::inst()->get('SectionIO', 'api_url');
229 6
        if (!isset($api_url) || strlen($api_url) < 1) {
230
            $missing[] = 'SectionIO.api_url';
231
        }
232 6
        $account_id = Config::inst()->get('SectionIO', 'account_id');
233 6
        if (!isset($account_id) || strlen($account_id) < 1) {
234
            $missing[] = 'SectionIO.account_id';
235
        }
236 6
        $application_id = Config::inst()->get('SectionIO', 'application_id');
237 6
        if (!isset($application_id) || (!is_array($application_id) && strlen((string) $application_id) < 1)) {
238
            $missing[] = 'SectionIO.application_id';
239
        }
240 6
        $environment_name = Config::inst()->get('SectionIO', 'environment_name');
241 6
        if (!isset($environment_name) || strlen($environment_name) < 1) {
242
            $missing[] = 'SectionIO.environment_name';
243
        }
244 6
        $proxy_name = Config::inst()->get('SectionIO', 'proxy_name');
245 6
        if (!isset($proxy_name) || strlen($proxy_name) < 1) {
246
            $missing[] = 'SectionIO.proxy_name';
247
        }
248 6
        $username = Config::inst()->get('SectionIO', 'username');
249 6
        if (!isset($username) || strlen($username) < 1) {
250
            $missing[] = 'SectionIO.username';
251
        }
252 6
        $password = Config::inst()->get('SectionIO', 'password');
253 6
        if (!isset($password) || strlen($password) < 1) {
254
            $missing[] = 'SectionIO.password';
255
        }
256
        
257 6
        if (count($missing) > 0) {
258
			if (!Director::isDev()) {
259
				SS_Log::log('SectionIO:: config parameters missing: ' . implode(', ', $missing), SS_Log::WARN);
260
			}
261
            return false;
262
        }
263 6
        return true;
264
    }
265
}
266