IndexController.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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\Di\Annotation\Inject;
  16. use Hyperf\HttpServer\Annotation\Controller;
  17. use Hyperf\HttpServer\Annotation\GetMapping;
  18. use Hyperf\HttpServer\Contract\ResponseInterface;
  19. /**
  20. * @Controller
  21. */
  22. class IndexController
  23. {
  24. /**
  25. * @Inject()
  26. * @var Render
  27. */
  28. private $render;
  29. /**
  30. * @Inject()
  31. * @var ResponseInterface
  32. */
  33. private $response;
  34. /**
  35. * @GetMapping(path="/json")
  36. */
  37. public function json()
  38. {
  39. return $this->response->json(['message' => 'Hello, World!']);
  40. }
  41. /**
  42. * @GetMapping(path="/db")
  43. */
  44. public function db()
  45. {
  46. return $this->response->json(World::find(random_int(1, 10000)));
  47. }
  48. /**
  49. * @GetMapping(path="/queries/[{queries}]")
  50. */
  51. public function queries($queries = 1)
  52. {
  53. $queries = $this->clamp($queries);
  54. $rows = [];
  55. while ($queries--) {
  56. $rows[] = World::find(random_int(1, 10000));
  57. }
  58. return $this->response->json($rows);
  59. }
  60. /**
  61. * @GetMapping(path="/fortunes")
  62. */
  63. public function fortunes()
  64. {
  65. $rows = Fortune::all();
  66. $insert = new Fortune();
  67. $insert->id = 0;
  68. $insert->message = 'Additional fortune added at request time.';
  69. $rows->add($insert);
  70. $rows = $rows->sortBy('message');
  71. return $this->render->render('fortunes', ['rows' => $rows]);
  72. }
  73. /**
  74. * @GetMapping(path="/updates/[{queries}]")
  75. */
  76. public function updates($queries = 1)
  77. {
  78. $queries = $this->clamp($queries);
  79. $rows = [];
  80. while ($queries--) {
  81. $row = World::find(random_int(1, 10000));
  82. $row->randomNumber = random_int(1, 10000);
  83. $row->save();
  84. $rows[] = $row;
  85. }
  86. return $this->response->json($rows);
  87. }
  88. /**
  89. * @GetMapping(path="/plaintext")
  90. */
  91. public function plaintext()
  92. {
  93. return $this->response->raw('Hello, World!');
  94. }
  95. private function clamp($value): int
  96. {
  97. if (! is_numeric($value) || $value < 1) {
  98. return 1;
  99. }
  100. if ($value > 500) {
  101. return 500;
  102. }
  103. return (int)$value;
  104. }
  105. }