Completed
Push — master ( 11971b...eeafb3 )
by Nate
01:16
created

AbstractController::verbs()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember/
7
 */
8
9
namespace flipbox\craft\ember\controllers;
10
11
use Craft;
12
use craft\helpers\ArrayHelper;
13
use craft\web\Controller;
14
use yii\filters\ContentNegotiator;
15
use yii\filters\VerbFilter;
16
use yii\web\JsonParser;
17
use yii\web\Response;
18
19
/**
20
 * @author Flipbox Factory <[email protected]>
21
 * @since 2.0.0
22
 */
23
abstract class AbstractController extends Controller
24
{
25
    /**
26
     * @inheritdoc
27
     */
28
    public function init()
29
    {
30
        parent::init();
31
32
        // Add json parser (to accept json encoded body)
33
        $parsers = Craft::$app->getRequest()->parsers;
34
        if (!array_key_exists('application/json', $parsers)) {
35
            // Make sure the body wasn't already retrieved (incorrectly)
36
            /** @noinspection PhpUnhandledExceptionInspection */
37
            $bodyParams = Craft::$app->getRequest()->getBodyParams();
38
            if ($bodyParams !== null && empty($bodyParams)) {
39
                Craft::$app->getRequest()->setBodyParams(null);
40
            }
41
42
            Craft::$app->getRequest()->parsers = array_merge(
43
                $parsers,
44
                [
45
                    'application/json' => JsonParser::class
46
                ]
47
            );
48
        }
49
    }
50
51
    /**
52
     * @return array
53
     */
54
    public function behaviors()
55
    {
56
        return ArrayHelper::merge(
57
            parent::behaviors(),
58
            [
59
                'verbFilter' => [
60
                    'class' => VerbFilter::class,
61
                    'actions' => $this->verbs(),
62
                ],
63
                'contentNegotiator' => [
64
                    'class' => ContentNegotiator::class,
65
                    'formats' => [
66
                        'application/json' => Response::FORMAT_JSON,
67
                        'application/xml' => Response::FORMAT_XML,
68
                        'text/html' => Response::FORMAT_RAW
69
                    ]
70
                ]
71
            ]
72
        );
73
    }
74
75
    /**
76
     * @return array
77
     */
78
    protected function verbs(): array
79
    {
80
        return [];
81
    }
82
}
83