UpdateResource.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Benchmark\Resources;
  3. use Benchmark\Entities\RandomNumber;
  4. use Hamlet\Database\Database;
  5. use Hamlet\Database\Procedure;
  6. use Hamlet\Http\Entities\JsonEntity;
  7. use Hamlet\Http\Requests\Request;
  8. use Hamlet\Http\Responses\Response;
  9. use Hamlet\Http\Responses\SimpleOKResponse;
  10. class UpdateResource extends DbResource
  11. {
  12. /** @var Procedure */
  13. private $selectProcedure;
  14. /** @var Procedure */
  15. private $updateProcedure;
  16. public function __construct(Database $database)
  17. {
  18. parent::__construct($database);
  19. $selectQuery = '
  20. SELECT id,
  21. randomNumber
  22. FROM World
  23. WHERE id = ?
  24. ';
  25. $this->selectProcedure = $this->database->prepare($selectQuery);
  26. $updateQuery = '
  27. UPDATE World
  28. SET randomNumber = ?
  29. WHERE id = ?
  30. ';
  31. $this->updateProcedure = $this->database->prepare($updateQuery);
  32. }
  33. public function getResponse(Request $request): Response
  34. {
  35. $count = $this->getQueriesCount($request);
  36. $payload = [];
  37. while ($count-- > 0) {
  38. $id = mt_rand(1, 10000);
  39. $randomNumber = mt_rand(1, 10000);
  40. $this->selectProcedure->bindInteger($id);
  41. /** @var RandomNumber $entry */
  42. $entry = $this->selectProcedure->processOne()
  43. ->selectAll()->cast(RandomNumber::class)
  44. ->collectHead();
  45. $modifiedEntry = $entry->withNumber($randomNumber);
  46. $this->updateProcedure->bindInteger($modifiedEntry->number());
  47. $this->updateProcedure->bindInteger($modifiedEntry->id());
  48. $this->updateProcedure->execute();
  49. $payload[] = $modifiedEntry;
  50. }
  51. return new SimpleOKResponse(new JsonEntity($payload));
  52. }
  53. }