AwsClientTrait.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace Aws;
  3. use Aws\Api\Service;
  4. use GuzzleHttp\Promise\Promise;
  5. /**
  6. * A trait providing generic functionality for interacting with Amazon Web
  7. * Services. This is meant to be used in classes implementing
  8. * \Aws\AwsClientInterface
  9. */
  10. trait AwsClientTrait
  11. {
  12. public function getPaginator($name, array $args = [])
  13. {
  14. $config = $this->getApi()->getPaginatorConfig($name);
  15. return new ResultPaginator($this, $name, $args, $config);
  16. }
  17. public function getIterator($name, array $args = [])
  18. {
  19. $config = $this->getApi()->getPaginatorConfig($name);
  20. if (!$config['result_key']) {
  21. throw new \UnexpectedValueException(sprintf(
  22. 'There are no resources to iterate for the %s operation of %s',
  23. $name, $this->getApi()['serviceFullName']
  24. ));
  25. }
  26. $key = is_array($config['result_key'])
  27. ? $config['result_key'][0]
  28. : $config['result_key'];
  29. if ($config['output_token'] && $config['input_token']) {
  30. return $this->getPaginator($name, $args)->search($key);
  31. }
  32. $result = $this->execute($this->getCommand($name, $args))->search($key);
  33. return new \ArrayIterator((array) $result);
  34. }
  35. public function waitUntil($name, array $args = [])
  36. {
  37. return $this->getWaiter($name, $args)->promise()->wait();
  38. }
  39. public function getWaiter($name, array $args = [])
  40. {
  41. $config = isset($args['@waiter']) ? $args['@waiter'] : [];
  42. $config += $this->getApi()->getWaiterConfig($name);
  43. return new Waiter($this, $name, $args, $config);
  44. }
  45. public function execute(CommandInterface $command)
  46. {
  47. return $this->executeAsync($command)->wait();
  48. }
  49. public function executeAsync(CommandInterface $command)
  50. {
  51. $handler = $command->getHandlerList()->resolve();
  52. return $handler($command);
  53. }
  54. public function __call($name, array $args)
  55. {
  56. $params = isset($args[0]) ? $args[0] : [];
  57. if (substr($name, -5) === 'Async') {
  58. return $this->executeAsync(
  59. $this->getCommand(substr($name, 0, -5), $params)
  60. );
  61. }
  62. return $this->execute($this->getCommand($name, $params));
  63. }
  64. /**
  65. * @param string $name
  66. * @param array $args
  67. *
  68. * @return CommandInterface
  69. */
  70. abstract public function getCommand($name, array $args = []);
  71. /**
  72. * @return Service
  73. */
  74. abstract public function getApi();
  75. }