Completed
Pull Request — master (#189)
by Robbie
02:42 queued 01:08
created

RatingApiController::getAddon()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
class RatingApiController extends Controller
4
{
5
    private static $url_handlers = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
6
        'GET $Vendor/$Package' => 'index',
7
    ];
8
9
    private static $allowed_actions = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
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];
0 ignored issues
show
Documentation introduced by
The property Rating does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
70
        if (!$detailed) {
71
            return $result;
72
        }
73
74
        // Try to decode the (JSON) rating details
75
        $details = Convert::json2array($addon->RatingDetails);
0 ignored issues
show
Documentation introduced by
The property RatingDetails does not exist on object<Addon>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
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