JsonController.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace common\rest;
  3. use yii\filters\ContentNegotiator;
  4. use yii\filters\Cors;
  5. use yii\rest\Controller;
  6. use yii\web\Response;
  7. use Yii;
  8. /**
  9. * @property \yii\web\Application $app
  10. * @property \yii\web\Request $req
  11. * @property \yii\web\Response $res
  12. * @property \yii\db\ActiveQuery $queryInicial
  13. * @property int $limite
  14. * @property int $pagina
  15. * @property string $ordenar
  16. * @property string $modelClass
  17. */
  18. class JsonController extends Controller {
  19. public $app = null;
  20. public $req = null;
  21. public $res = null;
  22. public $queryInicial = null;
  23. public $modelClass = null;
  24. public $limite = null;
  25. public $pagina = null;
  26. public $ordenar = null;
  27. public $serializer = 'common\rest\Serializer';
  28. public function behaviors() {
  29. $behavior = parent::behaviors();
  30. $behavior['contentNegotiator'] = [
  31. 'class' => ContentNegotiator::className(),
  32. 'formats' => [
  33. 'application/json' => Response::FORMAT_JSON,
  34. 'application/xml' => Response::FORMAT_XML,
  35. ],
  36. ];
  37. $behavior['corsFilter'] = [
  38. 'class' => Cors::className(),
  39. 'cors' => [
  40. 'Origin' => ['*'],
  41. 'Access-Control-Request-Method' => [
  42. 'GET', 'POST', 'PUT', 'PATCH',
  43. 'DELETE', 'HEAD', 'OPTIONS'
  44. ],
  45. 'Access-Control-Request-Headers' => ['*'],
  46. ],
  47. ];
  48. $behavior["authenticator"]["except"] = ['options'];
  49. return $behavior;
  50. }
  51. public function beforeAction($action) {
  52. parent::beforeAction($action);
  53. Yii::$app->getResponse()->format = Response::FORMAT_JSON;
  54. $this->app = Yii::$app;
  55. $this->req = $this->app->getRequest();
  56. $this->res = $this->app->getResponse();
  57. if ($this->req->isGet) {
  58. $this->limite = $this->req->get("limite", 20);
  59. $this->pagina = $this->req->get("pagina", 0);
  60. $this->ordenar = $this->req->get("ordenar", "");
  61. }
  62. if ($this->modelClass !== null) {
  63. $model = new $this->modelClass;
  64. $tableName = $this->modelClass::tableName();
  65. $this->queryInicial = $this->modelClass::find();
  66. if ($model->hasProperty('eliminado')) {
  67. $this->queryInicial
  68. ->where(["{{{$tableName}}}.[[eliminado]]" => null]);
  69. }
  70. }
  71. return true;
  72. }
  73. }