Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allowing behavior registration to web controllers #13477

Merged
merged 1 commit into from
Aug 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/web/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Craft;
use craft\base\ModelInterface;
use craft\elements\User;
use craft\events\DefineBehaviorsEvent;
use yii\base\Action;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
Expand All @@ -33,6 +34,12 @@
*/
abstract class Controller extends \yii\web\Controller
{
/**
* @event DefineBehaviorsEvent The event that is triggered when defining the class behaviors
* @see behaviors()
*/
public const EVENT_DEFINE_BEHAVIORS = 'defineBehaviors';

public const ALLOW_ANONYMOUS_NEVER = 0;
public const ALLOW_ANONYMOUS_LIVE = 1;
public const ALLOW_ANONYMOUS_OFFLINE = 2;
Expand All @@ -57,6 +64,37 @@ abstract class Controller extends \yii\web\Controller
*/
protected array|bool|int $allowAnonymous = self::ALLOW_ANONYMOUS_NEVER;

/**
* Returns the behaviors to attach to this class.
*
* See [[behaviors()]] for details about what should be returned.
*
* Models should override this method instead of [[behaviors()]] so [[EVENT_DEFINE_BEHAVIORS]] handlers can modify the
* class-defined behaviors.
*
* @return array
*/
protected function defineBehaviors(): array
{
return [];
}

/**
* @inheritdoc
*/
public function behaviors(): array
{
$behaviors = $this->defineBehaviors();

// Give plugins a chance to modify them
$event = new DefineBehaviorsEvent([
'behaviors' => $behaviors,
]);
$this->trigger(self::EVENT_DEFINE_BEHAVIORS, $event);

return $event->behaviors;
}

/**
* @inheritdoc
* @throws InvalidConfigException if [[$allowAnonymous]] is set to an invalid value
Expand Down
Loading