CommandRetry.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.6.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Core\Retry;
  16. use Exception;
  17. /**
  18. * Allows any action to be retried in case of an exception.
  19. *
  20. * This class can be parametrized with a strategy, which will be followed
  21. * to determine whether or not the action should be retried.
  22. */
  23. class CommandRetry
  24. {
  25. /**
  26. * The strategy to follow should the executed action fail.
  27. *
  28. * @var \Cake\Core\Retry\RetryStrategyInterface
  29. */
  30. protected $strategy;
  31. /**
  32. * The number of retries to perform in case of failure.
  33. *
  34. * @var int
  35. */
  36. protected $retries;
  37. /**
  38. * Creates the CommandRetry object with the given strategy and retry count
  39. *
  40. * @param \Cake\Core\Retry\RetryStrategyInterface $strategy The strategy to follow should the action fail
  41. * @param int $retries The number of times the action has been already called
  42. */
  43. public function __construct(RetryStrategyInterface $strategy, $retries = 1)
  44. {
  45. $this->strategy = $strategy;
  46. $this->retries = $retries;
  47. }
  48. /**
  49. * The number of retries to perform in case of failure
  50. *
  51. * @param callable $action The callable action to execute with a retry strategy
  52. * @return mixed The return value of the passed action callable
  53. * @throws \Exception
  54. */
  55. public function run(callable $action)
  56. {
  57. $retryCount = 0;
  58. $lastException = null;
  59. do {
  60. try {
  61. return $action();
  62. } catch (Exception $e) {
  63. $lastException = $e;
  64. if (!$this->strategy->shouldRetry($e, $retryCount)) {
  65. throw $e;
  66. }
  67. }
  68. } while ($this->retries > $retryCount++);
  69. if ($lastException !== null) {
  70. throw $lastException;
  71. }
  72. }
  73. }