Completed
Push — features/ss4-upgrade-v2 ( e12684...7bb85e )
by Sam
05:52
created

RatingApiController::formatResponse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
3
class RatingApiController extends Controller
4
{
5
    private static $url_handlers = [
6
        'GET $Vendor/$Package' => 'index',
7
    ];
8
9
    private static $allowed_actions = [
10
        'index',
11
    ];
12
13
    /**
14
     * Set the default cache lifetime in seconds. Only used outside of "dev" environments.
15
     *
16
     * @config
17
     * @var int
18
     */
19
    private static $cache_age = 10800;
20
21
    public function index(SS_HTTPRequest $request)
22
    {
23
        $params = $this->getURLParams();
24
        if (empty($params['Vendor']) || empty($params['Package'])) {
25
            return $this->formatResponse([
26
                'success' => false,
27
                'message' => 'Missing or incomplete module name',
28
            ]);
29
        }
30
31
        $package = sprintf('%s/%s', $params['Vendor'], $params['Package']);
32
        $addon = $this->getAddon($package);
33
        if (!$addon) {
34
            return $this->formatResponse([
35
                'success' => false,
36
                'message' => 'Module could not be found',
37
            ]);
38
        }
39
40
        $result = ['success' => true] + $this->getAddonMetrics($addon, $request->getVar('detailed') !== null);
41
42
        return $this->formatResponse($result);
43
    }
44
45
    /**
46
     * Given a package name, return the Addon model for it
47
     *
48
     * @param string $packageName
49
     * @return Addon
50
     */
51
    protected function getAddon($packageName)
52
    {
53
        return Addon::get()->filter(['Name' => $packageName])->first();
54
    }
55
56
    /**
57
     * Get the module metrics that will be returned
58
     *
59
     * @param Addon $addon
60
     * @param boolean $detailed
61
     * @return array
62
     */
63
    protected function getAddonMetrics(Addon $addon, $detailed)
64
    {
65
        if (!$addon) {
66
            return [];
67
        }
68
69
        $result = ['rating' => $addon->Rating];
70
        if (!$detailed) {
71
            return $result;
72
        }
73
74
        // Try to decode the (JSON) rating details
75
        $details = Convert::json2array($addon->RatingDetails);
76
77
        if ($details) {
78
            $result['metrics'] = $details;
79
        }
80
81
        return $result;
82
    }
83
84
    /**
85
     * Given a result payload, format as a JSON response and return
86
     *
87
     * @param array $data
88
     * @return SS_HTTPResponse
89
     */
90
    protected function formatResponse(array $data)
91
    {
92
        $response = new SS_HTTPResponse();
93
        $response
94
            ->addHeader('Content-Type', 'application/json')
95
            ->setBody(Convert::raw2json($data, JSON_PRETTY_PRINT));
96
97
        // Don't cache anything in dev mode
98
        if (Director::get_environment_type() !== 'dev') {
99
            // Only cache failure messages for one minute, otherwise use the configured cache age
100
            $cacheAge = empty($data['success']) ? 60 : Config::inst()->get(__CLASS__, 'cache_age');
101
            $response->addHeader('Cache-Control', 'max-age=' . $cacheAge);
102
        }
103
104
        return $response;
105
    }
106
}
107