OptionsAction.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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\rest;
  8. use Yii;
  9. /**
  10. * OptionsAction responds to the OPTIONS request by sending back an `Allow` header.
  11. *
  12. * For more details and usage information on OptionsAction, see the [guide article on rest controllers](guide:rest-controllers).
  13. *
  14. * @author Qiang Xue <qiang.xue@gmail.com>
  15. * @since 2.0
  16. */
  17. class OptionsAction extends \yii\base\Action
  18. {
  19. /**
  20. * @var array the HTTP verbs that are supported by the collection URL
  21. */
  22. public $collectionOptions = ['GET', 'POST', 'HEAD', 'OPTIONS'];
  23. /**
  24. * @var array the HTTP verbs that are supported by the resource URL
  25. */
  26. public $resourceOptions = ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
  27. /**
  28. * Responds to the OPTIONS request.
  29. * @param string $id
  30. */
  31. public function run($id = null)
  32. {
  33. if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
  34. Yii::$app->getResponse()->setStatusCode(405);
  35. }
  36. $options = $id === null ? $this->collectionOptions : $this->resourceOptions;
  37. $headers = Yii::$app->getResponse()->getHeaders();
  38. $headers->set('Allow', implode(', ', $options));
  39. $headers->set('Access-Control-Allow-Methods', implode(', ', $options));
  40. }
  41. }