IndexController.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. $updates = [];
  46. while ($count--) {
  47. $row = World::repeatStatement()->find(mt_rand(1, 10000));
  48. $list[] = $row;
  49. // $old = intval($row->randomNumber);
  50. $new = mt_rand(1, 10000);
  51. $updates[] = 'update world set randomNumber=' . $new . ' where id=' . $row->id;
  52. }
  53. World::beginTransaction();
  54. foreach ($updates as $sql) {
  55. $row->exec($sql);
  56. }
  57. World::commit();
  58. return $this->json($list);
  59. }
  60. public function queries($count = 1)
  61. {
  62. $count = max(min(intval($count), 500), 1);
  63. $list = [];
  64. while ($count--) {
  65. $list[] = World::repeatStatement()->find(mt_rand(1, 10000));
  66. }
  67. return $this->json($list);
  68. }
  69. }