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

CacheHelpfulRobotDataTask::run()   B

Complexity

Conditions 4
Paths 10

Size

Total Lines 41
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 41
rs 8.5806
cc 4
eloc 26
nc 10
nop 1
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