ResponseFormatBehavior.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2018-08-15 23:30
  7. */
  8. namespace api\behaviors;
  9. use Yii;
  10. use yii\web\Response;
  11. class ResponseFormatBehavior extends \yii\base\Behavior
  12. {
  13. public $negotiate = true;
  14. public $format = Response::FORMAT_JSON;
  15. /** @var Response $response */
  16. private $_response;
  17. public function events()
  18. {
  19. return [
  20. Response::EVENT_BEFORE_SEND => [$this, 'beforeSend'],
  21. ];
  22. }
  23. public function beforeSend()
  24. {
  25. $this->_response = Yii::$app->getResponse();
  26. if( !$this->negotiate ){
  27. $this->_response->format = $this->format;
  28. }else {
  29. $this->negotiate();
  30. }
  31. }
  32. private function negotiate()
  33. {
  34. $acceptTypes = Yii::$app->getRequest()->getAcceptableContentTypes();
  35. $acceptTypes = array_keys($acceptTypes);
  36. foreach ($acceptTypes as $acceptType){
  37. switch ($acceptType) {
  38. case "text/plain":
  39. $this->_response->format = Response::FORMAT_RAW;
  40. break;
  41. case "application/html":
  42. case "text/html":
  43. case "*/*":
  44. $this->_response->format = $this->format;
  45. break;
  46. case "application/json":
  47. case "text/json":
  48. $this->_response->format = Response::FORMAT_JSON;
  49. break;
  50. case "application/xml":
  51. case "text/xml":
  52. $this->_response->format = Response::FORMAT_XML;
  53. break;
  54. }
  55. }
  56. }
  57. }