Completed
Push — master ( 9b020f...c11b68 )
by Florian
02:34
created

SectionIO::performFlush()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 0
cts 19
cp 0
rs 8.7377
c 0
b 0
f 0
cc 6
nc 3
nop 1
crap 42
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 1
     */
22
    public static function flush()
23 1
    {
24 1
        if (Config::inst()->get('SectionIO', 'flush_on_dev_build')) {
25
            return static::flushAll();
26
        }
27 1
28
        return;
29
    }
30 3
31
    public static function flushAll()
32 3
    {
33
        $exp = 'obj.http.x-url ~ /';
34 3
35
        return static::performFlush($exp);
36
    }
37 1
38
    public static function flushImage($imageID)
39 1
    {
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
            return static::performFlush($exp);
46
        }
47
48
        return false;
49
    }
50 1
51
    public static function flushFile($fileID)
52 1
    {
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
            return static::performFlush($exp);
57
        }
58
59
        return false;
60
    }
61 1
62
    public static function flushSiteTree($sitetreeID)
63 1
    {
64 1
        $sitetree = SiteTree::get()->byID($sitetreeID);
65 1
        if ($sitetree && $sitetree->exists()) {
66
            $strategy = Config::inst()->get('SectionIO', 'sitetree_flush_strategy');
67
            switch ($strategy) {
68 1
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
                    break;
73 1
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
                    break;
84 1
85 1
                case 'all':
86 1
                    $exp = 'obj.http.content-type ~ "'.preg_quote('text/html').'"';
87
                    break;
88 1
89 1
                case 'everyting':
90 1
                default:
91 1
                    $exp = 'obj.http.x-url ~ /';
92
                    break;
93 1
94
            }
95 1
96
            return static::performFlush($exp);
97
        }
98
99
        return false;
100
    }
101 6
    
102
    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 6
146
    protected static function getService($url, $banExpression)
147
    {
148 6
        // prepare API call
149 6
        $service = new RestfulService(
150
            $url,
151 6
            0 // expiry time 0: do not cache the API call
152
        );
153 6
        // set basic auth
154 6
        $username = Config::inst()->get('SectionIO', 'username');
155 6
        $password = Config::inst()->get('SectionIO', 'password');
156
        $service->basicAuth($username, $password);
157 6
        // set query string (ban expression)
158 6
        $service->setQueryString(array(
159 6
            'banExpression' => $banExpression,
160
        ));
161 6
162
        return $service;
163
    }
164 6
165
    protected static function getOptions()
166
    {
167 6
        // prepare curl options for ssl verification
168
        if (Config::inst()->get('SectionIO', 'verify_ssl')) {
169 6
            return array(
170 6
                CURLOPT_SSL_VERIFYPEER => 0,
171 6
                CURLOPT_SSL_VERIFYHOST => 0,
172 6
            );
173
        }
174 6
        return ayya();
175
    }
176
177 6
    protected static function getHeaders()
178
    {
179 6
        $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
        $urls = array();
190 6
191 6
        if (static::checkConfig()) {
192 6
            $api_url = Config::inst()->get('SectionIO', 'api_url');
193
            $account_id = Config::inst()->get('SectionIO', 'account_id');
194 6
            $application_id = Config::inst()->get('SectionIO', 'application_id');
195
            $application_ids = array();
196
            if (is_string($application_id)) {
197 6
                $application_ids = preg_split("/[\s,]+/", $application_id);
198
            } elseif (is_array($application_id)) {
199 6
                $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 6
204 6
            foreach ($application_ids as $appid) {
205 6
                // 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
                    $account_id,
210
                    'application',
211 6
                    $appid,
212 6
                    'environment',
213
                    $environment_name,
214 6
                    'proxy',
215
                    $proxy_name,
216 6
                    'state'
217 6
                );
218 6
            }
219 6
        }
220 6
221 6
        return $urls;
222 6
    }
223 6
224 6
    protected static function checkConfig()
225 6
    {
226
        $missing = array();
227 6
        // 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 6
        }
232
        $account_id = Config::inst()->get('SectionIO', 'account_id');
233
        if (!isset($account_id) || strlen($account_id) < 1) {
234 6
            $missing[] = 'SectionIO.account_id';
235
        }
236 6
        $application_id = Config::inst()->get('SectionIO', 'application_id');
237
        if (!isset($application_id) || (!is_array($application_id) && strlen((string) $application_id) < 1)) {
238 6
            $missing[] = 'SectionIO.application_id';
239 6
        }
240
        $environment_name = Config::inst()->get('SectionIO', 'environment_name');
241
        if (!isset($environment_name) || strlen($environment_name) < 1) {
242 6
            $missing[] = 'SectionIO.environment_name';
243 6
        }
244
        $proxy_name = Config::inst()->get('SectionIO', 'proxy_name');
245
        if (!isset($proxy_name) || strlen($proxy_name) < 1) {
246 6
            $missing[] = 'SectionIO.proxy_name';
247 6
        }
248
        $username = Config::inst()->get('SectionIO', 'username');
249
        if (!isset($username) || strlen($username) < 1) {
250 6
            $missing[] = 'SectionIO.username';
251 6
        }
252
        $password = Config::inst()->get('SectionIO', 'password');
253
        if (!isset($password) || strlen($password) < 1) {
254 6
            $missing[] = 'SectionIO.password';
255 6
        }
256
        
257
        if (count($missing) > 0) {
258 6
			if (!Director::isDev()) {
259 6
				SS_Log::log('SectionIO:: config parameters missing: ' . implode(', ', $missing), SS_Log::WARN);
260
			}
261
            return false;
262 6
        }
263 6
        return true;
264
    }
265
}
266