IndexController.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Controllers;
  3. use App\Model\Fortune;
  4. use App\Model\World;
  5. use One\Http\Controller;
  6. class IndexController extends Controller
  7. {
  8. protected function json($data)
  9. {
  10. $this->response->header('Content-type', 'application/json; charset=UTF-8');
  11. return json_encode($data);
  12. }
  13. public function toJson()
  14. {
  15. return $this->json(['message' => 'Hello, World!']);
  16. }
  17. public function plaintext()
  18. {
  19. $this->response->header('Content-Type', 'text/plain');
  20. return 'Hello, World!';
  21. }
  22. public function db()
  23. {
  24. return $this->json(World::repeatStatement()->find(mt_rand(1, 10000)));
  25. }
  26. public function fortunes()
  27. {
  28. $data = Fortune::findAll()->jsonSerialize();
  29. $data[] = (object)['id' => 0, 'message' => 'Additional fortune added at request time.'];
  30. usort($data, function ($a, $b) {
  31. return $a->message <=> $b->message;
  32. });
  33. $html = '';
  34. foreach ($data as $f) {
  35. $f->message = htmlspecialchars($f->message, ENT_QUOTES, 'UTF-8');
  36. $html .= "<tr><td>{$f->id}</td><td>{$f->message}</td></tr>";
  37. }
  38. $this->response->header('Content-type', 'text/html; charset=UTF-8');
  39. return "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>{$html}</table></body></html>";
  40. }
  41. public function updates($count = 1)
  42. {
  43. $count = max(min(intval($count), 500), 1);
  44. $list = [];
  45. while ($count--) {
  46. $row = World::repeatStatement()->find(mt_rand(1, 10000));
  47. $row->randomNumber = mt_rand(1, 10000);
  48. $list[] = $row;
  49. }
  50. //
  51. World::beginTransaction();
  52. foreach($list as $r){
  53. $r->repeatStatement()->update(['randomNumber' => $r->randomNumber]);
  54. }
  55. World::commit();
  56. return $this->json($list);
  57. }
  58. public function queries($count = 1)
  59. {
  60. $count = max(min(intval($count), 500), 1);
  61. $list = [];
  62. while ($count--) {
  63. $list[] = World::repeatStatement()->find(mt_rand(1, 10000));
  64. }
  65. return $this->json($list);
  66. }
  67. }