CacheHelpfulRobotDataTask   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 5
dl 0
loc 76
rs 10
c 0
b 0
f 0

2 Methods

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