public function __invoke(CommandInterface $command, ResponseInterface $response)
 {
     $output = $this->api->getOperation($command->getName())->getOutput();
     $result = [];
     if ($payload = $output['payload']) {
         $this->extractPayload($payload, $output, $response, $result);
     }
     foreach ($output->getMembers() as $name => $member) {
         switch ($member['location']) {
             case 'header':
                 $this->extractHeader($name, $member, $response, $result);
                 break;
             case 'headers':
                 $this->extractHeaders($name, $member, $response, $result);
                 break;
             case 'statusCode':
                 $this->extractStatus($name, $response, $result);
                 break;
         }
     }
     if (!$payload && $response->getBody()->getSize() > 0) {
         // if no payload was found, then parse the contents of the body
         $this->payload($response, $output, $result);
     }
     return new Result($result);
 }
Esempio n. 2
0
 public function __invoke(CommandInterface $command, RequestInterface $request)
 {
     if (!$this->queue) {
         $last = $this->lastCommand ? ' The last command sent was ' . $this->lastCommand->getName() . '.' : '';
         throw new \RuntimeException('Mock queue is empty. Trying to send a ' . $command->getName() . ' command failed.' . $last);
     }
     $this->lastCommand = $command;
     $this->lastRequest = $request;
     $result = array_shift($this->queue);
     if (is_callable($result)) {
         $result = $result($command, $request);
     }
     if ($result instanceof \Exception) {
         $result = new RejectedPromise($result);
     } else {
         // Add an effective URI and statusCode if not present.
         $meta = $result['@metadata'];
         if (!isset($meta['effectiveUri'])) {
             $meta['effectiveUri'] = (string) $request->getUri();
         }
         if (!isset($meta['statusCode'])) {
             $meta['statusCode'] = 200;
         }
         $result['@metadata'] = $meta;
         $result = Promise\promise_for($result);
     }
     $result->then($this->onFulfilled, $this->onRejected);
     return $result;
 }
 /**
  * @param CommandInterface $command Command to serialized
  *
  * @return RequestInterface
  */
 public function __invoke(CommandInterface $command)
 {
     $operation = $this->api->getOperation($command->getName());
     $args = $command->toArray();
     $opts = $this->serialize($operation, $args);
     $uri = $this->buildEndpoint($operation, $args, $opts);
     return new Psr7\Request($operation['http']['method'], $uri, isset($opts['headers']) ? $opts['headers'] : [], isset($opts['body']) ? $opts['body'] : null);
 }
 public function __invoke(CommandInterface $command, RequestInterface $request)
 {
     $nextHandler = $this->nextHandler;
     $bucket = $command['Bucket'];
     if ($bucket && !isset(self::$exclusions[$command->getName()])) {
         $request = $this->modifyRequest($request, $command);
     }
     return $nextHandler($command, $request);
 }
 public function __invoke(CommandInterface $command, ResponseInterface $response)
 {
     $output = $this->api->getOperation($command->getName())->getOutput();
     $xml = new \SimpleXMLElement($response->getBody());
     if ($this->honorResultWrapper && $output['resultWrapper']) {
         $xml = $xml->{$output['resultWrapper']};
     }
     return new Result($this->xmlParser->parse($output, $xml));
 }
 public function __invoke(CommandInterface $command, RequestInterface $request)
 {
     $name = $command->getName();
     $body = $request->getBody();
     if (!$request->hasHeader('Content-MD5') && $body->getSize() && in_array($name, self::$requireMd5)) {
         $request = $request->withHeader('Content-MD5', base64_encode(Psr7\hash($body, 'md5', true)));
     }
     $next = $this->nextHandler;
     return $next($command, $request);
 }
 public function __invoke(CommandInterface $command, ResponseInterface $response)
 {
     if (200 === $response->getStatusCode() && isset(self::$ambiguousSuccesses[$command->getName()])) {
         $errorParser = $this->errorParser;
         $parsed = $errorParser($response);
         if (isset($parsed['code']) && isset($parsed['message'])) {
             throw new $this->exceptionClass($parsed['message'], $command, ['connection_error' => true]);
         }
     }
     $fn = $this->parser;
     return $fn($command, $response);
 }
Esempio n. 8
0
 /**
  * When invoked with an AWS command, returns a serialization array
  * containing "method", "uri", "headers", and "body" key value pairs.
  *
  * @param CommandInterface $command
  *
  * @return RequestInterface
  */
 public function __invoke(CommandInterface $command)
 {
     $operation = $this->api->getOperation($command->getName());
     $body = ['Action' => $command->getName(), 'Version' => $this->api->getMetadata('apiVersion')];
     $params = $command->toArray();
     // Only build up the parameters when there are parameters to build
     if ($params) {
         $body += call_user_func($this->paramBuilder, $operation->getInput(), $params);
     }
     $body = http_build_query($body, null, '&', PHP_QUERY_RFC3986);
     return new Request('POST', $this->endpoint, ['Content-Length' => strlen($body), 'Content-Type' => 'application/x-www-form-urlencoded'], $body);
 }
 public function __invoke(CommandInterface $command, RequestInterface $request)
 {
     $next = $this->nextHandler;
     $name = $command->getName();
     $body = $request->getBody();
     if (in_array($name, self::$md5) && !$request->hasHeader('Content-MD5')) {
         // Set the content MD5 header for operations that require it.
         $request = $request->withHeader('Content-MD5', base64_encode(Psr7\hash($body, 'md5', true)));
     } elseif (in_array($name, self::$sha256) && $command['ContentSHA256']) {
         // Set the content hash header if provided in the parameters.
         $request = $request->withHeader('X-Amz-Content-Sha256', $command['ContentSHA256']);
     }
     return $next($command, $request);
 }
 private function createPresignedUrl(AwsClientInterface $client, CommandInterface $cmd)
 {
     $newCmd = $client->getCommand('CopySnapshot', $cmd->toArray());
     // Avoid infinite recursion by flagging the new command.
     $newCmd->__skipCopySnapshot = true;
     // Serialize a request for the CopySnapshot operation.
     $request = \Aws\serialize($newCmd);
     // Create the new endpoint for the target endpoint.
     $endpoint = EndpointProvider::resolve($this->endpointProvider, ['region' => $cmd['SourceRegion'], 'service' => 'ec2'])['endpoint'];
     // Set the request to hit the target endpoint.
     $uri = $request->getUri()->withHost((new Uri($endpoint))->getHost());
     $request = $request->withUri($uri);
     // Create a presigned URL for our generated request.
     $signer = new SignatureV4('ec2', $cmd['SourceRegion']);
     return (string) $signer->presign(SignatureV4::convertPostToGet($request), $client->getCredentials()->wait(), '+1 hour')->getUri();
 }
Esempio n. 11
0
 public function __invoke(CommandInterface $command, ResponseInterface $response)
 {
     $operation = $this->api->getOperation($command->getName());
     $result = $this->parser->parse($operation->getOutput(), $this->parseJson($response->getBody()));
     return new Result($result ?: []);
 }
 /**
  * Parses a rejection into an AWS error.
  *
  * @param array            $err     Rejection error array.
  * @param RequestInterface $request Request that was sent.
  * @param CommandInterface $command Command being sent.
  *
  * @return \Exception
  */
 private function parseError(array $err, RequestInterface $request, CommandInterface $command)
 {
     if (!isset($err['exception'])) {
         throw new \RuntimeException('The HTTP handler was rejected without an "exception" key value pair.');
     }
     $serviceError = "AWS HTTP error: " . $err['exception']->getMessage();
     if (!isset($err['response'])) {
         $parts = ['response' => null];
     } else {
         $errorParser = $this->errorParser;
         $parts = $errorParser($err['response']);
         $parts['response'] = $err['response'];
         $serviceError .= " {$parts['code']} ({$parts['type']}): " . "{$parts['message']} - " . $err['response']->getBody();
     }
     $parts['exception'] = $err['exception'];
     $parts['request'] = $request;
     $parts['connection_error'] = !empty($err['connection_error']);
     return new $this->exceptionClass(sprintf('Error executing "%s" on "%s"; %s', $command->getName(), $request->getUri(), $serviceError), $command, $parts, $err['exception']);
 }
Esempio n. 13
0
 /**
  * When invoked with an AWS command, returns a serialization array
  * containing "method", "uri", "headers", and "body" key value pairs.
  *
  * @param CommandInterface $command
  *
  * @return RequestInterface
  */
 public function __invoke(CommandInterface $command)
 {
     $name = $command->getName();
     $operation = $this->api->getOperation($name);
     return new Request($operation['http']['method'], $this->endpoint, ['X-Amz-Target' => $this->api->getMetadata('targetPrefix') . '.' . $name, 'Content-Type' => $this->contentType], $this->jsonFormatter->build($operation->getInput(), $command->toArray()));
 }
 private function canAccelerate(CommandInterface $command)
 {
     return empty(self::$exclusions[$command->getName()]) && S3Client::isBucketDnsCompatible($command['Bucket']);
 }
 /**
  * Parses a rejection into an AWS error.
  *
  * @param array            $err     Rejection error array.
  * @param RequestInterface $request Request that was sent.
  * @param CommandInterface $command Command being sent.
  * @param array            $stats   Transfer statistics
  *
  * @return \Exception
  */
 private function parseError(array $err, RequestInterface $request, CommandInterface $command, array $stats)
 {
     if (!isset($err['exception'])) {
         throw new \RuntimeException('The HTTP handler was rejected without an "exception" key value pair.');
     }
     $serviceError = "AWS HTTP error: " . $err['exception']->getMessage();
     if (!isset($err['response'])) {
         $parts = ['response' => null];
     } else {
         try {
             $parts = call_user_func($this->errorParser, $err['response']);
             $serviceError .= " {$parts['code']} ({$parts['type']}): " . "{$parts['message']} - " . $err['response']->getBody();
         } catch (ParserException $e) {
             $parts = [];
             $serviceError .= ' Unable to parse error information from ' . "response - {$e->getMessage()}";
         }
         $parts['response'] = $err['response'];
     }
     $parts['exception'] = $err['exception'];
     $parts['request'] = $request;
     $parts['connection_error'] = !empty($err['connection_error']);
     $parts['transfer_stats'] = $stats;
     return new $this->exceptionClass(sprintf('Error executing "%s" on "%s"; %s', $command->getName(), $request->getUri(), $serviceError), $command, $parts, $err['exception']);
 }
 private function getRegionalizedCommand(CommandInterface $command, $region)
 {
     return $this->getClientFromPool($region)->getCommand($command->getName(), $command->toArray());
 }
/**
 * Serialize a request for a command but do not send it.
 *
 * Returns a promise that is fulfilled with the serialized request.
 *
 * @param CommandInterface $command Command to serialize.
 *
 * @return RequestInterface
 * @throws \RuntimeException
 */
function serialize(CommandInterface $command)
{
    $request = null;
    $handlerList = $command->getHandlerList();
    // Return a mock result.
    $handlerList->setHandler(function (CommandInterface $_, RequestInterface $r) use(&$request) {
        $request = $r;
        return new FulfilledPromise(new Result([]));
    });
    call_user_func($handlerList->resolve(), $command)->wait();
    if (!$request instanceof RequestInterface) {
        throw new \RuntimeException('Calling handler did not serialize request');
    }
    return $request;
}
Esempio n. 18
0
 public function executeAsync(CommandInterface $command)
 {
     $handler = $command->getHandlerList()->resolve();
     return $handler($command);
 }