GlobalAccessBehavior.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace app\components;
  3. use Yii;
  4. use yii\base\Behavior;
  5. use yii\base\Controller;
  6. use yii\filters\AccessControl;
  7. /**
  8. * Class GlobalAccessBehavior
  9. * @package common\behaviors
  10. */
  11. class GlobalAccessBehavior extends Behavior
  12. {
  13. /**
  14. * @var array
  15. * @see \yii\filters\AccessControl::rules
  16. */
  17. public $rules = [];
  18. /**
  19. * @var string
  20. */
  21. public $accessControlFilter = AccessControl::class;
  22. /**
  23. * @var callable a callback that will be called if the access should be denied
  24. * to the current user. If not set, [[denyAccess()]] will be called.
  25. *
  26. * The signature of the callback should be as follows:
  27. *
  28. * ~~~
  29. * function ($rule, $action)
  30. * ~~~
  31. *
  32. * where `$rule` is the rule that denies the user, and `$action` is the current [[Action|action]] object.
  33. * `$rule` can be `null` if access is denied because none of the rules matched.
  34. */
  35. public $denyCallback;
  36. /**
  37. * @return array
  38. */
  39. public function events()
  40. {
  41. return [
  42. Controller::EVENT_BEFORE_ACTION => 'beforeAction'
  43. ];
  44. }
  45. /**
  46. * @inheritdoc
  47. */
  48. public function beforeAction()
  49. {
  50. Yii::$app->controller->attachBehavior('access', [
  51. 'class' => $this->accessControlFilter,
  52. 'denyCallback' => $this->denyCallback,
  53. 'rules' => $this->rules
  54. ]);
  55. }
  56. }