Completed
Push — master ( 9d5b94...91923c )
by Seth
02:07
created

CanvasHack::parseManifestCanvasPages()   C

Complexity

Conditions 11
Paths 9

Size

Total Lines 51
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 22
nc 9
nop 1
dl 0
loc 51
rs 5.7333
c 0
b 0
f 0

How to fix   Long Method    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
/** CanvasHack and related classes */
4
5
namespace smtech\CanvasHack;
6
7
/**
8
 * CanvasHack
9
 *
10
 * @author Seth Battis <[email protected]>
11
 **/
12
class CanvasHack
13
{
14
15
    private $sql;
16
17
    private $path;
18
19
    private $table = 'canvashacks';
20
    private $css = 'css';
21
    private $javascript = 'javascript';
22
    private $pages = 'pages';
23
    private $dom = 'dom';
24
25
    private $id = null;
26
    private $name = null;
27
    private $abstract = null;
28
    private $description = null;
29
30
    public function __construct($sql, $path)
0 ignored issues
show
Coding Style introduced by
__construct uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
31
    {
32
33
        if ($sql instanceof \mysqli) {
34
            $this->sql = $sql;
35
        } else {
36
            throw new CanvasHack_Exception(
37
                'Expected mysqli object, received ' . get_class($sql),
38
                CanvasHack_Exception::MYSQL
39
            );
40
        }
41
42
        if (file_exists($path) && file_exists($manifest = realpath("$path/manifest.xml"))) {
43
            $this->path = dirname($manifest);
44
            $this->parseManifest($manifest);
45
            $pluginMetadata = new \Battis\AppMetadata($this->sql, $this->id);
46
            $pluginMetadata['PLUGIN_PATH'] = $path;
47
            $pluginMetadata['PLUGIN_URL'] = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on' ? 'http://' : 'https://') . $_SERVER['SERVER_NAME'] . preg_replace("|^{$_SERVER['DOCUMENT_ROOT']}(.*)$|", '$1', $pluginMetadata['PLUGIN_PATH']);
48
        } else {
49
            if (isset($manifest)) {
50
                throw new CanvasHack_Exception(
51
                    "Manifest file missing, expected <code>$path/manifest.xml</code>",
52
                    CanvasHack_Exception::MANIFEST
53
                );
54
            } else {
55
                $this->loadManifestEntry($path);
56
            }
57
        }
58
    }
59
60
    public static function getCanvasHackById($sql, $id)
61
    {
62
        if (!($sql instanceof \mysqli)) {
63
            throw new CanvasHack_Exception(
64
                'Expected mysqli object, received ' . get_class($sql),
65
                CanvasHack_Exception::MYSQL
66
            );
67
        }
68
69
        $_id = $sql->real_escape_string($id);
70
        $result = $sql->query("SELECT * FROM `canvashacks` WHERE `id` = '$_id'");
71
        if ($result->num_rows === 0) {
72
            throw new CanvasHack_Exception(
73
                "No existing CanvasHacks matching ID `$id`",
74
                CanvasHack_Exception::ID
75
            );
76
        } else {
77
            $row = $result->fetch_assoc();
78
            return new CanvasHack($sql, $row['path']);
79
        }
80
    }
81
82
    private function loadManifestEntry($id)
83
    {
84
        $response = $this->sql->query("
85
            SELECT * FROM `{$this->table}` WHERE `id` = '" . $this->sql->real_escape_string($id) . "'
86
        ");
87
        $row = $response->fetch_assoc();
88
        if ($row) {
89
            $this->id = $row['id'];
90
            $this->name = $row['name'];
91
            if (!empty($row['abstract'])) {
92
                $this->abstract = $row['abstract'];
93
            }
94
            if (!empty($row['description'])) {
95
                $this->description = $row['description'];
96
            }
97
        } else {
98
            throw new CanvasHack_Exception(
99
                "Manifest database entry missing for $id",
100
                CanvasHack_Exception::MANIFEST
101
            );
102
        }
103
    }
104
105
    private function parseManifest($manifest)
106
    {
107
        $xml = simplexml_load_string(file_get_contents($manifest));
108
        if ($xml === false) {
109
            throw new CanvasHack_Exception(
110
                "$manifest could not be parsed as a valid XML document",
111
                CanvasHack_Exception::MANIFEST
112
            );
113
        }
114
115
        $this->parseManifestMetadata($xml);
116
        $this->parseManifestComponents($xml->components);
117
    }
118
119
    private function parseManifestMetadata($xml)
120
    {
121
        $this->required('id', $this->sql->real_escape_string($xml->id));
122
        $this->required('name', $xml->name);
123
        $this->optional('abstract', $xml->abstract);
124
        $this->optional('description', $xml->description);
125
        if (!isset($this->abstract) && !isset($this->description)) {
126
            throw new CanvasHack_Exception(
127
                'Either an abstract or a description must be provided in the manifest',
128
                CanvasHack_Exception::REQUIRED
129
            );
130
        }
131
132
        // TODO deal with authors
133
134
        $_name = $this->sql->real_escape_string($this->name);
135
        $_abstract = (
136
            isset($this->abstract) ?
137
                $this->sql->real_escape_string($this->abstract) :
138
                $this->sql->real_escape_string($this->description)
139
        );
140
        $_description = (
141
            isset($this->description) ?
142
                $this->sql->real_escape_string($this->description) :
143
                $this->sql->real_escape_string($this->abstract)
144
        );
145
        $_path = $this->sql->real_escape_string($this->path);
146
147
        $this->updateDb($this->table, $this->id, array('name' => $_name, 'path' => $_path, 'abstract' => $_abstract, 'description' => $_description), 'id');
148
    }
149
150 View Code Duplication
    private function parseManifestCSS($css)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
    {
152
        if (!empty($css)) {
153
            $this->updateDb($this->css, $this->id, array('path' => realpath($this->path . '/' . $css)));
154
        } else {
155
            $this->clearDb($this->css, $this->id);
156
        }
157
    }
158
159 View Code Duplication
    private function parseManifestJavascript($javascript)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
160
    {
161
        if (!empty($javascript)) {
162
            $this->updateDb($this->javascript, $this->id, array('path' => realpath($this->path) . '/' . $javascript));
163
        } else {
164
            $this->clearDb($this->javascript, $this->id);
165
        }
166
    }
167
168
    private function parseManifestCanvasPages($pages)
169
    {
170
        $this->clearDb($this->pages, $this->id);
171
        if (!empty($pages->include)) {
172
            foreach ($pages->include->children() as $page) {
173
                if (!$this->sql->query("
174
                    INSERT INTO `{$this->pages}`
175
                    (
176
                        `canvashack`,
177
                        `url`,
178
                        `pattern`,
179
                        `include`
180
                    ) VALUES (
181
                        '{$this->id}',
182
                        " . ($page->type == 'url' ? "'{$page->url}'" : 'NULL') . ",
183
                        " . ($page->type == 'regex' ? "'" . addslashes($page->pattern) . "'" : 'NULL') . ",
184
                        TRUE
185
                    )
186
                ")) {
187
                    throw new CanvasHack_Exception(
188
                        "Could not insert included page entry for {$this->id}: " . $page->asXml() . PHP_EOL . $this->sql->error,
189
                        CanvasHack_Exception::SQL
190
                    );
191
                }
192
            }
193
        }
194
        if (!empty($pages->exclude)) {
195
            foreach ($pages->exclude->children() as $page) {
196
                if (!$this->sql->query("
197
                    INSERT INTO `{$this->pages}`
198
                    (
199
                        `canvashack`,
200
                        `url`,
201
                        `pattern`,
202
                        `include`
203
                    ) VALUES (
204
                        '{$this->id}',
205
                        " . ($page->type == 'url' ? "'" . $this->sql->real_escape_string($page->url) . "'" : 'NULL') . ",
206
                        " . ($page->type == 'regex' ? "'" . $this->sql->real_escape_string($page->pattern) . "'" : 'NULL') . ",
207
                        FALSE
208
                    )
209
                ")) {
210
                    // TODO wording could be improved
211
                    throw new CanvasHack_Exception(
212
                        "Could not insert included page entry for {$this->id}: " . $page->asXml() . PHP_EOL . $this->sql->error,
213
                        CanvasHack_Exception::SQL
214
                    );
215
                }
216
            }
217
        }
218
    }
219
220
    private function parseManifestCanvasDOM($dom)
221
    {
222
        $this->clearDb($this->dom, $this->id);
223
        if (!empty($dom)) {
224
            foreach ($dom->children() as $bundle) {
225
                if (!$this->sql->query("
226
                    INSERT INTO `{$this->dom}`
227
                    (
228
                        `canvashack`,
229
                        `selector`,
230
                        `event`,
231
                        `action`
232
                    ) VALUES (
233
                        '{$this->id}',
234
                        '" . $this->sql->real_escape_string($bundle->selector) . "',
235
                        '" . $this->sql->real_escape_string($bundle->event) . "',
236
                        '" . $this->sql->real_escape_string($bundle->action) . "'
237
                    )
238
                ")) {
239
                    // TODO wording could be improved
240
                    throw new CanvasHack_Exception(
241
                        "Could not insert DOM entry for {$this->id}: " . $dom->asXml() . PHP_EOL . $this->sql->error,
242
                        CanvasHack_Exception::SQL
243
                    );
244
                }
245
            }
246
        }
247
    }
248
249
    private function parseManifestCanvas($canvas)
250
    {
251
        $this->parseManifestCanvasPages($canvas->pages);
252
        $this->parseManifestCanvasDOM($canvas->dom);
253
    }
254
255
    private function parseManifestComponents($components)
256
    {
257
        $this->parseManifestCSS($components->css);
258
        $this->parseManifestJavascript($components->javascript);
259
        $this->parseManifestCanvas($components->canvas);
260
    }
261
262
    private function required($field, $value)
263
    {
264
        if (!empty($value)) {
265
            $this->$field = (string) $value;
266
        } else {
267
            throw new CanvasHack_Exception(
268
                "`$field` is required and was not found in the manifest",
269
                CanvasHack_Exception::REQUIRED
270
            );
271
        }
272
    }
273
274
    private function optional($field, $value)
275
    {
276
        if (isset($value)) {
277
            $this->$field = (string) $value;
278
        } else {
279
            $this->$field = null;
280
        }
281
    }
282
283
    public function getId()
284
    {
285
        return $this->id;
286
    }
287
288
    public function getName()
289
    {
290
        return $this->name;
291
    }
292
293
    public function getAbstract()
294
    {
295
        if (empty($this->abstract)) {
296
            return $this->description;
297
        } else {
298
            return $this->abstract;
299
        }
300
    }
301
302
    public function getDescription()
303
    {
304
        if (empty($this->description)) {
305
            return $this->abstract;
306
        } else {
307
            return $this->description;
308
        }
309
    }
310
311
    public function isEnabled()
312
    {
313
        $result = $this->sql->query("
314
            SELECT * FROM `{$this->table}` WHERE `id` = '{$this->id}'
315
        ");
316
        $row = $result->fetch_assoc();
317
        return (isset($row['enabled']) && $row['enabled']);
318
    }
319
320
    public function enable()
321
    {
322
        $this->sql->query("
323
            UPDATE `{$this->table}` SET `enabled` = '1' WHERE `id` = '{$this->id}'
324
        ");
325
    }
326
327
    public function disable()
328
    {
329
        $this->sql->query("
330
            UPDATE `{$this->table}` SET `enabled` = '0' WHERE `id` = '{$this->id}'
331
        ");
332
    }
333
334
    /**
335
     * Helper function to insert/update into a SQL table
336
     *
337
     * @param string $table
338
     * @param string $id CanvasHack identifier
339
     * @param array $fields
340
     **/
341
    private function updateDb($table, $id, $fields, $idKey = 'canvashack')
342
    {
343
        $response = $this->sql->query("
344
            SELECT *
345
                FROM `$table`
346
                WHERE
347
                    `$idKey` = '$id'
348
                LIMIT 1
349
        ");
350
351
        $params = array();
352
        foreach ($fields as $field => $value) {
353
            $params[] = "`$field` = '$value'";
354
        }
355
356
        if ($response->num_rows > 0) {
357
            if (!$this->sql->query("
358
                UPDATE `$table`
359
                    SET " .
360
                    implode(', ', $params) .
361
                "WHERE
362
                    `$idKey` = '$id'
363
            ")) {
364
                throw new CanvasHack_Exception(
365
                    "Could not update `$table` with `$idKey` = '$id' and fields `$params'. " . $this->sql->error,
366
                    CanvasHack_Exception::SQL
367
                );
368
            }
369
        } else {
370
            $fields[$idKey] = $this->id;
371
            if (!$this->sql->query("
372
                INSERT INTO `$table`
373
                (`" . implode('`, `', array_keys($fields)) . "`)
374
                VALUES
375
                ('" . implode("', '", $fields) . "')
376
            ")) {
377
                throw new CanvasHack_Exception(
378
                    "Could not insert a new row into `$table` with `$idkey` = '$id' and fields `$params'. " . $this->sql->error,
379
                    CanvasHack_Exception::SQL
380
                );
381
            }
382
        }
383
    }
384
385
    private function clearDb($table, $id, $idKey = 'canvashack')
386
    {
387
        if (!$this->sql->query("
388
            DELETE FROM `$table`
389
                WHERE
390
                    `$idKey` = '$id'
391
        ")) {
392
            throw new CanvasHack_Exception(
393
                "Could not clear `$table` of `$idKey` = '$id' entries. " . $this->sql->error,
394
                CanvasHack_Exception::SQL
395
            );
396
        }
397
    }
398
}
399