-
Notifications
You must be signed in to change notification settings - Fork 611
/
BaseElementsController.php
71 lines (62 loc) · 1.91 KB
/
BaseElementsController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\controllers;
use craft\base\ElementInterface;
use craft\errors\InvalidTypeException;
use craft\services\ElementSources;
use craft\web\Controller;
use yii\web\BadRequestHttpException;
/**
* The BaseElementsController class provides some common methods for [[ElementsController]] and [[ElementIndexesController]].
* Note that all actions in the controller require an authenticated Craft session via [[allowAnonymous]].
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
abstract class BaseElementsController extends Controller
{
/**
* @inheritdoc
*/
public function beforeAction($action): bool
{
if (!parent::beforeAction($action)) {
return false;
}
// All actions require control panel requests
$this->requireCpRequest();
return true;
}
/**
* Returns the posted element type class.
*
* @return string
* @throws BadRequestHttpException if the requested element type is invalid
*/
protected function elementType(): string
{
$class = $this->request->getRequiredParam('elementType');
// TODO: should probably move the code inside try{} to a helper method
try {
if (!is_subclass_of($class, ElementInterface::class)) {
throw new InvalidTypeException($class, ElementInterface::class);
}
} catch (InvalidTypeException $e) {
throw new BadRequestHttpException($e->getMessage());
}
return $class;
}
/**
* Returns the context that this controller is being called in.
*
* @return string
*/
protected function context(): string
{
return $this->request->getParam('context') ?? ElementSources::CONTEXT_INDEX;
}
}