Messenger.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /*
  3. * This file is part of the overtrue/easy-sms.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Overtrue\EasySms;
  11. use Overtrue\EasySms\Contracts\MessageInterface;
  12. use Overtrue\EasySms\Contracts\PhoneNumberInterface;
  13. use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
  14. /**
  15. * Class Messenger.
  16. */
  17. class Messenger
  18. {
  19. const STATUS_SUCCESS = 'success';
  20. const STATUS_FAILURE = 'failure';
  21. /**
  22. * @var \Overtrue\EasySms\EasySms
  23. */
  24. protected $easySms;
  25. /**
  26. * Messenger constructor.
  27. *
  28. * @param \Overtrue\EasySms\EasySms $easySms
  29. */
  30. public function __construct(EasySms $easySms)
  31. {
  32. $this->easySms = $easySms;
  33. }
  34. /**
  35. * Send a message.
  36. *
  37. * @param \Overtrue\EasySms\Contracts\PhoneNumberInterface $to
  38. * @param \Overtrue\EasySms\Contracts\MessageInterface $message
  39. * @param array $gateways
  40. *
  41. * @return array
  42. *
  43. * @throws \Overtrue\EasySms\Exceptions\NoGatewayAvailableException
  44. */
  45. public function send(PhoneNumberInterface $to, MessageInterface $message, array $gateways = [])
  46. {
  47. $results = [];
  48. $isSuccessful = false;
  49. foreach ($gateways as $gateway => $config) {
  50. try {
  51. $results[$gateway] = [
  52. 'gateway' => $gateway,
  53. 'status' => self::STATUS_SUCCESS,
  54. 'result' => $this->easySms->gateway($gateway)->send($to, $message, $config),
  55. ];
  56. $isSuccessful = true;
  57. break;
  58. } catch (\Exception $e) {
  59. $results[$gateway] = [
  60. 'gateway' => $gateway,
  61. 'status' => self::STATUS_FAILURE,
  62. 'exception' => $e,
  63. ];
  64. } catch (\Throwable $e) {
  65. $results[$gateway] = [
  66. 'gateway' => $gateway,
  67. 'status' => self::STATUS_FAILURE,
  68. 'exception' => $e,
  69. ];
  70. }
  71. }
  72. if (!$isSuccessful) {
  73. throw new NoGatewayAvailableException($results);
  74. }
  75. return $results;
  76. }
  77. }