Exemplo n.º 1
1
 /**
  * {@inheritDoc}
  */
 public static function fromCommand(CommandInterface $command, Response $response)
 {
     $errors = json_decode($response->getBody(true), true);
     $type = array_get($errors, 'error.type', null);
     $code = array_get($errors, 'error.code', null);
     $message = array_get($errors, 'error.message', null);
     $class = '\\Apache\\Usergrid\\Api\\Exception\\' . studly_case($type) . 'Exception';
     if (class_exists($class)) {
         $exception = new $class($message, $response->getStatusCode());
     } else {
         $exception = new static($message, $response->getStatusCode());
     }
     $exception->setErrorType($type);
     $exception->setResponse($response);
     $exception->setRequest($command->getRequest());
     return $exception;
 }
 /**
  * {@inheritDoc}
  */
 public static function fromCommand(CommandInterface $command, Response $response)
 {
     $errors = json_decode($response->getBody(true), true);
     $type = $errors['error']['type'];
     $message = isset($errors['error']['message']) ? $errors['error']['message'] : 'Unknown error';
     $code = isset($errors['error']['code']) ? $errors['error']['code'] : null;
     // We can trigger very specific exception based on the type and code
     if ($type === 'card_error') {
         $exception = new CardErrorException($message, $response->getStatusCode());
     } elseif ($type === 'invalid_request_error' && $code === 'rate_limit') {
         $exception = new ApiRateLimitException($message, $response->getStatusCode());
     } else {
         $exception = new static($message, $response->getStatusCode());
     }
     $exception->setRequest($command->getRequest());
     $exception->setResponse($response);
     return $exception;
 }
Exemplo n.º 3
0
 public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
 {
     $this->fqname = $command->getName();
     $query = array();
     $this->customResolver($value, $param, $query, $param->getWireName());
     $request->addPostFields($query);
 }
 protected function handleParsing(CommandInterface $command, Response $response, $contentType)
 {
     $operation = $command->getOperation();
     $type = $operation->getResponseType();
     $model = null;
     if ($type == OperationInterface::TYPE_MODEL) {
         $model = $operation->getServiceDescription()->getModel($operation->getResponseClass());
     } elseif ($type == OperationInterface::TYPE_CLASS) {
         $responseClassInterface = __NAMESPACE__ . '\\ResponseClassInterface';
         $className = $operation->getResponseClass();
         if (!class_exists($className)) {
             throw new ResponseClassException("{$className} does not exist");
         } elseif (!method_exists($className, 'fromCommand')) {
             throw new ResponseClassException("{$className} must implement {$responseClassInterface}");
         }
         return $className::fromCommand($command);
     }
     if (!$model) {
         // Return basic processing if the responseType is not model or the model cannot be found
         return parent::handleParsing($command, $response, $contentType);
     } elseif ($command[AbstractCommand::RESPONSE_PROCESSING] != AbstractCommand::TYPE_MODEL) {
         // Returns a model with no visiting if the command response processing is not model
         return new Model(parent::handleParsing($command, $response, $contentType), $model);
     } else {
         return new Model($this->visitResult($model, $command, $response), $model);
     }
 }
Exemplo n.º 5
0
public function after(CommandInterface $command, RequestInterface $request)
{
$xml = null;


 if (isset($this->data[$command])) {
$xml = $this->finishDocument($this->data[$command]);
unset($this->data[$command]);
} else {

 $operation = $command->getOperation();
if ($operation->getData('xmlAllowEmpty')) {
$xmlWriter = $this->createRootElement($operation);
$xml = $this->finishDocument($xmlWriter);
}
}

if ($xml) {

 if ($this->contentType && !$request->hasHeader('Content-Type')) {
$request->setHeader('Content-Type', $this->contentType);
}
$request->setBody($xml);
}
}
Exemplo n.º 6
0
 /**
  * Create a new model instance from a command.
  *
  * @param  CommandInterface
  * @return array
  */
 public static function fromCommand(CommandInterface $command)
 {
     $file = new self();
     $file->setParameters($command->getResponse()->json() + array('path' => $command['path']));
     $file->finishUpload();
     return $file->getParameters();
 }
Exemplo n.º 7
0
/**
 * Allows modules to alter an S3 command after it has been created.
 *
 * @param \Guzzle\Service\Command\CommandInterface $command
 *   The command that was created.
 */
function hook_amazons3_command_alter(\Guzzle\Service\Command\CommandInterface $command)
{
    if ($command->getName('HeadObject')) {
        $command->setOnComplete(function () {
            watchdog('amazons3', 'HeadObject was called.');
        });
    }
}
Exemplo n.º 8
0
 /**
  * @param  CommandInterface $command
  * @return EncodingResponse
  */
 protected function runCommand($command)
 {
     try {
         return $command->getResult();
     } catch (\Exception $e) {
         throw new RuntimeException('Could not run encoding.com request.', 0, $e);
     }
 }
Exemplo n.º 9
0
 /**
  * {@inheritdoc}
  */
 public function createLinkCommand(CommandInterface $command, Parameter $structure, array $data)
 {
     $this->validateLink($data);
     $this->validateLinkStructure($structure);
     $operation = $structure->getData('operation');
     $pattern = $structure->getData('pattern');
     $params = $this->parseHref($data['href'], $pattern);
     return $command->getClient()->getCommand($operation, $params);
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 protected function getClassName(CommandInterface $command)
 {
     // If it's a ListWidgets command, we can iterate over it
     if (preg_match('/^List[A-Za-z]+/', $command->getName())) {
         return $this->iteratorClassName;
     }
     // Otherwise, we don't know how to iterate over that command
     return null;
 }
 private function addMd5(CommandInterface $command)
 {
     $request = $command->getRequest();
     if ($body = $request->getBody()) {
         if (false !== ($md5 = $body->getContentMd5(true, true))) {
             $request->setHeader('Content-MD5', $md5);
         }
     }
 }
Exemplo n.º 12
0
 /**
  * Create a resource iterator
  *
  * @param CommandInterface $data    Command used for building the iterator
  * @param array            $options Iterator options.
  *
  * @return ResourceIteratorInterface
  */
 public function build($data, array $options = null)
 {
     if (!$data instanceof CommandInterface) {
         throw new InvalidArgumentException('The first argument must be an ' . 'instance of CommandInterface');
     }
     // Determine the name of the class to load
     $className = $this->baseNamespace . '\\' . Inflector::camel($data->getName()) . 'Iterator';
     return new $className($data, $options);
 }
Exemplo n.º 13
0
 /**
  * {@inheritdoc}
  */
 public function before(CommandInterface $command, array &$result)
 {
     $json = $command->getResponse()->json();
     // store links to use later
     if (array_key_exists(self::ELEMENT, $json)) {
         $this->set($command, 'links', $json[self::ELEMENT]);
     }
     // create new array of links which visit() adds to
     $result[self::ELEMENT] = array();
 }
Exemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 public function before(CommandInterface $command, array &$result)
 {
     $json = $command->getResponse()->json();
     // store links to use later
     if (array_key_exists($this->getOutputFieldName(), $json)) {
         $this->set($command, $this->getFieldName(), $json[$this->getOutputFieldName()]);
     }
     // create new array of links which visit() adds to
     $result[$this->getOutputFieldName()] = array();
 }
 /**
  * {@inheritdoc}
  */
 public function factory(CommandInterface $originalCommand, array $data)
 {
     $command = $this->newCommand();
     // set up embedded command
     $command->setClient($originalCommand->getClient());
     $originalResponse = $originalCommand->getResponse();
     $response = $this->createResponse($originalResponse, $data);
     $command->setResponse($response);
     return $command;
 }
Exemplo n.º 16
0
 private function addMd5(CommandInterface $command)
 {
     $request = $command->getRequest();
     if ($body = $request->getBody()) {
         if (false === ($md5 = $body->getContentMd5(true, true))) {
             throw new RuntimeException('Unable to add a MD5 checksum');
         }
         $request->setHeader('Content-MD5', $md5);
     }
 }
 private function createPresignedUrl(AwsClientInterface $client, CommandInterface $command)
 {
     // Create a temporary client used to generate the presigned URL
     $newClient = Ec2Client::factory(array('region' => $command['SourceRegion'], 'signature' => 'v4', 'credentials' => $client->getCredentials()));
     $preCommand = $newClient->getCommand('CopySnapshot', $command->toArray());
     $preCommand['__internal'] = true;
     /** @var \Guzzle\Http\Message\EntityEnclosingRequest $preRequest */
     $preRequest = $preCommand->prepare();
     return $newClient->getSignature()->createPresignedUrl(SignatureV4::convertPostToGet($preRequest), $newClient->getCredentials(), '+1 hour');
 }
Exemplo n.º 18
0
 public function parse(CommandInterface $command)
 {
     $response = $command->getRequest()->getResponse();
     if ($contentType = $command['command.expects']) {
         $response->setHeader('Content-Type', $contentType);
     } else {
         $contentType = (string) $response->getHeader('Content-Type');
     }
     return $this->handleParsing($command, $response, $contentType);
 }
Exemplo n.º 19
0
 public function getClassName(CommandInterface $command)
 {
     $className = $command->getName();
     if (isset($this->map[$className])) {
         return $this->map[$className];
     } elseif (isset($this->map['*'])) {
         return $this->map['*'];
     }
     return null;
 }
Exemplo n.º 20
0
 protected function getClassName(CommandInterface $command)
 {
     $iteratorName = $this->inflector->camel($command->getName()) . 'Iterator';
     foreach ($this->namespaces as $namespace) {
         $potentialClassName = $namespace . '\\' . $iteratorName;
         if (class_exists($potentialClassName)) {
             return $potentialClassName;
         }
     }
     return false;
 }
 public function parse(CommandInterface $command)
 {
     $response = $command->getRequest()->getResponse();
     // Account for hard coded content-type values specified in service descriptions
     if ($contentType = $command['command.expects']) {
         $response->setHeader('Content-Type', $contentType);
     } else {
         $contentType = (string) $response->getHeader('Content-Type');
     }
     return $this->handleParsing($command, $response, $contentType);
 }
 /**
  * Parse a class object
  *
  * @param CommandInterface $command Command to parse into an object
  *
  * @return mixed
  * @throws ResponseClassException
  */
 protected function parseClass(CommandInterface $command)
 {
     $className = $command->getOperation()->getResponseClass();
     if (!class_exists($className)) {
         throw new ResponseClassException("{$className} does not exist");
     }
     if (!method_exists($className, 'fromCommand')) {
         throw new ResponseClassException("{$className} must implement the fromCommand() method");
     }
     return $className::fromCommand($command);
 }
 public function getClassName(CommandInterface $command)
 {
     $className = $command->getName();
     if (isset($this->map[$className])) {
         return $this->map[$className];
     } elseif (isset($this->map['*'])) {
         // If a wildcard was added, then always use that
         return $this->map['*'];
     }
     return null;
 }
Exemplo n.º 24
0
 protected function parseClass(CommandInterface $command)
 {
     $event = new CreateResponseClassEvent(array('command' => $command));
     $command->getClient()->getEventDispatcher()->dispatch('command.parse_response', $event);
     if ($result = $event->getResult()) {
         return $result;
     }
     $className = $command->getOperation()->getResponseClass();
     if (!method_exists($className, 'fromCommand')) {
         throw new ResponseClassException("{$className} must exist and implement a static fromCommand() method");
     }
     return $className::fromCommand($command);
 }
 /**
  * Deserialize the response.
  *
  * @param CommandInterface $command     Command.
  * @param Response         $response    Response.
  * @param string           $contentType Content type.
  *
  * @return mixed|null Deserialized response, or `null`.
  */
 protected function deserialize(CommandInterface $command, Response $response, $contentType)
 {
     if ($this->serializer) {
         if (false !== stripos($contentType, 'json')) {
             $serializerContentType = 'json';
         } elseif (false !== stripos($contentType, 'xml')) {
             $serializerContentType = 'xml';
         } else {
             $serializerContentType = null;
         }
         if (null !== $serializerContentType && OperationInterface::TYPE_CLASS === $command->getOperation()->getResponseType()) {
             $context = DeserializationContext::create();
             $operation = $command->getOperation();
             if (null !== ($groups = $operation->getData('jms_serializer.groups'))) {
                 $context->setGroups($groups);
             }
             if (null !== ($version = $operation->getData('jms_serializer.version'))) {
                 $context->setVersion($version);
             }
             if (true === $operation->getData('jms_serializer.max_depth_checks')) {
                 $context->enableMaxDepthChecks();
             }
             return $this->serializer->deserialize($response->getBody(), $command->getOperation()->getResponseClass(), $serializerContentType, $context);
         }
     }
     return null;
 }
 /**
  * {@inheritdoc}
  *
  * @param CommandInterface $command
  * @return array|MultiResultResponse|SingleResultResponse|Response|mixed
  */
 public function parse(CommandInterface $command)
 {
     $response = $command->getRequest()->getResponse();
     if ($response === null) {
         return null;
     }
     $responseArray = $this->parseResponseIntoArray($response);
     // If there is no Body, just return the Response
     if (!$response->getBody()) {
         return $response;
     }
     // Handle multi-result responses
     if (array_key_exists('results', $responseArray)) {
         return $this->createMultiResultResponse($response);
     }
     return $this->createSingleResultResponse($response);
 }
 /**
  * {@inheritdoc}
  */
 public function build(CommandInterface $command, array $options = array())
 {
     // Get the configuration data for the command
     $commandName = $command->getName();
     $iteratorConfig = $this->operations->get($commandName) ?: array();
     $options = array_replace($this->config->getAll(), $iteratorConfig, $options);
     // Instantiate the iterator using the primary factory (if there is one)
     if ($this->primaryIteratorFactory && $this->primaryIteratorFactory->canBuild($command)) {
         $iterator = $this->primaryIteratorFactory->build($command, $options);
     } elseif (!$this->operations->hasKey($commandName)) {
         throw new InvalidArgumentException("Iterator was not found for {$commandName}.");
     } else {
         // Fallback to this factory for creating the iterator if the primary factory did not work
         $iterator = new AwsResourceIterator($command, $options);
     }
     return $iterator;
 }
 public function build(CommandInterface $command, array $options = array())
 {
     // Get the configuration data for the command
     $commandName = $command->getName();
     $commandSupported = isset($this->config[$commandName]);
     $options = $this->translateLegacyConfigOptions($options);
     $options += $commandSupported ? $this->config[$commandName] : array();
     // Instantiate the iterator using the primary factory (if one was provided)
     if ($this->primaryIteratorFactory && $this->primaryIteratorFactory->canBuild($command)) {
         $iterator = $this->primaryIteratorFactory->build($command, $options);
     } elseif (!$commandSupported) {
         throw new InvalidArgumentException("Iterator was not found for {$commandName}.");
     } else {
         // Instantiate a generic AWS resource iterator
         $iterator = new MssResourceIterator($command, $options);
     }
     return $iterator;
 }
 /**
  * {@inheritdoc}
  */
 public function prepare(CommandInterface $command)
 {
     $operation = $command->getOperation();
     $client = $command->getClient();
     $uri = $operation->getUri();
     if (!$uri) {
         $url = $client->getBaseUrl();
     } else {
         // Get the path values and use the client config settings
         $variables = $client->getConfig()->getAll();
         foreach ($operation->getParams() as $name => $arg) {
             if ($arg->getLocation() == 'uri' && $command->hasKey($name)) {
                 $variables[$name] = $command->get($name);
                 if (!is_array($variables[$name])) {
                     $variables[$name] = (string) $variables[$name];
                 }
             }
         }
         // Merge the client's base URL with an expanded URI template
         $url = (string) Url::factory($client->getBaseUrl())->combine(ParserRegistry::getInstance()->getParser('uri_template')->expand($uri, $variables));
     }
     // Inject path and base_url values into the URL
     $request = $client->createRequest($operation->getHttpMethod(), $url);
     // Add arguments to the request using the location attribute
     foreach ($operation->getParams() as $name => $arg) {
         /** @var $arg \Guzzle\Service\Description\Parameter */
         $location = $arg->getLocation();
         // Visit with the associated visitor
         if (isset($this->visitors[$location])) {
             // Ensure that a value has been set for this parameter
             $value = $command->get($name);
             if ($value !== null) {
                 // Apply the parameter value with the location visitor
                 $this->visitors[$location]->visit($command, $request, $arg, $value);
             }
         }
     }
     // Call the after method on each visitor
     foreach ($this->visitors as $visitor) {
         $visitor->after($command, $request);
     }
     return $request;
 }
Exemplo n.º 30
0
 /**
  * Create a resource iterator
  *
  * @param CommandInterface $data    Command used for building the iterator
  * @param array            $options Iterator options that are exposed as data.
  *
  * @return ResourceIteratorInterface
  */
 public function build($data, array $options = array())
 {
     if (!$data instanceof CommandInterface) {
         throw new InvalidArgumentException('The first argument must be an instance of CommandInterface');
     }
     $iteratorName = $this->inflector->camel($data->getName()) . 'Iterator';
     // Determine the name of the class to load
     $className = null;
     foreach ($this->namespaces as $namespace) {
         $potentialClassName = $namespace . '\\' . $iteratorName;
         if (class_exists($potentialClassName)) {
             $className = $potentialClassName;
             break;
         }
     }
     if (!$className) {
         throw new InvalidArgumentException("Iterator was not found matching {$iteratorName}");
     }
     return new $className($data, $options);
 }