Completed
Push — master ( a743e8...453823 )
by Florian
01:45
created

SectionIO::flushSiteTree()   C

Complexity

Conditions 12
Paths 13

Size

Total Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 13.5062

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 25
cts 32
cp 0.7813
rs 6.9666
c 0
b 0
f 0
cc 12
nc 13
nop 2
crap 13.5062

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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