SortAction.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2017-08-13 10:00
  7. */
  8. namespace backend\actions;
  9. use Yii;
  10. use stdClass;
  11. use Closure;
  12. use backend\actions\helpers\Helper;
  13. use yii\base\Exception;
  14. use yii\base\InvalidArgumentException;
  15. use yii\web\MethodNotAllowedHttpException;
  16. use yii\web\Response;
  17. use yii\web\UnprocessableEntityHttpException;
  18. /**
  19. * backend sort
  20. *
  21. * Class SortAction
  22. * @package backend\actions
  23. */
  24. class SortAction extends \yii\base\Action
  25. {
  26. /**
  27. * @var Closure
  28. */
  29. public $doSort = null;
  30. /**
  31. * @var string after success doUpdate tips message showed in page top
  32. */
  33. public $successTipsMessage = "success";
  34. public function init()
  35. {
  36. parent::init();
  37. if( $this->successTipsMessage === "success"){
  38. $this->successTipsMessage = Yii::t("app", "success");
  39. }
  40. }
  41. /**
  42. * sort
  43. *
  44. * @return array|\yii\web\Response
  45. * @throws MethodNotAllowedHttpException
  46. * @throws UnprocessableEntityHttpException
  47. * @throws \yii\base\Exception
  48. */
  49. public function run()
  50. {
  51. if (Yii::$app->getRequest()->getIsPost()) {
  52. if(!$this->doSort instanceof Closure){
  53. throw new Exception(__CLASS__ . "::doSort must be closure");
  54. }
  55. $post = Yii::$app->getRequest()->post();
  56. if (isset($post[Yii::$app->getRequest()->csrfParam])) {
  57. unset($post[Yii::$app->getRequest()->csrfParam]);
  58. }
  59. reset($post);
  60. $temp = current($post);
  61. $condition = array_keys($temp)[0];
  62. $value = $temp[$condition];
  63. $condition = json_decode($condition, true);
  64. if (!is_array($condition)) throw new InvalidArgumentException("SortColumn generate html must post data like xxx[{pk:'unique'}]=number");
  65. $result = call_user_func_array($this->doSort, [$condition, $value, $this]);
  66. if (Yii::$app->getRequest()->getIsAjax()) {
  67. Yii::$app->getResponse()->format = Response::FORMAT_JSON;
  68. if( $result === true ){
  69. return ['code'=>0, 'msg'=>'success', 'data'=>new stdClass()];
  70. }else{
  71. throw new UnprocessableEntityHttpException(Helper::getErrorString($result));
  72. }
  73. }else {
  74. if ($result === true) {
  75. Yii::$app->getSession()->setFlash('success', $this->successTipsMessage);
  76. } else {
  77. Yii::$app->getSession()->setFlash('error', Helper::getErrorString($result));
  78. }
  79. return $this->controller->goBack();
  80. }
  81. }else{
  82. throw new MethodNotAllowedHttpException(Yii::t('app', "Sort must be POST http method"));
  83. }
  84. }
  85. }