Acknowledger.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Messenger\Handler;
  11. use Symfony\Component\Messenger\Exception\LogicException;
  12. /**
  13. * @author Nicolas Grekas <p@tchwork.com>
  14. */
  15. class Acknowledger
  16. {
  17. private $handlerClass;
  18. private $ack;
  19. private $error = null;
  20. private $result = null;
  21. /**
  22. * @param null|\Closure(\Throwable|null, mixed):void $ack
  23. */
  24. public function __construct(string $handlerClass, \Closure $ack = null)
  25. {
  26. $this->handlerClass = $handlerClass;
  27. $this->ack = $ack ?? static function () {};
  28. }
  29. /**
  30. * @param mixed $result
  31. */
  32. public function ack($result = null): void
  33. {
  34. $this->doAck(null, $result);
  35. }
  36. public function nack(\Throwable $error): void
  37. {
  38. $this->doAck($error);
  39. }
  40. public function getError(): ?\Throwable
  41. {
  42. return $this->error;
  43. }
  44. /**
  45. * @return mixed
  46. */
  47. public function getResult()
  48. {
  49. return $this->result;
  50. }
  51. public function isAcknowledged(): bool
  52. {
  53. return null === $this->ack;
  54. }
  55. public function __destruct()
  56. {
  57. if ($this->ack instanceof \Closure) {
  58. throw new LogicException(sprintf('The acknowledger was not called by the "%s" batch handler.', $this->handlerClass));
  59. }
  60. }
  61. private function doAck(\Throwable $e = null, $result = null): void
  62. {
  63. if (!$ack = $this->ack) {
  64. throw new LogicException(sprintf('The acknowledger cannot be called twice by the "%s" batch handler.', $this->handlerClass));
  65. }
  66. $this->ack = null;
  67. $this->error = $e;
  68. $this->result = $result;
  69. $ack($e, $result);
  70. }
  71. }