IndexController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://doc.hyperf.io
  8. * @contact [email protected]
  9. * @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
  10. */
  11. namespace App\Controller;
  12. use App\Model\Fortune;
  13. use App\Model\World;
  14. use App\Render;
  15. use Hyperf\HttpServer\Annotation\Controller;
  16. use Hyperf\HttpServer\Annotation\GetMapping;
  17. use Hyperf\HttpServer\Contract\ResponseInterface;
  18. /**
  19. * @Controller
  20. */
  21. class IndexController
  22. {
  23. /**
  24. * @GetMapping(path="/json")
  25. */
  26. public function json()
  27. {
  28. return ['message' => 'Hello, World!'];
  29. }
  30. /**
  31. * @GetMapping(path="/db")
  32. */
  33. public function db()
  34. {
  35. return World::find(random_int(1, 10000));
  36. }
  37. /**
  38. * @GetMapping(path="/queries/[{queries}]")
  39. */
  40. public function queries($queries = 1, ResponseInterface $response)
  41. {
  42. $queries = $this->clamp($queries);
  43. $rows = [];
  44. while ($queries--) {
  45. $rows[] = World::find(random_int(1, 10000));
  46. }
  47. return $response->json($rows);
  48. }
  49. /**
  50. * @GetMapping(path="/fortunes")
  51. */
  52. public function fortunes(Render $render)
  53. {
  54. $rows = Fortune::all();
  55. $insert = new Fortune();
  56. $insert->id = 0;
  57. $insert->message = 'Additional fortune added at request time.';
  58. $rows->add($insert);
  59. $rows = $rows->sortBy('message');
  60. return $render->render('fortunes', ['rows' => $rows]);
  61. }
  62. /**
  63. * @GetMapping(path="/updates/[{queries}]")
  64. */
  65. public function updates($queries = 1, ResponseInterface $response)
  66. {
  67. $queries = $this->clamp($queries);
  68. $rows = [];
  69. while ($queries--) {
  70. $row = World::find(random_int(1, 10000));
  71. $row->randomNumber = random_int(1, 10000);
  72. $row->save();
  73. $rows[] = $row;
  74. }
  75. return $response->json($rows);
  76. }
  77. /**
  78. * @GetMapping(path="/plaintext")
  79. */
  80. public function plaintext()
  81. {
  82. return 'Hello, World!';
  83. }
  84. private function clamp($value): int
  85. {
  86. if (! is_numeric($value) || $value < 1) {
  87. return 1;
  88. }
  89. if ($value > 500) {
  90. return 500;
  91. }
  92. return (int)$value;
  93. }
  94. }