AjaxFilter.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\filters;
  8. use Yii;
  9. use yii\base\ActionFilter;
  10. use yii\web\BadRequestHttpException;
  11. use yii\web\Request;
  12. /**
  13. * AjaxFilter allow to limit access only for ajax requests.
  14. *
  15. * ```php
  16. * public function behaviors()
  17. * {
  18. * return [
  19. * [
  20. * 'class' => 'yii\filters\AjaxFilter',
  21. * 'only' => ['index']
  22. * ],
  23. * ];
  24. * }
  25. * ```
  26. *
  27. * @author Dmitry Dorogin <dmirogin@ya.ru>
  28. * @since 2.0.13
  29. */
  30. class AjaxFilter extends ActionFilter
  31. {
  32. /**
  33. * @var string the message to be displayed when request isn't ajax
  34. */
  35. public $errorMessage = 'Request must be XMLHttpRequest.';
  36. /**
  37. * @var Request the current request. If not set, the `request` application component will be used.
  38. */
  39. public $request;
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function init()
  44. {
  45. if ($this->request === null) {
  46. $this->request = Yii::$app->getRequest();
  47. }
  48. }
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function beforeAction($action)
  53. {
  54. if ($this->request->getIsAjax()) {
  55. return true;
  56. }
  57. throw new BadRequestHttpException($this->errorMessage);
  58. }
  59. }