Completed
Pull Request — master (#192)
by
unknown
19:56
created

SupportedAddonsApiController::formatResponse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
dl 16
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
3
class SupportedAddonsApiController extends Controller
4
{
5
    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...
6
        'index',
7
    ];
8
9
    /**
10
     * Set the default cache lifetime in seconds. Only used outside of "dev" environments.
11
     *
12
     * @config
13
     * @var int
14
     */
15
    private static $cache_age = 86400; // 24 hours
16
17
    public function index()
18
    {
19
        $supportedAddons = Addon::get()->filter('Supported', true)->column('Name');
20
21
        $result = ['success' => true, 'addons' => $supportedAddons];
22
23
        return $this->formatResponse($result);
24
    }
25
26
    /**
27
     * Given a result payload, format as a JSON response and return
28
     *
29
     * @param array $data
30
     * @return SS_HTTPResponse
31
     */
32 View Code Duplication
    protected function formatResponse(array $data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
33
    {
34
        $response = new SS_HTTPResponse();
35
        $response
36
            ->addHeader('Content-Type', 'application/json')
37
            ->setBody(Convert::raw2json($data, JSON_PRETTY_PRINT));
38
39
        // Don't cache anything in dev mode
40
        if (Director::get_environment_type() !== 'dev') {
41
            // Only cache failure messages for one minute, otherwise use the configured cache age
42
            $cacheAge = empty($data['success']) ? 60 : Config::inst()->get(__CLASS__, 'cache_age');
43
            $response->addHeader('Cache-Control', 'max-age=' . $cacheAge);
44
        }
45
46
        return $response;
47
    }
48
}
49