Completed
Push — master ( 7ad254...81439b )
by Robbie
10s
created

ApiController::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
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