Completed
Pull Request — master (#119)
by Christopher
02:39
created

CacheHelpfulRobotDataTask   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 6
c 1
b 0
f 1
lcom 0
cbo 3
dl 0
loc 69
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B run() 0 41 4
A log() 0 8 2
1
<?php
2
3
class CacheHelpfulRobotDataTask extends BuildTask
4
{
5
    /**
6
     * @var string
7
     */
8
    protected $title = 'Cache Helpful Robot Data';
9
10
    /**
11
     * @var string
12
     */
13
    protected $description = 'Downloads and stores Helpful Robot module data';
14
15
    /**
16
     * @param SS_HTTPRequest $request
17
     */
18
    public function run($request)
19
    {
20
        set_error_handler(function($code, $message) {
21
            throw new ErrorException($message, $code);
22
        });
23
24
        $addons = Addon::get();
25
26
        foreach ($addons as $addon) {
27
            $this->log('fetching ' . $addon->Name);
28
29
            $context = stream_context_create([
30
                'http' => [
31
                    'method' => 'GET',
32
                    'user_agent' => 'addons.silverstripe.org',
33
                    'follow_location' => true,
34
                    'timeout' => 5,
35
                ],
36
            ]);
37
38
            try {
39
                $url = 'https://helpfulrobot.io/' . $addon->Name;
40
                $contents = file_get_contents($url, null, $context);
41
42
                $json = json_decode($contents, true);
43
44
                $addon->HelpfulRobotData = $contents;
45
                $addon->HelpfulRobotScore = $json['inspections'][0]['score'];
46
                $addon->write();
47
            } catch (ErrorException $exception) {
48
                $this->log(' - ' . $addon->Name . ' data missing');
49
50
                try {
51
                    file_get_contents($addon->Repository, null, $context);
52
                } catch (ErrorException $exception) {
53
                    $this->log(' - ' . $addon->Name . ' deleted');
54
                    $addon->delete();
55
                }
56
            }
57
        }
58
    }
59
60
    /**
61
     * @param string $message
62
     */
63
    private function log($message)
64
    {
65
        if (Director::is_cli()) {
66
            print $message . PHP_EOL;
67
        } else {
68
            print $message . "<br>";
69
        }
70
    }
71
}
72