Completed
Pull Request — master (#194)
by
unknown
01:40
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
3
/**
4
 * Abstract controller for actions that provide an API endpoint.
5
 */
6
abstract class ApiController extends Controller
7
{
8
    /**
9
     * Given a result payload, format as a JSON response and return
10
     *
11
     * @param array $data
12
     * @return SS_HTTPResponse
13
     */
14
    protected function formatResponse(array $data)
15
    {
16
        $response = new SS_HTTPResponse();
17
        $response
18
            ->addHeader('Content-Type', 'application/json')
19
            ->setBody(Convert::raw2json($data, JSON_PRETTY_PRINT));
20
21
        // Don't cache anything in dev mode
22
        if (Director::get_environment_type() !== 'dev') {
23
            // Only cache failure messages for one minute, otherwise use the configured cache age
24
            $cacheAge = empty($data['success']) ? 60 : Config::inst()->get(__CLASS__, 'cache_age');
25
            $response->addHeader('Cache-Control', 'max-age=' . $cacheAge);
26
        }
27
28
        return $response;
29
    }
30
31
    /**
32
     * Overrides this method only to prepend capturing any provided framework version header
33
     *
34
     * @inheritDoc
35
     */
36
    protected function handleAction($request, $action)
37
    {
38
        $frameworkVersionHeader = $request->getHeader('Silverstripe-Framework-Version');
39
40
        if ($frameworkVersionHeader) {
41
            ApiCallerVersions::create([
42
                'Endpoint' => $request->getURL(),
43
                'Version' => $frameworkVersionHeader,
44
            ])->write();
45
        }
46
47
        return parent::handleAction($request, $action);
48
    }
49
}
50