These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more
1 | <?php |
||
2 | /** |
||
3 | * @author Anton Tuyakhov <[email protected]> |
||
4 | */ |
||
5 | |||
6 | namespace tuyakhov\jsonapi; |
||
7 | |||
8 | use yii\base\Component; |
||
9 | use yii\helpers\ArrayHelper; |
||
10 | use yii\helpers\Json; |
||
11 | use yii\web\Response; |
||
12 | use yii\web\ResponseFormatterInterface; |
||
13 | |||
14 | class JsonApiResponseFormatter extends Component implements ResponseFormatterInterface |
||
15 | { |
||
16 | /** |
||
17 | * @var integer the encoding options passed to [[Json::encode()]]. For more details please refer to |
||
18 | * <http://www.php.net/manual/en/function.json-encode.php>. |
||
19 | * Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`. |
||
20 | */ |
||
21 | public $encodeOptions = 320; |
||
22 | /** |
||
23 | * @var bool whether to format the output in a readable "pretty" format. This can be useful for debugging purpose. |
||
24 | * If this is true, `JSON_PRETTY_PRINT` will be added to [[encodeOptions]]. |
||
25 | * Defaults to `false`. |
||
26 | */ |
||
27 | public $prettyPrint = false; |
||
28 | |||
29 | /** |
||
30 | * Formats response data in JSON format. |
||
31 | * @link http://jsonapi.org/format/upcoming/#document-structure |
||
32 | * @param Response $response |
||
33 | */ |
||
34 | public function format($response) |
||
35 | { |
||
36 | $response->getHeaders()->set('Content-Type', 'application/vnd.api+json; charset=UTF-8'); |
||
37 | if ($response->data !== null) { |
||
38 | $options = $this->encodeOptions; |
||
39 | if ($this->prettyPrint) { |
||
40 | $options |= JSON_PRETTY_PRINT; |
||
41 | } |
||
42 | $apiDocument = $response->data; |
||
43 | if ($response->isClientError || $response->isServerError) { |
||
44 | if (ArrayHelper::isAssociative($response->data)) { |
||
45 | $response->data = [$response->data]; |
||
46 | } |
||
47 | $apiDocument = ['errors' => $response->data]; |
||
48 | } |
||
49 | |||
50 | $response->content = Json::encode($apiDocument, $options); |
||
51 | } |
||
52 | } |
||
53 | } |
||
0 ignored issues
–
show
|
|||
54 |
This check marks files that end in a newline character, i.e. an empy line.