BaseController.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Exceptions\ValidateException;
  4. use App\Models\WechatAccountModel;
  5. use Illuminate\Http\Request;
  6. /**
  7. * @SWG\Swagger(
  8. * schemes={"http"},
  9. * host="test-daogou.codedreamit.com/api",
  10. * basePath="/",
  11. * @SWG\Info(
  12. * title="导购API文档",
  13. * version="1.0.0",
  14. * )
  15. * )
  16. */
  17. class BaseController extends Controller
  18. {
  19. /**
  20. * Controller constructor.
  21. */
  22. public function __construct(Request $request)
  23. {
  24. //进行统一的参数验证
  25. //判断对应目录下的验证类是否存在
  26. $controllerName = $request->route()->getActionName();
  27. $flag = preg_match("/Controllers\\\(.*)@(.*)/",$controllerName,$match);
  28. if($flag){
  29. $controllerName = $match[1];
  30. $actionName = $match[2];
  31. $class = "\\App\\Http\\Validate\\$controllerName"."Validate";
  32. //判断验证是否存在
  33. if(class_exists($class) && method_exists($class,$actionName)){
  34. $instance = new $class();
  35. $validateFlag = $instance->$actionName($request->all());
  36. if(!$validateFlag){
  37. throw new ValidateException($instance->getError(),501);
  38. }
  39. }
  40. }
  41. }
  42. /**
  43. * 成功返回
  44. * @param array $data
  45. * @param int $code
  46. * @param string $msg
  47. * @param string $url
  48. * @return \Illuminate\Http\JsonResponse
  49. */
  50. public function success($data = [], $code = 200, $msg = "", $url = "")
  51. {
  52. return response()->json(
  53. [
  54. "status"=>true,
  55. "data"=>$data,
  56. "code"=>$code,
  57. "msg"=>$msg,
  58. "url"=>$url
  59. ]
  60. );
  61. }
  62. /**
  63. * 错误返回
  64. * @param $msg
  65. * @param string $code
  66. * @param string $url
  67. */
  68. public function error($msg,$code="500",$url="")
  69. {
  70. return response()->json(
  71. [
  72. "status"=>false,
  73. "data"=>"",
  74. "code"=>$code,
  75. "msg"=>$msg,
  76. "url"=>$url
  77. ]
  78. );
  79. }
  80. /**
  81. * 生成swagger.json文件
  82. */
  83. public function swagger()
  84. {
  85. $swagger=\Swagger\scan(__DIR__."/../");
  86. $swagger->saveAs('./swagger.json');
  87. return $this->success();
  88. }
  89. /**
  90. * 读取swagger内容
  91. */
  92. public function loadSwagger()
  93. {
  94. $data = json_decode(file_get_contents("./swagger.json"),true);
  95. return $data;
  96. }
  97. public function test()
  98. {
  99. $data = WechatAccountModel::findByWechatAppCode("fanbuting");
  100. return $data;
  101. }
  102. }