Completed
Pull Request — master (#194)
by
unknown
01:48
created

ApiController::handleAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 2
1
<?php
2
abstract class ApiController extends Controller
3
{
4
    /**
5
     * Given a result payload, format as a JSON response and return
6
     *
7
     * @param array $data
8
     * @return SS_HTTPResponse
9
     */
10
    protected function formatResponse(array $data)
11
    {
12
        $response = new SS_HTTPResponse();
13
        $response
14
            ->addHeader('Content-Type', 'application/json')
15
            ->setBody(Convert::raw2json($data, JSON_PRETTY_PRINT));
16
17
        // Don't cache anything in dev mode
18
        if (Director::get_environment_type() !== 'dev') {
19
            // Only cache failure messages for one minute, otherwise use the configured cache age
20
            $cacheAge = empty($data['success']) ? 60 : Config::inst()->get(__CLASS__, 'cache_age');
21
            $response->addHeader('Cache-Control', 'max-age=' . $cacheAge);
22
        }
23
24
        return $response;
25
    }
26
27
    /**
28
     * Overrides this method only to prepend capturing any provided framework version header
29
     *
30
     * @inheritDoc
31
     */
32
    protected function handleAction($request, $action)
33
    {
34
        $frameworkVersionHeader = $request->getHeader('Silverstripe-Framework-Version');
35
36
        if ($frameworkVersionHeader) {
37
            ApiCallerVersions::create([
38
                'Endpoint' => $request->getURL(),
39
                'Version' => $frameworkVersionHeader,
40
            ])->write();
41
        }
42
43
        return parent::handleAction($request, $action);
44
    }
45
}
46