DbRawController.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Controller;
  3. use Doctrine\DBAL\Connection;
  4. use Doctrine\DBAL\FetchMode;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. class DbRawController
  9. {
  10. /** @var Connection */
  11. private $connection;
  12. public function __construct(Connection $connection)
  13. {
  14. $this->connection = $connection;
  15. }
  16. /**
  17. * @Route("/raw/db")
  18. */
  19. public function db(): JsonResponse
  20. {
  21. $statement = $this->connection->prepare('SELECT * FROM World WHERE id = ?');
  22. $statement->execute([mt_rand(1, 10000)]);
  23. $world = $statement->fetch(FetchMode::ASSOCIATIVE);
  24. return new JsonResponse($world);
  25. }
  26. /**
  27. * @Route("/raw/queries")
  28. */
  29. public function queries(Request $request): JsonResponse
  30. {
  31. $queries = (int) $request->query->get('queries', 1);
  32. $queries = min(max($queries, 1), 500);
  33. // possibility for enhancement is the use of SplFixedArray -> http://php.net/manual/de/class.splfixedarray.php
  34. $worlds = [];
  35. $statement = $this->connection->prepare('SELECT * FROM World WHERE id = ?');
  36. for ($i = 0; $i < $queries; ++$i) {
  37. $statement->execute([mt_rand(1, 10000)]);
  38. $worlds[] = $statement->fetch(FetchMode::ASSOCIATIVE);
  39. }
  40. return new JsonResponse($worlds);
  41. }
  42. /**
  43. * @Route("/raw/updates")
  44. */
  45. public function updates(Request $request): JsonResponse
  46. {
  47. $queries = (int) $request->query->get('queries', 1);
  48. $queries = min(500, max(1, $queries));
  49. $worlds = [];
  50. $writeStatement = $this->connection->prepare('UPDATE World SET randomNumber= ? WHERE id= ?');
  51. $readStatement = $this->connection->prepare('SELECT id,randomNumber FROM World WHERE id = ?');
  52. for ($i = 0; $i < $queries; ++$i) {
  53. $id = mt_rand(1, 10000);
  54. $readStatement->execute([$id]);
  55. $world = $readStatement->fetch(FetchMode::ASSOCIATIVE);
  56. $writeStatement->execute(
  57. [$world['randomNumber'] = mt_rand(1, 10000), $id]
  58. );
  59. $worlds[] = $world;
  60. }
  61. return new JsonResponse($worlds);
  62. }
  63. }