vendor/florianv/exchanger/src/Service/Chain.php line 53

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of Exchanger.
  5.  *
  6.  * (c) Florian Voutzinos <florian@voutzinos.com>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11. namespace Exchanger\Service;
  12. use Exchanger\Contract\ExchangeRate;
  13. use Exchanger\Contract\ExchangeRateQuery;
  14. use Exchanger\Contract\ExchangeRateService;
  15. use Exchanger\Exception\ChainException;
  16. /**
  17.  * A service using other services in a chain.
  18.  *
  19.  * @author Florian Voutzinos <florian@voutzinos.com>
  20.  */
  21. final class Chain implements ExchangeRateService
  22. {
  23.     /**
  24.      * The services.
  25.      *
  26.      * @var array|ExchangeRateService[]
  27.      */
  28.     private $services;
  29.     /**
  30.      * Creates a new chain service.
  31.      *
  32.      * @param ExchangeRateService[] $services
  33.      */
  34.     public function __construct(iterable $services = [])
  35.     {
  36.         if (!\is_array($services)) {
  37.             /** @var \Iterator $services */
  38.             $services iterator_to_array($services);
  39.         }
  40.         $this->services $services;
  41.     }
  42.     /**
  43.      * {@inheritdoc}
  44.      */
  45.     public function getExchangeRate(ExchangeRateQuery $exchangeQuery): ExchangeRate
  46.     {
  47.         $exceptions = [];
  48.         foreach ($this->services as $service) {
  49.             if (!$service->supportQuery($exchangeQuery)) {
  50.                 continue;
  51.             }
  52.             try {
  53.                 return $service->getExchangeRate($exchangeQuery);
  54.             } catch (\Throwable $e) {
  55.                 $exceptions[] = $e;
  56.             }
  57.         }
  58.         throw new ChainException($exceptions);
  59.     }
  60.     /**
  61.      * {@inheritdoc}
  62.      */
  63.     public function supportQuery(ExchangeRateQuery $exchangeQuery): bool
  64.     {
  65.         foreach ($this->services as $service) {
  66.             if ($service->supportQuery($exchangeQuery)) {
  67.                 return true;
  68.             }
  69.         }
  70.         return false;
  71.     }
  72.     /**
  73.      * {@inheritdoc}
  74.      */
  75.     public function getName(): string
  76.     {
  77.         return 'chain';
  78.     }
  79. }