IndexController.php 2.3 KB

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