update 1.0.8.0

Commits for version update
This commit is contained in:
Manish Verma
2016-10-17 12:02:27 +05:30
parent dec927987b
commit 76e85db070
9674 changed files with 495757 additions and 58922 deletions

141
vendor/aws/aws-sdk-php/LICENSE.md vendored Normal file
View File

@@ -0,0 +1,141 @@
# Apache License
Version 2.0, January 2004
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
## 1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1
through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the
License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled
by, or are under common control with that entity. For the purposes of this definition, "control" means
(i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract
or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial
ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software
source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form,
including but not limited to compiled object code, generated documentation, and conversions to other media
types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License,
as indicated by a copyright notice that is included in or attached to the work (an example is provided in the
Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from)
the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent,
as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not
include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work
and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any
modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to
Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to
submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of
electronic, verbal, or written communication sent to the Licensor or its representatives, including but not
limited to communication on electronic mailing lists, source code control systems, and issue tracking systems
that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise designated in writing by the copyright
owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been
received by Licensor and subsequently incorporated within the Work.
## 2. Grant of Copyright License.
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare
Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
## 3. Grant of Patent License.
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent
license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such
license applies only to those patent claims licensable by such Contributor that are necessarily infringed by
their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such
Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim
or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work
constitutes direct or contributory patent infringement, then any patent licenses granted to You under this
License for that Work shall terminate as of the date such litigation is filed.
## 4. Redistribution.
You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You meet the following conditions:
1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
2. You must cause any modified files to carry prominent notices stating that You changed the files; and
3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent,
trademark, and attribution notices from the Source form of the Work, excluding those notices that do
not pertain to any part of the Derivative Works; and
4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that
You distribute must include a readable copy of the attribution notices contained within such NOTICE
file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed as part of the Derivative Works; within
the Source form or documentation, if provided along with the Derivative Works; or, within a display
generated by the Derivative Works, if and wherever such third-party notices normally appear. The
contents of the NOTICE file are for informational purposes only and do not modify the License. You may
add Your own attribution notices within Derivative Works that You distribute, alongside or as an
addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be
construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license
terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative
Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the
conditions stated in this License.
## 5. Submission of Contributions.
Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by
You to the Licensor shall be under the terms and conditions of this License, without any additional terms or
conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate
license agreement you may have executed with Licensor regarding such Contributions.
## 6. Trademarks.
This License does not grant permission to use the trade names, trademarks, service marks, or product names of
the Licensor, except as required for reasonable and customary use in describing the origin of the Work and
reproducing the content of the NOTICE file.
## 7. Disclaimer of Warranty.
Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor
provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of
permissions under this License.
## 8. Limitation of Liability.
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless
required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any
Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential
damages of any character arising as a result of this License or out of the use or inability to use the Work
(including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or
any and all other commercial damages or losses), even if such Contributor has been advised of the possibility
of such damages.
## 9. Accepting Warranty or Additional Liability.
While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole
responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold
each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

64
vendor/aws/aws-sdk-php/NOTICE.md vendored Normal file
View File

@@ -0,0 +1,64 @@
# AWS SDK for PHP
<http://aws.amazon.com/php>
Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
<http://aws.amazon.com/apache2.0>
or in the "license" file accompanying this file. This file is distributed
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License.
# Guzzle
<https://github.com/guzzle/guzzle>
Copyright (c) 2014 Michael Dowling, https://github.com/mtdowling
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# jmespath.php
<https://github.com/mtdowling/jmespath.php>
Copyright (c) 2014 Michael Dowling, https://github.com/mtdowling
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

63
vendor/aws/aws-sdk-php/composer.json vendored Normal file
View File

@@ -0,0 +1,63 @@
{
"name": "aws/aws-sdk-php",
"homepage": "http://aws.amazon.com/sdkforphp",
"description": "AWS SDK for PHP - Use Amazon Web Services in your PHP project",
"keywords": ["aws","amazon","sdk","s3","ec2","dynamodb","cloud","glacier"],
"type": "library",
"license": "Apache-2.0",
"authors": [
{
"name": "Amazon Web Services",
"homepage": "http://aws.amazon.com"
}
],
"support": {
"forum": "https://forums.aws.amazon.com/forum.jspa?forumID=80",
"issues": "https://github.com/aws/aws-sdk-php/issues"
},
"require": {
"php": ">=5.5",
"guzzlehttp/guzzle": "^5.3.1|^6.2.1",
"guzzlehttp/psr7": "~1.3.1",
"guzzlehttp/promises": "~1.0",
"mtdowling/jmespath.php": "~2.2"
},
"require-dev": {
"ext-openssl": "*",
"ext-pcre": "*",
"ext-spl": "*",
"ext-json": "*",
"ext-dom": "*",
"ext-simplexml": "*",
"phpunit/phpunit": "~4.0|~5.0",
"behat/behat": "~3.0",
"doctrine/cache": "~1.4",
"aws/aws-php-sns-message-validator": "~1.0",
"nette/neon": "^2.3",
"andrewsville/php-token-reflection": "^1.4",
"psr/cache": "^1.0"
},
"suggest": {
"ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages",
"ext-curl": "To send requests using cURL",
"doctrine/cache": "To use the DoctrineCacheAdapter",
"aws/aws-php-sns-message-validator": "To validate incoming SNS notifications"
},
"autoload": {
"psr-4": {
"Aws\\": "src/"
},
"files": ["src/functions.php"]
},
"autoload-dev": {
"psr-4": {
"Aws\\Test\\": "tests/"
},
"classmap": ["build/"]
},
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Aws\Acm;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS Certificate Manager** service.
*
* @method \Aws\Result addTagsToCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise addTagsToCertificateAsync(array $args = [])
* @method \Aws\Result deleteCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteCertificateAsync(array $args = [])
* @method \Aws\Result describeCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeCertificateAsync(array $args = [])
* @method \Aws\Result getCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCertificateAsync(array $args = [])
* @method \Aws\Result listCertificates(array $args = [])
* @method \GuzzleHttp\Promise\Promise listCertificatesAsync(array $args = [])
* @method \Aws\Result listTagsForCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsForCertificateAsync(array $args = [])
* @method \Aws\Result removeTagsFromCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise removeTagsFromCertificateAsync(array $args = [])
* @method \Aws\Result requestCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise requestCertificateAsync(array $args = [])
* @method \Aws\Result resendValidationEmail(array $args = [])
* @method \GuzzleHttp\Promise\Promise resendValidationEmailAsync(array $args = [])
*/
class AcmClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\Acm\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS Certificate Manager** service.
*/
class AcmException extends AwsException {}

View File

@@ -0,0 +1,67 @@
<?php
namespace Aws\Api;
/**
* Base class that is used by most API shapes
*/
abstract class AbstractModel implements \ArrayAccess
{
/** @var array */
protected $definition;
/** @var ShapeMap */
protected $shapeMap;
/**
* @param array $definition Service description
* @param ShapeMap $shapeMap Shapemap used for creating shapes
*/
public function __construct(array $definition, ShapeMap $shapeMap)
{
$this->definition = $definition;
$this->shapeMap = $shapeMap;
}
public function toArray()
{
return $this->definition;
}
public function offsetGet($offset)
{
return isset($this->definition[$offset])
? $this->definition[$offset] : null;
}
public function offsetSet($offset, $value)
{
$this->definition[$offset] = $value;
}
public function offsetExists($offset)
{
return isset($this->definition[$offset]);
}
public function offsetUnset($offset)
{
unset($this->definition[$offset]);
}
protected function shapeAt($key)
{
if (!isset($this->definition[$key])) {
throw new \InvalidArgumentException('Expected shape definition at '
. $key);
}
return $this->shapeFor($this->definition[$key]);
}
protected function shapeFor(array $definition)
{
return isset($definition['shape'])
? $this->shapeMap->resolve($definition)
: Shape::create($definition, $this->shapeMap);
}
}

View File

@@ -0,0 +1,244 @@
<?php
namespace Aws\Api;
use Aws\Exception\UnresolvedApiException;
/**
* API providers.
*
* An API provider is a function that accepts a type, service, and version and
* returns an array of API data on success or NULL if no API data can be created
* for the provided arguments.
*
* You can wrap your calls to an API provider with the
* {@see ApiProvider::resolve} method to ensure that API data is created. If the
* API data is not created, then the resolve() method will throw a
* {@see Aws\Exception\UnresolvedApiException}.
*
* use Aws\Api\ApiProvider;
* $provider = ApiProvider::defaultProvider();
* // Returns an array or NULL.
* $data = $provider('api', 's3', '2006-03-01');
* // Returns an array or throws.
* $data = ApiProvider::resolve($provider, 'api', 'elasticfood', '2020-01-01');
*
* You can compose multiple providers into a single provider using
* {@see Aws\or_chain}. This method accepts providers as arguments and
* returns a new function that will invoke each provider until a non-null value
* is returned.
*
* $a = ApiProvider::filesystem(sys_get_temp_dir() . '/aws-beta-models');
* $b = ApiProvider::manifest();
*
* $c = \Aws\or_chain($a, $b);
* $data = $c('api', 'betaservice', '2015-08-08'); // $a handles this.
* $data = $c('api', 's3', '2006-03-01'); // $b handles this.
* $data = $c('api', 'invalid', '2014-12-15'); // Neither handles this.
*/
class ApiProvider
{
/** @var array A map of public API type names to their file suffix. */
private static $typeMap = [
'api' => 'api-2',
'paginator' => 'paginators-1',
'waiter' => 'waiters-2',
'docs' => 'docs-2',
];
/** @var array API manifest */
private $manifest;
/** @var string The directory containing service models. */
private $modelsDir;
/**
* Resolves an API provider and ensures a non-null return value.
*
* @param callable $provider Provider function to invoke.
* @param string $type Type of data ('api', 'waiter', 'paginator').
* @param string $service Service name.
* @param string $version API version.
*
* @return array
* @throws UnresolvedApiException
*/
public static function resolve(callable $provider, $type, $service, $version)
{
// Execute the provider and return the result, if there is one.
$result = $provider($type, $service, $version);
if (is_array($result)) {
if (!isset($result['metadata']['serviceIdentifier'])) {
$result['metadata']['serviceIdentifier'] = $service;
}
return $result;
}
// Throw an exception with a message depending on the inputs.
if (!isset(self::$typeMap[$type])) {
$msg = "The type must be one of: " . implode(', ', self::$typeMap);
} elseif ($service) {
$msg = "The {$service} service does not have version: {$version}.";
} else {
$msg = "You must specify a service name to retrieve its API data.";
}
throw new UnresolvedApiException($msg);
}
/**
* Default SDK API provider.
*
* This provider loads pre-built manifest data from the `data` directory.
*
* @return self
*/
public static function defaultProvider()
{
return new self(__DIR__ . '/../data', \Aws\manifest());
}
/**
* Loads API data after resolving the version to the latest, compatible,
* available version based on the provided manifest data.
*
* Manifest data is essentially an associative array of service names to
* associative arrays of API version aliases.
*
* [
* ...
* 'ec2' => [
* 'latest' => '2014-10-01',
* '2014-10-01' => '2014-10-01',
* '2014-09-01' => '2014-10-01',
* '2014-06-15' => '2014-10-01',
* ...
* ],
* 'ecs' => [...],
* 'elasticache' => [...],
* ...
* ]
*
* @param string $dir Directory containing service models.
* @param array $manifest The API version manifest data.
*
* @return self
*/
public static function manifest($dir, array $manifest)
{
return new self($dir, $manifest);
}
/**
* Loads API data from the specified directory.
*
* If "latest" is specified as the version, this provider must glob the
* directory to find which is the latest available version.
*
* @param string $dir Directory containing service models.
*
* @return self
* @throws \InvalidArgumentException if the provided `$dir` is invalid.
*/
public static function filesystem($dir)
{
return new self($dir);
}
/**
* Retrieves a list of valid versions for the specified service.
*
* @param string $service Service name
*
* @return array
*/
public function getVersions($service)
{
if (!isset($this->manifest)) {
$this->buildVersionsList($service);
}
if (!isset($this->manifest[$service]['versions'])) {
return [];
}
return array_values(array_unique($this->manifest[$service]['versions']));
}
/**
* Execute the the provider.
*
* @param string $type Type of data ('api', 'waiter', 'paginator').
* @param string $service Service name.
* @param string $version API version.
*
* @return array|null
*/
public function __invoke($type, $service, $version)
{
// Resolve the type or return null.
if (isset(self::$typeMap[$type])) {
$type = self::$typeMap[$type];
} else {
return null;
}
// Resolve the version or return null.
if (!isset($this->manifest)) {
$this->buildVersionsList($service);
}
if (!isset($this->manifest[$service]['versions'][$version])) {
return null;
}
$version = $this->manifest[$service]['versions'][$version];
$path = "{$this->modelsDir}/{$service}/{$version}/{$type}.json";
try {
return \Aws\load_compiled_json($path);
} catch (\InvalidArgumentException $e) {
return null;
}
}
/**
* @param string $modelsDir Directory containing service models.
* @param array $manifest The API version manifest data.
*/
private function __construct($modelsDir, array $manifest = null)
{
$this->manifest = $manifest;
$this->modelsDir = rtrim($modelsDir, '/');
if (!is_dir($this->modelsDir)) {
throw new \InvalidArgumentException(
"The specified models directory, {$modelsDir}, was not found."
);
}
}
/**
* Build the versions list for the specified service by globbing the dir.
*/
private function buildVersionsList($service)
{
$dir = "{$this->modelsDir}/{$service}/";
if (!is_dir($dir)) {
return;
}
// Get versions, remove . and .., and sort in descending order.
$results = array_diff(scandir($dir, SCANDIR_SORT_DESCENDING), ['..', '.']);
if (!$results) {
$this->manifest[$service] = ['versions' => []];
} else {
$this->manifest[$service] = [
'versions' => [
'latest' => $results[0]
]
];
$this->manifest[$service]['versions'] += array_combine($results, $results);
}
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace Aws\Api;
/**
* DateTime overrides that make DateTime work more seamlessly as a string,
* with JSON documents, and with JMESPath.
*/
class DateTimeResult extends \DateTime implements \JsonSerializable
{
/**
* Create a new DateTimeResult from a unix timestamp.
*
* @param $unixTimestamp
*
* @return DateTimeResult
*/
public static function fromEpoch($unixTimestamp)
{
return new self(gmdate('c', $unixTimestamp));
}
/**
* Serialize the DateTimeResult as an ISO 8601 date string.
*
* @return string
*/
public function __toString()
{
return $this->format('c');
}
/**
* Serialize the date as an ISO 8601 date when serializing as JSON.
*
* @return mixed|string
*/
public function jsonSerialize()
{
return (string) $this;
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace Aws\Api;
/**
* Encapsulates the documentation strings for a given service-version and
* provides methods for extracting the desired parts related to a service,
* operation, error, or shape (i.e., parameter).
*/
class DocModel
{
/** @var array */
private $docs;
/**
* @param array $docs
*
* @throws \RuntimeException
*/
public function __construct(array $docs)
{
if (!extension_loaded('tidy')) {
throw new \RuntimeException('The "tidy" PHP extension is required.');
}
$this->docs = $docs;
}
/**
* Convert the doc model to an array.
*
* @return array
*/
public function toArray()
{
return $this->docs;
}
/**
* Retrieves documentation about the service.
*
* @return null|string
*/
public function getServiceDocs()
{
return isset($this->docs['service']) ? $this->docs['service'] : null;
}
/**
* Retrieves documentation about an operation.
*
* @param string $operation Name of the operation
*
* @return null|string
*/
public function getOperationDocs($operation)
{
return isset($this->docs['operations'][$operation])
? $this->docs['operations'][$operation]
: null;
}
/**
* Retrieves documentation about an error.
*
* @param string $error Name of the error
*
* @return null|string
*/
public function getErrorDocs($error)
{
return isset($this->docs['shapes'][$error]['base'])
? $this->docs['shapes'][$error]['base']
: null;
}
/**
* Retrieves documentation about a shape, specific to the context.
*
* @param string $shapeName Name of the shape.
* @param string $parentName Name of the parent/context shape.
* @param string $ref Name used by the context to reference the shape.
*
* @return null|string
*/
public function getShapeDocs($shapeName, $parentName, $ref)
{
if (!isset($this->docs['shapes'][$shapeName])) {
return '';
}
$result = '';
$d = $this->docs['shapes'][$shapeName];
if (isset($d['refs']["{$parentName}\$${ref}"])) {
$result = $d['refs']["{$parentName}\$${ref}"];
} elseif (isset($d['base'])) {
$result = $d['base'];
}
if (isset($d['append'])) {
$result .= $d['append'];
}
return $this->clean($result);
}
private function clean($content)
{
if (!$content) {
return '';
}
$tidy = new \Tidy();
$tidy->parseString($content, [
'indent' => true,
'doctype' => 'omit',
'output-html' => true,
'show-body-only' => true,
'drop-empty-paras' => true,
'drop-font-tags' => true,
'drop-proprietary-attributes' => true,
'hide-comments' => true,
'logical-emphasis' => true
]);
$tidy->cleanRepair();
return (string) $content;
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Aws\Api\ErrorParser;
use Aws\Api\Parser\PayloadParserTrait;
use Psr\Http\Message\ResponseInterface;
/**
* Provides basic JSON error parsing functionality.
*/
trait JsonParserTrait
{
use PayloadParserTrait;
private function genericHandler(ResponseInterface $response)
{
$code = (string) $response->getStatusCode();
return [
'request_id' => (string) $response->getHeaderLine('x-amzn-requestid'),
'code' => null,
'message' => null,
'type' => $code[0] == '4' ? 'client' : 'server',
'parsed' => $this->parseJson($response->getBody())
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace Aws\Api\ErrorParser;
use Psr\Http\Message\ResponseInterface;
/**
* Parsers JSON-RPC errors.
*/
class JsonRpcErrorParser
{
use JsonParserTrait;
public function __invoke(ResponseInterface $response)
{
$data = $this->genericHandler($response);
// Make the casing consistent across services.
if ($data['parsed']) {
$data['parsed'] = array_change_key_case($data['parsed']);
}
if (isset($data['parsed']['__type'])) {
$parts = explode('#', $data['parsed']['__type']);
$data['code'] = isset($parts[1]) ? $parts[1] : $parts[0];
$data['message'] = isset($data['parsed']['message'])
? $data['parsed']['message']
: null;
}
return $data;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Aws\Api\ErrorParser;
use Psr\Http\Message\ResponseInterface;
/**
* Parses JSON-REST errors.
*/
class RestJsonErrorParser
{
use JsonParserTrait;
public function __invoke(ResponseInterface $response)
{
$data = $this->genericHandler($response);
// Merge in error data from the JSON body
if ($json = $data['parsed']) {
$data = array_replace($data, $json);
}
// Correct error type from services like Amazon Glacier
if (!empty($data['type'])) {
$data['type'] = strtolower($data['type']);
}
// Retrieve the error code from services like Amazon Elastic Transcoder
if ($code = $response->getHeaderLine('x-amzn-errortype')) {
$colon = strpos($code, ':');
$data['code'] = $colon ? substr($code, 0, $colon) : $code;
}
return $data;
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace Aws\Api\ErrorParser;
use Aws\Api\Parser\PayloadParserTrait;
use Psr\Http\Message\ResponseInterface;
/**
* Parses XML errors.
*/
class XmlErrorParser
{
use PayloadParserTrait;
public function __invoke(ResponseInterface $response)
{
$code = (string) $response->getStatusCode();
$data = [
'type' => $code[0] == '4' ? 'client' : 'server',
'request_id' => null,
'code' => null,
'message' => null,
'parsed' => null
];
$body = $response->getBody();
if ($body->getSize() > 0) {
$this->parseBody($this->parseXml($body), $data);
} else {
$this->parseHeaders($response, $data);
}
return $data;
}
private function parseHeaders(ResponseInterface $response, array &$data)
{
if ($response->getStatusCode() == '404') {
$data['code'] = 'NotFound';
}
$data['message'] = $response->getStatusCode() . ' '
. $response->getReasonPhrase();
if ($requestId = $response->getHeaderLine('x-amz-request-id')) {
$data['request_id'] = $requestId;
$data['message'] .= " (Request-ID: $requestId)";
}
}
private function parseBody(\SimpleXMLElement $body, array &$data)
{
$data['parsed'] = $body;
$namespaces = $body->getDocNamespaces();
if (!isset($namespaces[''])) {
$prefix = '';
} else {
// Account for the default namespace being defined and PHP not
// being able to handle it :(.
$body->registerXPathNamespace('ns', $namespaces['']);
$prefix = 'ns:';
}
if ($tempXml = $body->xpath("//{$prefix}Code[1]")) {
$data['code'] = (string) $tempXml[0];
}
if ($tempXml = $body->xpath("//{$prefix}Message[1]")) {
$data['message'] = (string) $tempXml[0];
}
$tempXml = $body->xpath("//{$prefix}RequestId[1]");
if (empty($tempXml)) {
$tempXml = $body->xpath("//{$prefix}RequestID[1]");
}
if (isset($tempXml[0])) {
$data['request_id'] = (string) $tempXml[0];
}
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Aws\Api;
/**
* Represents a list shape.
*/
class ListShape extends Shape
{
private $member;
public function __construct(array $definition, ShapeMap $shapeMap)
{
$definition['type'] = 'list';
parent::__construct($definition, $shapeMap);
}
/**
* @return Shape
* @throws \RuntimeException if no member is specified
*/
public function getMember()
{
if (!$this->member) {
if (!isset($this->definition['member'])) {
throw new \RuntimeException('No member attribute specified');
}
$this->member = Shape::create(
$this->definition['member'],
$this->shapeMap
);
}
return $this->member;
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Aws\Api;
/**
* Represents a map shape.
*/
class MapShape extends Shape
{
/** @var Shape */
private $value;
/** @var Shape */
private $key;
public function __construct(array $definition, ShapeMap $shapeMap)
{
$definition['type'] = 'map';
parent::__construct($definition, $shapeMap);
}
/**
* @return Shape
* @throws \RuntimeException if no value is specified
*/
public function getValue()
{
if (!$this->value) {
if (!isset($this->definition['value'])) {
throw new \RuntimeException('No value specified');
}
$this->value = Shape::create(
$this->definition['value'],
$this->shapeMap
);
}
return $this->value;
}
/**
* @return Shape
*/
public function getKey()
{
if (!$this->key) {
$this->key = isset($this->definition['key'])
? Shape::create($this->definition['key'], $this->shapeMap)
: new Shape(['type' => 'string'], $this->shapeMap);
}
return $this->key;
}
}

View File

@@ -0,0 +1,97 @@
<?php
namespace Aws\Api;
/**
* Represents an API operation.
*/
class Operation extends AbstractModel
{
private $input;
private $output;
private $errors;
public function __construct(array $definition, ShapeMap $shapeMap)
{
$definition['type'] = 'structure';
if (!isset($definition['http']['method'])) {
$definition['http']['method'] = 'POST';
}
if (!isset($definition['http']['requestUri'])) {
$definition['http']['requestUri'] = '/';
}
parent::__construct($definition, $shapeMap);
}
/**
* Returns an associative array of the HTTP attribute of the operation:
*
* - method: HTTP method of the operation
* - requestUri: URI of the request (can include URI template placeholders)
*
* @return array
*/
public function getHttp()
{
return $this->definition['http'];
}
/**
* Get the input shape of the operation.
*
* @return StructureShape
*/
public function getInput()
{
if (!$this->input) {
if ($input = $this['input']) {
$this->input = $this->shapeFor($input);
} else {
$this->input = new StructureShape([], $this->shapeMap);
}
}
return $this->input;
}
/**
* Get the output shape of the operation.
*
* @return StructureShape
*/
public function getOutput()
{
if (!$this->output) {
if ($output = $this['output']) {
$this->output = $this->shapeFor($output);
} else {
$this->output = new StructureShape([], $this->shapeMap);
}
}
return $this->output;
}
/**
* Get an array of operation error shapes.
*
* @return Shape[]
*/
public function getErrors()
{
if ($this->errors === null) {
if ($errors = $this['errors']) {
foreach ($errors as &$error) {
$error = $this->shapeFor($error);
}
$this->errors = $errors;
} else {
$this->errors = [];
}
}
return $this->errors;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Aws\Api\Parser;
use Aws\Api\Service;
use Aws\CommandInterface;
use Aws\ResultInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @internal
*/
abstract class AbstractParser
{
/** @var \Aws\Api\Service Representation of the service API*/
protected $api;
/**
* @param Service $api Service description.
*/
public function __construct(Service $api)
{
$this->api = $api;
}
/**
* @param CommandInterface $command Command that was executed.
* @param ResponseInterface $response Response that was received.
*
* @return ResultInterface
*/
abstract public function __invoke(
CommandInterface $command,
ResponseInterface $response
);
}

View File

@@ -0,0 +1,157 @@
<?php
namespace Aws\Api\Parser;
use Aws\Api\DateTimeResult;
use Aws\Api\Shape;
use Aws\Api\StructureShape;
use Aws\Result;
use Aws\CommandInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @internal
*/
abstract class AbstractRestParser extends AbstractParser
{
/**
* Parses a payload from a response.
*
* @param ResponseInterface $response Response to parse.
* @param StructureShape $member Member to parse
* @param array $result Result value
*
* @return mixed
*/
abstract protected function payload(
ResponseInterface $response,
StructureShape $member,
array &$result
);
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
&& count($output->getMembers()) > 0
) {
// if no payload was found, then parse the contents of the body
$this->payload($response, $output, $result);
}
return new Result($result);
}
private function extractPayload(
$payload,
StructureShape $output,
ResponseInterface $response,
array &$result
) {
$member = $output->getMember($payload);
if ($member instanceof StructureShape) {
// Structure members parse top-level data into a specific key.
$result[$payload] = [];
$this->payload($response, $member, $result[$payload]);
} else {
// Streaming data is just the stream from the response body.
$result[$payload] = $response->getBody();
}
}
/**
* Extract a single header from the response into the result.
*/
private function extractHeader(
$name,
Shape $shape,
ResponseInterface $response,
&$result
) {
$value = $response->getHeaderLine($shape['locationName'] ?: $name);
switch ($shape->getType()) {
case 'float':
case 'double':
$value = (float) $value;
break;
case 'long':
$value = (int) $value;
break;
case 'boolean':
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
break;
case 'blob':
$value = base64_decode($value);
break;
case 'timestamp':
try {
$value = new DateTimeResult($value);
break;
} catch (\Exception $e) {
// If the value cannot be parsed, then do not add it to the
// output structure.
return;
}
}
$result[$name] = $value;
}
/**
* Extract a map of headers with an optional prefix from the response.
*/
private function extractHeaders(
$name,
Shape $shape,
ResponseInterface $response,
&$result
) {
// Check if the headers are prefixed by a location name
$result[$name] = [];
$prefix = $shape['locationName'];
$prefixLen = strlen($prefix);
foreach ($response->getHeaders() as $k => $values) {
if (!$prefixLen) {
$result[$name][$k] = implode(', ', $values);
} elseif (stripos($k, $prefix) === 0) {
$result[$name][substr($k, $prefixLen)] = implode(', ', $values);
}
}
}
/**
* Places the status code of the response into the result array.
*/
private function extractStatus(
$name,
ResponseInterface $response,
array &$result
) {
$result[$name] = (int) $response->getStatusCode();
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Aws\Api\Parser;
use Aws\CommandInterface;
use Aws\Exception\AwsException;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Psr7;
/**
* @internal Decorates a parser and validates the x-amz-crc32 header.
*/
class Crc32ValidatingParser extends AbstractParser
{
/** @var callable */
private $parser;
/**
* @param callable $parser Parser to wrap.
*/
public function __construct(callable $parser)
{
$this->parser = $parser;
}
public function __invoke(
CommandInterface $command,
ResponseInterface $response
) {
if ($expected = $response->getHeaderLine('x-amz-crc32')) {
$hash = hexdec(Psr7\hash($response->getBody(), 'crc32b'));
if ($expected != $hash) {
throw new AwsException(
"crc32 mismatch. Expected {$expected}, found {$hash}.",
$command,
[
'code' => 'ClientChecksumMismatch',
'connection_error' => true,
'response' => $response
]
);
}
}
$fn = $this->parser;
return $fn($command, $response);
}
}

View File

@@ -0,0 +1,4 @@
<?php
namespace Aws\Api\Parser\Exception;
class ParserException extends \RuntimeException {}

View File

@@ -0,0 +1,58 @@
<?php
namespace Aws\Api\Parser;
use Aws\Api\DateTimeResult;
use Aws\Api\Shape;
/**
* @internal Implements standard JSON parsing.
*/
class JsonParser
{
public function parse(Shape $shape, $value)
{
if ($value === null) {
return $value;
}
switch ($shape['type']) {
case 'structure':
$target = [];
foreach ($shape->getMembers() as $name => $member) {
$locationName = $member['locationName'] ?: $name;
if (isset($value[$locationName])) {
$target[$name] = $this->parse($member, $value[$locationName]);
}
}
return $target;
case 'list':
$member = $shape->getMember();
$target = [];
foreach ($value as $v) {
$target[] = $this->parse($member, $v);
}
return $target;
case 'map':
$values = $shape->getValue();
$target = [];
foreach ($value as $k => $v) {
$target[$k] = $this->parse($values, $v);
}
return $target;
case 'timestamp':
// The Unix epoch (or Unix time or POSIX time or Unix
// timestamp) is the number of seconds that have elapsed since
// January 1, 1970 (midnight UTC/GMT).
return DateTimeResult::fromEpoch($value);
case 'blob':
return base64_decode($value);
default:
return $value;
}
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Aws\Api\Parser;
use Aws\Api\Service;
use Aws\Result;
use Aws\CommandInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @internal Implements JSON-RPC parsing (e.g., DynamoDB)
*/
class JsonRpcParser extends AbstractParser
{
use PayloadParserTrait;
private $parser;
/**
* @param Service $api Service description
* @param JsonParser $parser JSON body builder
*/
public function __construct(Service $api, JsonParser $parser = null)
{
parent::__construct($api);
$this->parser = $parser ?: new JsonParser();
}
public function __invoke(
CommandInterface $command,
ResponseInterface $response
) {
$operation = $this->api->getOperation($command->getName());
$result = null === $operation['output']
? null
: $this->parser->parse(
$operation->getOutput(),
$this->parseJson($response->getBody())
);
return new Result($result ?: []);
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Aws\Api\Parser;
use Aws\Api\Parser\Exception\ParserException;
trait PayloadParserTrait
{
/**
* @param string $json
*
* @throws ParserException
*
* @return array
*/
private function parseJson($json)
{
$jsonPayload = json_decode($json, true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new ParserException('Error parsing JSON: '
. json_last_error_msg());
}
return $jsonPayload;
}
/**
* @param string $xml
*
* @throws ParserException
*
* @return \SimpleXMLElement
*/
private function parseXml($xml)
{
$priorSetting = libxml_use_internal_errors(true);
try {
libxml_clear_errors();
$xmlPayload = new \SimpleXMLElement($xml);
if ($error = libxml_get_last_error()) {
throw new \RuntimeException($error->message);
}
} catch (\Exception $e) {
throw new ParserException("Error parsing XML: {$e->getMessage()}", 0, $e);
} finally {
libxml_use_internal_errors($priorSetting);
}
return $xmlPayload;
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Aws\Api\Parser;
use Aws\Api\Service;
use Aws\Result;
use Aws\CommandInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @internal Parses query (XML) responses (e.g., EC2, SQS, and many others)
*/
class QueryParser extends AbstractParser
{
use PayloadParserTrait;
/** @var XmlParser */
private $xmlParser;
/** @var bool */
private $honorResultWrapper;
/**
* @param Service $api Service description
* @param XmlParser $xmlParser Optional XML parser
* @param bool $honorResultWrapper Set to false to disable the peeling
* back of result wrappers from the
* output structure.
*/
public function __construct(
Service $api,
XmlParser $xmlParser = null,
$honorResultWrapper = true
) {
parent::__construct($api);
$this->xmlParser = $xmlParser ?: new XmlParser();
$this->honorResultWrapper = $honorResultWrapper;
}
public function __invoke(
CommandInterface $command,
ResponseInterface $response
) {
$output = $this->api->getOperation($command->getName())->getOutput();
$xml = $this->parseXml($response->getBody());
if ($this->honorResultWrapper && $output['resultWrapper']) {
$xml = $xml->{$output['resultWrapper']};
}
return new Result($this->xmlParser->parse($output, $xml));
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace Aws\Api\Parser;
use Aws\Api\Service;
use Aws\Api\StructureShape;
use Psr\Http\Message\ResponseInterface;
/**
* @internal Implements REST-JSON parsing (e.g., Glacier, Elastic Transcoder)
*/
class RestJsonParser extends AbstractRestParser
{
use PayloadParserTrait;
/** @var JsonParser */
private $parser;
/**
* @param Service $api Service description
* @param JsonParser $parser JSON body builder
*/
public function __construct(Service $api, JsonParser $parser = null)
{
parent::__construct($api);
$this->parser = $parser ?: new JsonParser();
}
protected function payload(
ResponseInterface $response,
StructureShape $member,
array &$result
) {
$jsonBody = $this->parseJson($response->getBody());
if ($jsonBody) {
$result += $this->parser->parse($member, $jsonBody);
}
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Aws\Api\Parser;
use Aws\Api\StructureShape;
use Aws\Api\Service;
use Psr\Http\Message\ResponseInterface;
/**
* @internal Implements REST-XML parsing (e.g., S3, CloudFront, etc...)
*/
class RestXmlParser extends AbstractRestParser
{
use PayloadParserTrait;
/** @var XmlParser */
private $parser;
/**
* @param Service $api Service description
* @param XmlParser $parser XML body parser
*/
public function __construct(Service $api, XmlParser $parser = null)
{
parent::__construct($api);
$this->parser = $parser ?: new XmlParser();
}
protected function payload(
ResponseInterface $response,
StructureShape $member,
array &$result
) {
$xml = $this->parseXml($response->getBody());
$result += $this->parser->parse($member, $xml);
}
}

View File

@@ -0,0 +1,134 @@
<?php
namespace Aws\Api\Parser;
use Aws\Api\DateTimeResult;
use Aws\Api\ListShape;
use Aws\Api\MapShape;
use Aws\Api\Shape;
use Aws\Api\StructureShape;
/**
* @internal Implements standard XML parsing for REST-XML and Query protocols.
*/
class XmlParser
{
public function parse(StructureShape $shape, \SimpleXMLElement $value)
{
return $this->dispatch($shape, $value);
}
private function dispatch($shape, \SimpleXMLElement $value)
{
static $methods = [
'structure' => 'parse_structure',
'list' => 'parse_list',
'map' => 'parse_map',
'blob' => 'parse_blob',
'boolean' => 'parse_boolean',
'integer' => 'parse_integer',
'float' => 'parse_float',
'double' => 'parse_float',
'timestamp' => 'parse_timestamp',
];
$type = $shape['type'];
if (isset($methods[$type])) {
return $this->{$methods[$type]}($shape, $value);
}
return (string) $value;
}
private function parse_structure(
StructureShape $shape,
\SimpleXMLElement $value
) {
$target = [];
foreach ($shape->getMembers() as $name => $member) {
// Extract the name of the XML node
$node = $this->memberKey($member, $name);
if (isset($value->{$node})) {
$target[$name] = $this->dispatch($member, $value->{$node});
}
}
return $target;
}
private function memberKey(Shape $shape, $name)
{
if (null !== $shape['locationName']) {
return $shape['locationName'];
}
if ($shape instanceof ListShape && $shape['flattened']) {
return $shape->getMember()['locationName'] ?: $name;
}
return $name;
}
private function parse_list(ListShape $shape, \SimpleXMLElement $value)
{
$target = [];
$member = $shape->getMember();
if (!$shape['flattened']) {
$value = $value->{$member['locationName'] ?: 'member'};
}
foreach ($value as $v) {
$target[] = $this->dispatch($member, $v);
}
return $target;
}
private function parse_map(MapShape $shape, \SimpleXMLElement $value)
{
$target = [];
if (!$shape['flattened']) {
$value = $value->entry;
}
$mapKey = $shape->getKey();
$mapValue = $shape->getValue();
$keyName = $shape->getKey()['locationName'] ?: 'key';
$valueName = $shape->getValue()['locationName'] ?: 'value';
foreach ($value as $node) {
$key = $this->dispatch($mapKey, $node->{$keyName});
$value = $this->dispatch($mapValue, $node->{$valueName});
$target[$key] = $value;
}
return $target;
}
private function parse_blob(Shape $shape, $value)
{
return base64_decode((string) $value);
}
private function parse_float(Shape $shape, $value)
{
return (float) (string) $value;
}
private function parse_integer(Shape $shape, $value)
{
return (int) (string) $value;
}
private function parse_boolean(Shape $shape, $value)
{
return $value == 'true' ? true : false;
}
private function parse_timestamp(Shape $shape, $value)
{
return new DateTimeResult($value);
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace Aws\Api\Serializer;
use Aws\Api\Shape;
use Aws\Api\ListShape;
/**
* @internal
*/
class Ec2ParamBuilder extends QueryParamBuilder
{
protected function queryName(Shape $shape, $default = null)
{
return ($shape['queryName']
?: ucfirst($shape['locationName']))
?: $default;
}
protected function isFlat(Shape $shape)
{
return false;
}
protected function format_list(
ListShape $shape,
array $value,
$prefix,
&$query
) {
// Handle empty list serialization
if (!$value) {
$query[$prefix] = false;
} else {
$items = $shape->getMember();
foreach ($value as $k => $v) {
$this->format($items, $v, $prefix . '.' . ($k + 1), $query);
}
}
}
}

View File

@@ -0,0 +1,90 @@
<?php
namespace Aws\Api\Serializer;
use Aws\Api\Service;
use Aws\Api\Shape;
use Aws\Api\TimestampShape;
/**
* Formats the JSON body of a JSON-REST or JSON-RPC operation.
* @internal
*/
class JsonBody
{
private $api;
public function __construct(Service $api)
{
$this->api = $api;
}
/**
* Gets the JSON Content-Type header for a service API
*
* @param Service $service
*
* @return string
*/
public static function getContentType(Service $service)
{
return 'application/x-amz-json-'
. number_format($service->getMetadata('jsonVersion'), 1);
}
/**
* Builds the JSON body based on an array of arguments.
*
* @param Shape $shape Operation being constructed
* @param array $args Associative array of arguments
*
* @return string
*/
public function build(Shape $shape, array $args)
{
$result = json_encode($this->format($shape, $args));
return $result == '[]' ? '{}' : $result;
}
private function format(Shape $shape, $value)
{
switch ($shape['type']) {
case 'structure':
$data = [];
foreach ($value as $k => $v) {
if ($v !== null && $shape->hasMember($k)) {
$valueShape = $shape->getMember($k);
$data[$valueShape['locationName'] ?: $k]
= $this->format($valueShape, $v);
}
}
return $data;
case 'list':
$items = $shape->getMember();
foreach ($value as &$v) {
$v = $this->format($items, $v);
}
return $value;
case 'map':
if (empty($value)) {
return new \stdClass;
}
$values = $shape->getValue();
foreach ($value as &$v) {
$v = $this->format($values, $v);
}
return $value;
case 'blob':
return base64_encode($value);
case 'timestamp':
return TimestampShape::format($value, 'unixTimestamp');
default:
return $value;
}
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Aws\Api\Serializer;
use Aws\Api\Service;
use Aws\CommandInterface;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\RequestInterface;
/**
* Prepares a JSON-RPC request for transfer.
* @internal
*/
class JsonRpcSerializer
{
/** @var JsonBody */
private $jsonFormatter;
/** @var string */
private $endpoint;
/** @var Service */
private $api;
/** @var string */
private $contentType;
/**
* @param Service $api Service description
* @param string $endpoint Endpoint to connect to
* @param JsonBody $jsonFormatter Optional JSON formatter to use
*/
public function __construct(
Service $api,
$endpoint,
JsonBody $jsonFormatter = null
) {
$this->endpoint = $endpoint;
$this->api = $api;
$this->jsonFormatter = $jsonFormatter ?: new JsonBody($this->api);
$this->contentType = JsonBody::getContentType($api);
}
/**
* 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()
)
);
}
}

View File

@@ -0,0 +1,154 @@
<?php
namespace Aws\Api\Serializer;
use Aws\Api\StructureShape;
use Aws\Api\ListShape;
use Aws\Api\MapShape;
use Aws\Api\Shape;
use Aws\Api\TimestampShape;
/**
* @internal
*/
class QueryParamBuilder
{
private $methods;
protected function queryName(Shape $shape, $default = null)
{
if (null !== $shape['queryName']) {
return $shape['queryName'];
}
if (null !== $shape['locationName']) {
return $shape['locationName'];
}
if ($this->isFlat($shape) && !empty($shape['member']['locationName'])) {
return $shape['member']['locationName'];
}
return $default;
}
protected function isFlat(Shape $shape)
{
return $shape['flattened'] === true;
}
public function __invoke(StructureShape $shape, array $params)
{
if (!$this->methods) {
$this->methods = array_fill_keys(get_class_methods($this), true);
}
$query = [];
$this->format_structure($shape, $params, '', $query);
return $query;
}
protected function format(Shape $shape, $value, $prefix, array &$query)
{
$type = 'format_' . $shape['type'];
if (isset($this->methods[$type])) {
$this->{$type}($shape, $value, $prefix, $query);
} else {
$query[$prefix] = (string) $value;
}
}
protected function format_structure(
StructureShape $shape,
array $value,
$prefix,
&$query
) {
if ($prefix) {
$prefix .= '.';
}
foreach ($value as $k => $v) {
if ($shape->hasMember($k)) {
$member = $shape->getMember($k);
$this->format(
$member,
$v,
$prefix . $this->queryName($member, $k),
$query
);
}
}
}
protected function format_list(
ListShape $shape,
array $value,
$prefix,
&$query
) {
// Handle empty list serialization
if (!$value) {
$query[$prefix] = '';
return;
}
$items = $shape->getMember();
if (!$this->isFlat($shape)) {
$locationName = $shape->getMember()['locationName'] ?: 'member';
$prefix .= ".$locationName";
} elseif ($name = $this->queryName($items)) {
$parts = explode('.', $prefix);
$parts[count($parts) - 1] = $name;
$prefix = implode('.', $parts);
}
foreach ($value as $k => $v) {
$this->format($items, $v, $prefix . '.' . ($k + 1), $query);
}
}
protected function format_map(
MapShape $shape,
array $value,
$prefix,
array &$query
) {
$vals = $shape->getValue();
$keys = $shape->getKey();
if (!$this->isFlat($shape)) {
$prefix .= '.entry';
}
$i = 0;
$keyName = '%s.%d.' . $this->queryName($keys, 'key');
$valueName = '%s.%s.' . $this->queryName($vals, 'value');
foreach ($value as $k => $v) {
$i++;
$this->format($keys, $k, sprintf($keyName, $prefix, $i), $query);
$this->format($vals, $v, sprintf($valueName, $prefix, $i), $query);
}
}
protected function format_blob(Shape $shape, $value, $prefix, array &$query)
{
$query[$prefix] = base64_encode($value);
}
protected function format_timestamp(
TimestampShape $shape,
$value,
$prefix,
array &$query
) {
$query[$prefix] = TimestampShape::format($value, 'iso8601');
}
protected function format_boolean(Shape $shape, $value, $prefix, array &$query)
{
$query[$prefix] = ($value) ? 'true' : 'false';
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Aws\Api\Serializer;
use Aws\Api\Service;
use Aws\CommandInterface;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\RequestInterface;
/**
* Serializes a query protocol request.
* @internal
*/
class QuerySerializer
{
private $endpoint;
private $api;
private $paramBuilder;
public function __construct(
Service $api,
$endpoint,
callable $paramBuilder = null
) {
$this->api = $api;
$this->endpoint = $endpoint;
$this->paramBuilder = $paramBuilder ?: new QueryParamBuilder();
}
/**
* 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
);
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace Aws\Api\Serializer;
use Aws\Api\Service;
use Aws\Api\StructureShape;
/**
* Serializes requests for the REST-JSON protocol.
* @internal
*/
class RestJsonSerializer extends RestSerializer
{
/** @var JsonBody */
private $jsonFormatter;
/** @var string */
private $contentType;
/**
* @param Service $api Service API description
* @param string $endpoint Endpoint to connect to
* @param JsonBody $jsonFormatter Optional JSON formatter to use
*/
public function __construct(
Service $api,
$endpoint,
JsonBody $jsonFormatter = null
) {
parent::__construct($api, $endpoint);
$this->contentType = JsonBody::getContentType($api);
$this->jsonFormatter = $jsonFormatter ?: new JsonBody($api);
}
protected function payload(StructureShape $member, array $value, array &$opts)
{
$opts['headers']['Content-Type'] = $this->contentType;
$opts['body'] = (string) $this->jsonFormatter->build($member, $value);
}
}

View File

@@ -0,0 +1,197 @@
<?php
namespace Aws\Api\Serializer;
use Aws\Api\MapShape;
use Aws\Api\Service;
use Aws\Api\Operation;
use Aws\Api\Shape;
use Aws\Api\StructureShape;
use Aws\Api\TimestampShape;
use Aws\CommandInterface;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
/**
* Serializes HTTP locations like header, uri, payload, etc...
* @internal
*/
abstract class RestSerializer
{
/** @var Service */
private $api;
/** @var Psr7\Uri */
private $endpoint;
/**
* @param Service $api Service API description
* @param string $endpoint Endpoint to connect to
*/
public function __construct(Service $api, $endpoint)
{
$this->api = $api;
$this->endpoint = Psr7\uri_for($endpoint);
}
/**
* @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
);
}
/**
* Modifies a hash of request options for a payload body.
*
* @param StructureShape $member Member to serialize
* @param array $value Value to serialize
* @param array $opts Request options to modify.
*/
abstract protected function payload(
StructureShape $member,
array $value,
array &$opts
);
private function serialize(Operation $operation, array $args)
{
$opts = [];
$input = $operation->getInput();
// Apply the payload trait if present
if ($payload = $input['payload']) {
$this->applyPayload($input, $payload, $args, $opts);
}
foreach ($args as $name => $value) {
if ($input->hasMember($name)) {
$member = $input->getMember($name);
$location = $member['location'];
if (!$payload && !$location) {
$bodyMembers[$name] = $value;
} elseif ($location == 'header') {
$this->applyHeader($name, $member, $value, $opts);
} elseif ($location == 'querystring') {
$this->applyQuery($name, $member, $value, $opts);
} elseif ($location == 'headers') {
$this->applyHeaderMap($name, $member, $value, $opts);
}
}
}
if (isset($bodyMembers)) {
$this->payload($operation->getInput(), $bodyMembers, $opts);
}
return $opts;
}
private function applyPayload(StructureShape $input, $name, array $args, array &$opts)
{
if (!isset($args[$name])) {
return;
}
$m = $input->getMember($name);
if ($m['streaming'] ||
($m['type'] == 'string' || $m['type'] == 'blob')
) {
// Streaming bodies or payloads that are strings are
// always just a stream of data.
$opts['body'] = Psr7\stream_for($args[$name]);
return;
}
$this->payload($m, $args[$name], $opts);
}
private function applyHeader($name, Shape $member, $value, array &$opts)
{
if ($member->getType() == 'timestamp') {
$value = TimestampShape::format($value, 'rfc822');
}
$opts['headers'][$member['locationName'] ?: $name] = $value;
}
/**
* Note: This is currently only present in the Amazon S3 model.
*/
private function applyHeaderMap($name, Shape $member, array $value, array &$opts)
{
$prefix = $member['locationName'];
foreach ($value as $k => $v) {
$opts['headers'][$prefix . $k] = $v;
}
}
private function applyQuery($name, Shape $member, $value, array &$opts)
{
if ($member instanceof MapShape) {
$opts['query'] = isset($opts['query']) && is_array($opts['query'])
? $opts['query'] + $value
: $value;
} elseif ($value !== null) {
if ($member->getType() === 'boolean') {
$value = $value ? 'true' : 'false';
}
$opts['query'][$member['locationName'] ?: $name] = $value;
}
}
private function buildEndpoint(Operation $operation, array $args, array $opts)
{
$varspecs = [];
// Create an associative array of varspecs used in expansions
foreach ($operation->getInput()->getMembers() as $name => $member) {
if ($member['location'] == 'uri') {
$varspecs[$member['locationName'] ?: $name] =
isset($args[$name])
? $args[$name]
: null;
}
}
$relative = preg_replace_callback(
'/\{([^\}]+)\}/',
function (array $matches) use ($varspecs) {
$isGreedy = substr($matches[1], -1, 1) == '+';
$k = $isGreedy ? substr($matches[1], 0, -1) : $matches[1];
if (!isset($varspecs[$k])) {
return '';
} elseif ($isGreedy) {
return str_replace('%2F', '/', rawurlencode($varspecs[$k]));
} else {
return rawurlencode($varspecs[$k]);
}
},
$operation['http']['requestUri']
);
// Add the query string variables or appending to one if needed.
if (!empty($opts['query'])) {
$append = Psr7\build_query($opts['query']);
$relative .= strpos($relative, '?') ? "&{$append}" : "?$append";
}
// Expand path place holders using Amazon's slightly different URI
// template syntax.
return Psr7\Uri::resolve($this->endpoint, $relative);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Aws\Api\Serializer;
use Aws\Api\StructureShape;
use Aws\Api\Service;
/**
* @internal
*/
class RestXmlSerializer extends RestSerializer
{
/** @var XmlBody */
private $xmlBody;
/**
* @param Service $api Service API description
* @param string $endpoint Endpoint to connect to
* @param XmlBody $xmlBody Optional XML formatter to use
*/
public function __construct(
Service $api,
$endpoint,
XmlBody $xmlBody = null
) {
parent::__construct($api, $endpoint);
$this->xmlBody = $xmlBody ?: new XmlBody($api);
}
protected function payload(StructureShape $member, array $value, array &$opts)
{
$opts['headers']['Content-Type'] = 'application/xml';
$opts['body'] = (string) $this->xmlBody->build($member, $value);
}
}

View File

@@ -0,0 +1,217 @@
<?php
namespace Aws\Api\Serializer;
use Aws\Api\MapShape;
use Aws\Api\Service;
use Aws\Api\Shape;
use Aws\Api\StructureShape;
use Aws\Api\ListShape;
use Aws\Api\TimestampShape;
use XMLWriter;
/**
* @internal Formats the XML body of a REST-XML services.
*/
class XmlBody
{
/** @var \Aws\Api\Service */
private $api;
/**
* @param Service $api API being used to create the XML body.
*/
public function __construct(Service $api)
{
$this->api = $api;
}
/**
* Builds the XML body based on an array of arguments.
*
* @param Shape $shape Operation being constructed
* @param array $args Associative array of arguments
*
* @return string
*/
public function build(Shape $shape, array $args)
{
$xml = new XMLWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$this->format($shape, $shape['locationName'], $args, $xml);
$xml->endDocument();
return $xml->outputMemory();
}
private function startElement(Shape $shape, $name, XMLWriter $xml)
{
$xml->startElement($name);
if ($ns = $shape['xmlNamespace']) {
$xml->writeAttribute(
isset($ns['prefix']) ? "xmlns:{$ns['prefix']}" : 'xmlns',
$shape['xmlNamespace']['uri']
);
}
}
private function format(Shape $shape, $name, $value, XMLWriter $xml)
{
// Any method mentioned here has a custom serialization handler.
static $methods = [
'add_structure' => true,
'add_list' => true,
'add_blob' => true,
'add_timestamp' => true,
'add_boolean' => true,
'add_map' => true,
'add_string' => true
];
$type = 'add_' . $shape['type'];
if (isset($methods[$type])) {
$this->{$type}($shape, $name, $value, $xml);
} else {
$this->defaultShape($shape, $name, $value, $xml);
}
}
private function defaultShape(Shape $shape, $name, $value, XMLWriter $xml)
{
$this->startElement($shape, $name, $xml);
$xml->writeRaw($value);
$xml->endElement();
}
private function add_structure(
StructureShape $shape,
$name,
array $value,
\XMLWriter $xml
) {
$this->startElement($shape, $name, $xml);
foreach ($this->getStructureMembers($shape, $value) as $k => $definition) {
$this->format(
$definition['member'],
$definition['member']['locationName'] ?: $k,
$definition['value'],
$xml
);
}
$xml->endElement();
}
private function getStructureMembers(StructureShape $shape, array $value)
{
$members = [];
foreach ($value as $k => $v) {
if ($v !== null && $shape->hasMember($k)) {
$definition = [
'member' => $shape->getMember($k),
'value' => $v,
];
if ($definition['member']['xmlAttribute']) {
// array_unshift_associative
$members = [$k => $definition] + $members;
} else {
$members[$k] = $definition;
}
}
}
return $members;
}
private function add_list(
ListShape $shape,
$name,
array $value,
XMLWriter $xml
) {
$items = $shape->getMember();
if ($shape['flattened']) {
$elementName = $name;
} else {
$this->startElement($shape, $name, $xml);
$elementName = $items['locationName'] ?: 'member';
}
foreach ($value as &$v) {
$this->format($items, $elementName, $v, $xml);
}
if (!$shape['flattened']) {
$xml->endElement();
}
}
private function add_map(
MapShape $shape,
$name,
array $value,
XMLWriter $xml
) {
$xmlEntry = $shape['flattened'] ? $shape['locationName'] : 'entry';
$xmlKey = $shape->getKey()['locationName'] ?: 'key';
$xmlValue = $shape->getValue()['locationName'] ?: 'value';
$this->startElement($shape, $name, $xml);
foreach ($value as $key => $v) {
$this->startElement($shape, $xmlEntry, $xml);
$this->format($shape->getKey(), $xmlKey, $key, $xml);
$this->format($shape->getValue(), $xmlValue, $v, $xml);
$xml->endElement();
}
$xml->endElement();
}
private function add_blob(Shape $shape, $name, $value, XMLWriter $xml)
{
$this->startElement($shape, $name, $xml);
$xml->writeRaw(base64_encode($value));
$xml->endElement();
}
private function add_timestamp(
TimestampShape $shape,
$name,
$value,
XMLWriter $xml
) {
$this->startElement($shape, $name, $xml);
$xml->writeRaw(TimestampShape::format($value, 'iso8601'));
$xml->endElement();
}
private function add_boolean(
Shape $shape,
$name,
$value,
XMLWriter $xml
) {
$this->startElement($shape, $name, $xml);
$xml->writeRaw($value ? 'true' : 'false');
$xml->endElement();
}
private function add_string(
Shape $shape,
$name,
$value,
XMLWriter $xml
) {
if ($shape['xmlAttribute']) {
$xml->writeAttribute($shape['locationName'] ?: $name, $value);
} else {
$this->defaultShape($shape, $name, $value, $xml);
}
}
}

View File

@@ -0,0 +1,420 @@
<?php
namespace Aws\Api;
use Aws\Api\Serializer\QuerySerializer;
use Aws\Api\Serializer\Ec2ParamBuilder;
use Aws\Api\Parser\QueryParser;
/**
* Represents a web service API model.
*/
class Service extends AbstractModel
{
/** @var callable */
private $apiProvider;
/** @var string */
private $serviceName;
/** @var string */
private $apiVersion;
/** @var Operation[] */
private $operations = [];
/** @var array */
private $paginators = null;
/** @var array */
private $waiters = null;
/**
* @param array $definition
* @param callable $provider
*
* @internal param array $definition Service description
*/
public function __construct(array $definition, callable $provider)
{
static $defaults = [
'operations' => [],
'shapes' => [],
'metadata' => []
], $defaultMeta = [
'apiVersion' => null,
'serviceFullName' => null,
'endpointPrefix' => null,
'signingName' => null,
'signatureVersion' => null,
'protocol' => null
];
$definition += $defaults;
$definition['metadata'] += $defaultMeta;
$this->definition = $definition;
$this->apiProvider = $provider;
parent::__construct($definition, new ShapeMap($definition['shapes']));
if (isset($definition['metadata']['serviceIdentifier'])) {
$this->serviceName = $this->getServiceName();
} else {
$this->serviceName = $this->getEndpointPrefix();
}
$this->apiVersion = $this->getApiVersion();
}
/**
* Creates a request serializer for the provided API object.
*
* @param Service $api API that contains a protocol.
* @param string $endpoint Endpoint to send requests to.
*
* @return callable
* @throws \UnexpectedValueException
*/
public static function createSerializer(Service $api, $endpoint)
{
static $mapping = [
'json' => 'Aws\Api\Serializer\JsonRpcSerializer',
'query' => 'Aws\Api\Serializer\QuerySerializer',
'rest-json' => 'Aws\Api\Serializer\RestJsonSerializer',
'rest-xml' => 'Aws\Api\Serializer\RestXmlSerializer'
];
$proto = $api->getProtocol();
if (isset($mapping[$proto])) {
return new $mapping[$proto]($api, $endpoint);
} elseif ($proto == 'ec2') {
return new QuerySerializer($api, $endpoint, new Ec2ParamBuilder());
}
throw new \UnexpectedValueException(
'Unknown protocol: ' . $api->getProtocol()
);
}
/**
* Creates an error parser for the given protocol.
*
* @param string $protocol Protocol to parse (e.g., query, json, etc.)
*
* @return callable
* @throws \UnexpectedValueException
*/
public static function createErrorParser($protocol)
{
static $mapping = [
'json' => 'Aws\Api\ErrorParser\JsonRpcErrorParser',
'query' => 'Aws\Api\ErrorParser\XmlErrorParser',
'rest-json' => 'Aws\Api\ErrorParser\RestJsonErrorParser',
'rest-xml' => 'Aws\Api\ErrorParser\XmlErrorParser',
'ec2' => 'Aws\Api\ErrorParser\XmlErrorParser'
];
if (isset($mapping[$protocol])) {
return new $mapping[$protocol]();
}
throw new \UnexpectedValueException("Unknown protocol: $protocol");
}
/**
* Applies the listeners needed to parse client models.
*
* @param Service $api API to create a parser for
* @return callable
* @throws \UnexpectedValueException
*/
public static function createParser(Service $api)
{
static $mapping = [
'json' => 'Aws\Api\Parser\JsonRpcParser',
'query' => 'Aws\Api\Parser\QueryParser',
'rest-json' => 'Aws\Api\Parser\RestJsonParser',
'rest-xml' => 'Aws\Api\Parser\RestXmlParser'
];
$proto = $api->getProtocol();
if (isset($mapping[$proto])) {
return new $mapping[$proto]($api);
} elseif ($proto == 'ec2') {
return new QueryParser($api, null, false);
}
throw new \UnexpectedValueException(
'Unknown protocol: ' . $api->getProtocol()
);
}
/**
* Get the full name of the service
*
* @return string
*/
public function getServiceFullName()
{
return $this->definition['metadata']['serviceFullName'];
}
/**
* Get the API version of the service
*
* @return string
*/
public function getApiVersion()
{
return $this->definition['metadata']['apiVersion'];
}
/**
* Get the API version of the service
*
* @return string
*/
public function getEndpointPrefix()
{
return $this->definition['metadata']['endpointPrefix'];
}
/**
* Get the signing name used by the service.
*
* @return string
*/
public function getSigningName()
{
return $this->definition['metadata']['signingName']
?: $this->definition['metadata']['endpointPrefix'];
}
/**
* Get the service name.
*
* @return string
*/
public function getServiceName()
{
return $this->definition['metadata']['serviceIdentifier'];
}
/**
* Get the default signature version of the service.
*
* Note: this method assumes "v4" when not specified in the model.
*
* @return string
*/
public function getSignatureVersion()
{
return $this->definition['metadata']['signatureVersion'] ?: 'v4';
}
/**
* Get the protocol used by the service.
*
* @return string
*/
public function getProtocol()
{
return $this->definition['metadata']['protocol'];
}
/**
* Check if the description has a specific operation by name.
*
* @param string $name Operation to check by name
*
* @return bool
*/
public function hasOperation($name)
{
return isset($this['operations'][$name]);
}
/**
* Get an operation by name.
*
* @param string $name Operation to retrieve by name
*
* @return Operation
* @throws \InvalidArgumentException If the operation is not found
*/
public function getOperation($name)
{
if (!isset($this->operations[$name])) {
if (!isset($this->definition['operations'][$name])) {
throw new \InvalidArgumentException("Unknown operation: $name");
}
$this->operations[$name] = new Operation(
$this->definition['operations'][$name],
$this->shapeMap
);
}
return $this->operations[$name];
}
/**
* Get all of the operations of the description.
*
* @return Operation[]
*/
public function getOperations()
{
$result = [];
foreach ($this->definition['operations'] as $name => $definition) {
$result[$name] = $this->getOperation($name);
}
return $result;
}
/**
* Get all of the service metadata or a specific metadata key value.
*
* @param string|null $key Key to retrieve or null to retrieve all metadata
*
* @return mixed Returns the result or null if the key is not found
*/
public function getMetadata($key = null)
{
if (!$key) {
return $this['metadata'];
} elseif (isset($this->definition['metadata'][$key])) {
return $this->definition['metadata'][$key];
}
return null;
}
/**
* Gets an associative array of available paginator configurations where
* the key is the name of the paginator, and the value is the paginator
* configuration.
*
* @return array
* @unstable The configuration format of paginators may change in the future
*/
public function getPaginators()
{
if (!isset($this->paginators)) {
$res = call_user_func(
$this->apiProvider,
'paginator',
$this->serviceName,
$this->apiVersion
);
$this->paginators = isset($res['pagination'])
? $res['pagination']
: [];
}
return $this->paginators;
}
/**
* Determines if the service has a paginator by name.
*
* @param string $name Name of the paginator.
*
* @return bool
*/
public function hasPaginator($name)
{
return isset($this->getPaginators()[$name]);
}
/**
* Retrieve a paginator by name.
*
* @param string $name Paginator to retrieve by name. This argument is
* typically the operation name.
* @return array
* @throws \UnexpectedValueException if the paginator does not exist.
* @unstable The configuration format of paginators may change in the future
*/
public function getPaginatorConfig($name)
{
static $defaults = [
'input_token' => null,
'output_token' => null,
'limit_key' => null,
'result_key' => null,
'more_results' => null,
];
if ($this->hasPaginator($name)) {
return $this->paginators[$name] + $defaults;
}
throw new \UnexpectedValueException("There is no {$name} "
. "paginator defined for the {$this->serviceName} service.");
}
/**
* Gets an associative array of available waiter configurations where the
* key is the name of the waiter, and the value is the waiter
* configuration.
*
* @return array
*/
public function getWaiters()
{
if (!isset($this->waiters)) {
$res = call_user_func(
$this->apiProvider,
'waiter',
$this->serviceName,
$this->apiVersion
);
$this->waiters = isset($res['waiters'])
? $res['waiters']
: [];
}
return $this->waiters;
}
/**
* Determines if the service has a waiter by name.
*
* @param string $name Name of the waiter.
*
* @return bool
*/
public function hasWaiter($name)
{
return isset($this->getWaiters()[$name]);
}
/**
* Get a waiter configuration by name.
*
* @param string $name Name of the waiter by name.
*
* @return array
* @throws \UnexpectedValueException if the waiter does not exist.
*/
public function getWaiterConfig($name)
{
// Error if the waiter is not defined
if ($this->hasWaiter($name)) {
return $this->waiters[$name];
}
throw new \UnexpectedValueException("There is no {$name} waiter "
. "defined for the {$this->serviceName} service.");
}
/**
* Get the shape map used by the API.
*
* @return ShapeMap
*/
public function getShapeMap()
{
return $this->shapeMap;
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Aws\Api;
/**
* Base class representing a modeled shape.
*/
class Shape extends AbstractModel
{
/**
* Get a concrete shape for the given definition.
*
* @param array $definition
* @param ShapeMap $shapeMap
*
* @return mixed
* @throws \RuntimeException if the type is invalid
*/
public static function create(array $definition, ShapeMap $shapeMap)
{
static $map = [
'structure' => 'Aws\Api\StructureShape',
'map' => 'Aws\Api\MapShape',
'list' => 'Aws\Api\ListShape',
'timestamp' => 'Aws\Api\TimestampShape',
'integer' => 'Aws\Api\Shape',
'double' => 'Aws\Api\Shape',
'float' => 'Aws\Api\Shape',
'long' => 'Aws\Api\Shape',
'string' => 'Aws\Api\Shape',
'byte' => 'Aws\Api\Shape',
'character' => 'Aws\Api\Shape',
'blob' => 'Aws\Api\Shape',
'boolean' => 'Aws\Api\Shape'
];
if (isset($definition['shape'])) {
return $shapeMap->resolve($definition);
}
if (!isset($map[$definition['type']])) {
throw new \RuntimeException('Invalid type: '
. print_r($definition, true));
}
$type = $map[$definition['type']];
return new $type($definition, $shapeMap);
}
/**
* Get the type of the shape
*
* @return string
*/
public function getType()
{
return $this->definition['type'];
}
/**
* Get the name of the shape
*
* @return string
*/
public function getName()
{
return $this->definition['name'];
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace Aws\Api;
/**
* Builds shape based on shape references.
*/
class ShapeMap
{
/** @var array */
private $definitions;
/** @var Shape[] */
private $simple;
/**
* @param array $shapeModels Associative array of shape definitions.
*/
public function __construct(array $shapeModels)
{
$this->definitions = $shapeModels;
}
/**
* Get an array of shape names.
*
* @return array
*/
public function getShapeNames()
{
return array_keys($this->definitions);
}
/**
* Resolve a shape reference
*
* @param array $shapeRef Shape reference shape
*
* @return Shape
* @throws \InvalidArgumentException
*/
public function resolve(array $shapeRef)
{
$shape = $shapeRef['shape'];
if (!isset($this->definitions[$shape])) {
throw new \InvalidArgumentException('Shape not found: ' . $shape);
}
$isSimple = count($shapeRef) == 1;
if ($isSimple && isset($this->simple[$shape])) {
return $this->simple[$shape];
}
$definition = $shapeRef + $this->definitions[$shape];
$definition['name'] = $definition['shape'];
unset($definition['shape']);
$result = Shape::create($definition, $this);
if ($isSimple) {
$this->simple[$shape] = $result;
}
return $result;
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace Aws\Api;
/**
* Represents a structure shape and resolve member shape references.
*/
class StructureShape extends Shape
{
/**
* @var Shape[]
*/
private $members;
public function __construct(array $definition, ShapeMap $shapeMap)
{
$definition['type'] = 'structure';
if (!isset($definition['members'])) {
$definition['members'] = [];
}
parent::__construct($definition, $shapeMap);
}
/**
* Gets a list of all members
*
* @return Shape[]
*/
public function getMembers()
{
if (empty($this->members)) {
$this->generateMembersHash();
}
return $this->members;
}
/**
* Check if a specific member exists by name.
*
* @param string $name Name of the member to check
*
* @return bool
*/
public function hasMember($name)
{
return isset($this->definition['members'][$name]);
}
/**
* Retrieve a member by name.
*
* @param string $name Name of the member to retrieve
*
* @return Shape
* @throws \InvalidArgumentException if the member is not found.
*/
public function getMember($name)
{
$members = $this->getMembers();
if (!isset($members[$name])) {
throw new \InvalidArgumentException('Unknown member ' . $name);
}
return $members[$name];
}
private function generateMembersHash()
{
$this->members = [];
foreach ($this->definition['members'] as $name => $definition) {
$this->members[$name] = $this->shapeFor($definition);
}
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Aws\Api;
/**
* Represents a timestamp shape.
*/
class TimestampShape extends Shape
{
public function __construct(array $definition, ShapeMap $shapeMap)
{
$definition['type'] = 'timestamp';
parent::__construct($definition, $shapeMap);
}
/**
* Formats a timestamp value for a service.
*
* @param mixed $value Value to format
* @param string $format Format used to serialize the value
*
* @return int|string
* @throws \UnexpectedValueException if the format is unknown.
* @throws \InvalidArgumentException if the value is an unsupported type.
*/
public static function format($value, $format)
{
if ($value instanceof \DateTime) {
$value = $value->getTimestamp();
} elseif (is_string($value)) {
$value = strtotime($value);
} elseif (!is_int($value)) {
throw new \InvalidArgumentException('Unable to handle the provided'
. ' timestamp type: ' . gettype($value));
}
switch ($format) {
case 'iso8601':
return gmdate('Y-m-d\TH:i:s\Z', $value);
case 'rfc822':
return gmdate('D, d M Y H:i:s \G\M\T', $value);
case 'unixTimestamp':
return $value;
default:
throw new \UnexpectedValueException('Unknown timestamp format: '
. $format);
}
}
}

View File

@@ -0,0 +1,260 @@
<?php
namespace Aws\Api;
use Aws;
/**
* Validates a schema against a hash of input.
*/
class Validator
{
private $path = [];
private $errors = [];
private $constraints = [];
private static $defaultConstraints = [
'required' => true,
'min' => true,
'max' => false,
'pattern' => false
];
/**
* @param array $constraints Associative array of constraints to enforce.
* Accepts the following keys: "required", "min",
* "max", and "pattern". If a key is not
* provided, the constraint will assume false.
*/
public function __construct(array $constraints = null)
{
static $assumedFalseValues = [
'required' => false,
'min' => false,
'max' => false,
'pattern' => false
];
$this->constraints = empty($constraints)
? self::$defaultConstraints
: $constraints + $assumedFalseValues;
}
/**
* Validates the given input against the schema.
*
* @param string $name Operation name
* @param Shape $shape Shape to validate
* @param array $input Input to validate
*
* @throws \InvalidArgumentException if the input is invalid.
*/
public function validate($name, Shape $shape, array $input)
{
$this->dispatch($shape, $input);
if ($this->errors) {
$message = sprintf(
"Found %d error%s while validating the input provided for the "
. "%s operation:\n%s",
count($this->errors),
count($this->errors) > 1 ? 's' : '',
$name,
implode("\n", $this->errors)
);
$this->errors = [];
throw new \InvalidArgumentException($message);
}
}
private function dispatch(Shape $shape, $value)
{
static $methods = [
'structure' => 'check_structure',
'list' => 'check_list',
'map' => 'check_map',
'blob' => 'check_blob',
'boolean' => 'check_boolean',
'integer' => 'check_numeric',
'float' => 'check_numeric',
'long' => 'check_numeric',
'string' => 'check_string',
'byte' => 'check_string',
'char' => 'check_string'
];
$type = $shape->getType();
if (isset($methods[$type])) {
$this->{$methods[$type]}($shape, $value);
}
}
private function check_structure(StructureShape $shape, $value)
{
if (!$this->checkAssociativeArray($value)) {
return;
}
if ($this->constraints['required'] && $shape['required']) {
foreach ($shape['required'] as $req) {
if (!isset($value[$req])) {
$this->path[] = $req;
$this->addError('is missing and is a required parameter');
array_pop($this->path);
}
}
}
foreach ($value as $name => $v) {
if ($shape->hasMember($name)) {
$this->path[] = $name;
$this->dispatch(
$shape->getMember($name),
isset($value[$name]) ? $value[$name] : null
);
array_pop($this->path);
}
}
}
private function check_list(ListShape $shape, $value)
{
if (!is_array($value)) {
$this->addError('must be an array. Found '
. Aws\describe_type($value));
return;
}
$this->validateRange($shape, count($value), "list element count");
$items = $shape->getMember();
foreach ($value as $index => $v) {
$this->path[] = $index;
$this->dispatch($items, $v);
array_pop($this->path);
}
}
private function check_map(MapShape $shape, $value)
{
if (!$this->checkAssociativeArray($value)) {
return;
}
$values = $shape->getValue();
foreach ($value as $key => $v) {
$this->path[] = $key;
$this->dispatch($values, $v);
array_pop($this->path);
}
}
private function check_blob(Shape $shape, $value)
{
static $valid = [
'string' => true,
'integer' => true,
'double' => true,
'resource' => true
];
$type = gettype($value);
if (!isset($valid[$type])) {
if ($type != 'object' || !method_exists($value, '__toString')) {
$this->addError('must be an fopen resource, a '
. 'GuzzleHttp\Stream\StreamInterface object, or something '
. 'that can be cast to a string. Found '
. Aws\describe_type($value));
}
}
}
private function check_numeric(Shape $shape, $value)
{
if (!is_numeric($value)) {
$this->addError('must be numeric. Found '
. Aws\describe_type($value));
return;
}
$this->validateRange($shape, $value, "numeric value");
}
private function check_boolean(Shape $shape, $value)
{
if (!is_bool($value)) {
$this->addError('must be a boolean. Found '
. Aws\describe_type($value));
}
}
private function check_string(Shape $shape, $value)
{
if (!$this->checkCanString($value)) {
$this->addError('must be a string or an object that implements '
. '__toString(). Found ' . Aws\describe_type($value));
return;
}
$this->validateRange($shape, strlen($value), "string length");
if ($this->constraints['pattern']) {
$pattern = $shape['pattern'];
if ($pattern && !preg_match("/$pattern/", $value)) {
$this->addError("Pattern /$pattern/ failed to match '$value'");
}
}
}
private function validateRange(Shape $shape, $length, $descriptor)
{
if ($this->constraints['min']) {
$min = $shape['min'];
if ($min && $length < $min) {
$this->addError("expected $descriptor to be >= $min, but "
. "found $descriptor of $length");
}
}
if ($this->constraints['max']) {
$max = $shape['max'];
if ($max && $length > $max) {
$this->addError("expected $descriptor to be <= $max, but "
. "found $descriptor of $length");
}
}
}
private function checkCanString($value)
{
static $valid = [
'string' => true,
'integer' => true,
'double' => true,
'NULL' => true,
];
$type = gettype($value);
return isset($valid[$type]) ||
($type == 'object' && method_exists($value, '__toString'));
}
private function checkAssociativeArray($value)
{
if (!is_array($value) || isset($value[0])) {
$this->addError('must be an associative array. Found '
. Aws\describe_type($value));
return false;
}
return true;
}
private function addError($message)
{
$this->errors[] =
implode('', array_map(function ($s) { return "[{$s}]"; }, $this->path))
. ' '
. $message;
}
}

View File

@@ -0,0 +1,210 @@
<?php
namespace Aws\ApiGateway;
use Aws\AwsClient;
use Aws\CommandInterface;
use Psr\Http\Message\RequestInterface;
/**
* This client is used to interact with the **AWS API Gateway** service.
*
* @method \Aws\Result createApiKey(array $args = [])
* @method \GuzzleHttp\Promise\Promise createApiKeyAsync(array $args = [])
* @method \Aws\Result createAuthorizer(array $args = [])
* @method \GuzzleHttp\Promise\Promise createAuthorizerAsync(array $args = [])
* @method \Aws\Result createBasePathMapping(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBasePathMappingAsync(array $args = [])
* @method \Aws\Result createDeployment(array $args = [])
* @method \GuzzleHttp\Promise\Promise createDeploymentAsync(array $args = [])
* @method \Aws\Result createDomainName(array $args = [])
* @method \GuzzleHttp\Promise\Promise createDomainNameAsync(array $args = [])
* @method \Aws\Result createModel(array $args = [])
* @method \GuzzleHttp\Promise\Promise createModelAsync(array $args = [])
* @method \Aws\Result createResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise createResourceAsync(array $args = [])
* @method \Aws\Result createRestApi(array $args = [])
* @method \GuzzleHttp\Promise\Promise createRestApiAsync(array $args = [])
* @method \Aws\Result createStage(array $args = [])
* @method \GuzzleHttp\Promise\Promise createStageAsync(array $args = [])
* @method \Aws\Result createUsagePlan(array $args = [])
* @method \GuzzleHttp\Promise\Promise createUsagePlanAsync(array $args = [])
* @method \Aws\Result createUsagePlanKey(array $args = [])
* @method \GuzzleHttp\Promise\Promise createUsagePlanKeyAsync(array $args = [])
* @method \Aws\Result deleteApiKey(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteApiKeyAsync(array $args = [])
* @method \Aws\Result deleteAuthorizer(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAuthorizerAsync(array $args = [])
* @method \Aws\Result deleteBasePathMapping(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteBasePathMappingAsync(array $args = [])
* @method \Aws\Result deleteClientCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteClientCertificateAsync(array $args = [])
* @method \Aws\Result deleteDeployment(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDeploymentAsync(array $args = [])
* @method \Aws\Result deleteDomainName(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDomainNameAsync(array $args = [])
* @method \Aws\Result deleteIntegration(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteIntegrationAsync(array $args = [])
* @method \Aws\Result deleteIntegrationResponse(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteIntegrationResponseAsync(array $args = [])
* @method \Aws\Result deleteMethod(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteMethodAsync(array $args = [])
* @method \Aws\Result deleteMethodResponse(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteMethodResponseAsync(array $args = [])
* @method \Aws\Result deleteModel(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteModelAsync(array $args = [])
* @method \Aws\Result deleteResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteResourceAsync(array $args = [])
* @method \Aws\Result deleteRestApi(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteRestApiAsync(array $args = [])
* @method \Aws\Result deleteStage(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteStageAsync(array $args = [])
* @method \Aws\Result deleteUsagePlan(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteUsagePlanAsync(array $args = [])
* @method \Aws\Result deleteUsagePlanKey(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteUsagePlanKeyAsync(array $args = [])
* @method \Aws\Result flushStageAuthorizersCache(array $args = [])
* @method \GuzzleHttp\Promise\Promise flushStageAuthorizersCacheAsync(array $args = [])
* @method \Aws\Result flushStageCache(array $args = [])
* @method \GuzzleHttp\Promise\Promise flushStageCacheAsync(array $args = [])
* @method \Aws\Result generateClientCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise generateClientCertificateAsync(array $args = [])
* @method \Aws\Result getAccount(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAccountAsync(array $args = [])
* @method \Aws\Result getApiKey(array $args = [])
* @method \GuzzleHttp\Promise\Promise getApiKeyAsync(array $args = [])
* @method \Aws\Result getApiKeys(array $args = [])
* @method \GuzzleHttp\Promise\Promise getApiKeysAsync(array $args = [])
* @method \Aws\Result getAuthorizer(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAuthorizerAsync(array $args = [])
* @method \Aws\Result getAuthorizers(array $args = [])
* @method \GuzzleHttp\Promise\Promise getAuthorizersAsync(array $args = [])
* @method \Aws\Result getBasePathMapping(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBasePathMappingAsync(array $args = [])
* @method \Aws\Result getBasePathMappings(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBasePathMappingsAsync(array $args = [])
* @method \Aws\Result getClientCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise getClientCertificateAsync(array $args = [])
* @method \Aws\Result getClientCertificates(array $args = [])
* @method \GuzzleHttp\Promise\Promise getClientCertificatesAsync(array $args = [])
* @method \Aws\Result getDeployment(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDeploymentAsync(array $args = [])
* @method \Aws\Result getDeployments(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDeploymentsAsync(array $args = [])
* @method \Aws\Result getDomainName(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDomainNameAsync(array $args = [])
* @method \Aws\Result getDomainNames(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDomainNamesAsync(array $args = [])
* @method \Aws\Result getExport(array $args = [])
* @method \GuzzleHttp\Promise\Promise getExportAsync(array $args = [])
* @method \Aws\Result getIntegration(array $args = [])
* @method \GuzzleHttp\Promise\Promise getIntegrationAsync(array $args = [])
* @method \Aws\Result getIntegrationResponse(array $args = [])
* @method \GuzzleHttp\Promise\Promise getIntegrationResponseAsync(array $args = [])
* @method \Aws\Result getMethod(array $args = [])
* @method \GuzzleHttp\Promise\Promise getMethodAsync(array $args = [])
* @method \Aws\Result getMethodResponse(array $args = [])
* @method \GuzzleHttp\Promise\Promise getMethodResponseAsync(array $args = [])
* @method \Aws\Result getModel(array $args = [])
* @method \GuzzleHttp\Promise\Promise getModelAsync(array $args = [])
* @method \Aws\Result getModelTemplate(array $args = [])
* @method \GuzzleHttp\Promise\Promise getModelTemplateAsync(array $args = [])
* @method \Aws\Result getModels(array $args = [])
* @method \GuzzleHttp\Promise\Promise getModelsAsync(array $args = [])
* @method \Aws\Result getResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise getResourceAsync(array $args = [])
* @method \Aws\Result getResources(array $args = [])
* @method \GuzzleHttp\Promise\Promise getResourcesAsync(array $args = [])
* @method \Aws\Result getRestApi(array $args = [])
* @method \GuzzleHttp\Promise\Promise getRestApiAsync(array $args = [])
* @method \Aws\Result getRestApis(array $args = [])
* @method \GuzzleHttp\Promise\Promise getRestApisAsync(array $args = [])
* @method \Aws\Result getSdk(array $args = [])
* @method \GuzzleHttp\Promise\Promise getSdkAsync(array $args = [])
* @method \Aws\Result getStage(array $args = [])
* @method \GuzzleHttp\Promise\Promise getStageAsync(array $args = [])
* @method \Aws\Result getStages(array $args = [])
* @method \GuzzleHttp\Promise\Promise getStagesAsync(array $args = [])
* @method \Aws\Result getUsage(array $args = [])
* @method \GuzzleHttp\Promise\Promise getUsageAsync(array $args = [])
* @method \Aws\Result getUsagePlan(array $args = [])
* @method \GuzzleHttp\Promise\Promise getUsagePlanAsync(array $args = [])
* @method \Aws\Result getUsagePlanKey(array $args = [])
* @method \GuzzleHttp\Promise\Promise getUsagePlanKeyAsync(array $args = [])
* @method \Aws\Result getUsagePlanKeys(array $args = [])
* @method \GuzzleHttp\Promise\Promise getUsagePlanKeysAsync(array $args = [])
* @method \Aws\Result getUsagePlans(array $args = [])
* @method \GuzzleHttp\Promise\Promise getUsagePlansAsync(array $args = [])
* @method \Aws\Result importApiKeys(array $args = [])
* @method \GuzzleHttp\Promise\Promise importApiKeysAsync(array $args = [])
* @method \Aws\Result importRestApi(array $args = [])
* @method \GuzzleHttp\Promise\Promise importRestApiAsync(array $args = [])
* @method \Aws\Result putIntegration(array $args = [])
* @method \GuzzleHttp\Promise\Promise putIntegrationAsync(array $args = [])
* @method \Aws\Result putIntegrationResponse(array $args = [])
* @method \GuzzleHttp\Promise\Promise putIntegrationResponseAsync(array $args = [])
* @method \Aws\Result putMethod(array $args = [])
* @method \GuzzleHttp\Promise\Promise putMethodAsync(array $args = [])
* @method \Aws\Result putMethodResponse(array $args = [])
* @method \GuzzleHttp\Promise\Promise putMethodResponseAsync(array $args = [])
* @method \Aws\Result putRestApi(array $args = [])
* @method \GuzzleHttp\Promise\Promise putRestApiAsync(array $args = [])
* @method \Aws\Result testInvokeAuthorizer(array $args = [])
* @method \GuzzleHttp\Promise\Promise testInvokeAuthorizerAsync(array $args = [])
* @method \Aws\Result testInvokeMethod(array $args = [])
* @method \GuzzleHttp\Promise\Promise testInvokeMethodAsync(array $args = [])
* @method \Aws\Result updateAccount(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateAccountAsync(array $args = [])
* @method \Aws\Result updateApiKey(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateApiKeyAsync(array $args = [])
* @method \Aws\Result updateAuthorizer(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateAuthorizerAsync(array $args = [])
* @method \Aws\Result updateBasePathMapping(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateBasePathMappingAsync(array $args = [])
* @method \Aws\Result updateClientCertificate(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateClientCertificateAsync(array $args = [])
* @method \Aws\Result updateDeployment(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateDeploymentAsync(array $args = [])
* @method \Aws\Result updateDomainName(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateDomainNameAsync(array $args = [])
* @method \Aws\Result updateIntegration(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateIntegrationAsync(array $args = [])
* @method \Aws\Result updateIntegrationResponse(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateIntegrationResponseAsync(array $args = [])
* @method \Aws\Result updateMethod(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateMethodAsync(array $args = [])
* @method \Aws\Result updateMethodResponse(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateMethodResponseAsync(array $args = [])
* @method \Aws\Result updateModel(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateModelAsync(array $args = [])
* @method \Aws\Result updateResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateResourceAsync(array $args = [])
* @method \Aws\Result updateRestApi(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateRestApiAsync(array $args = [])
* @method \Aws\Result updateStage(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateStageAsync(array $args = [])
* @method \Aws\Result updateUsage(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateUsageAsync(array $args = [])
* @method \Aws\Result updateUsagePlan(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateUsagePlanAsync(array $args = [])
*/
class ApiGatewayClient extends AwsClient
{
public function __construct(array $args)
{
parent::__construct($args);
$stack = $this->getHandlerList();
$stack->appendBuild([__CLASS__, '_add_accept_header']);
}
public static function _add_accept_header(callable $handler)
{
return function (
CommandInterface $command,
RequestInterface $request
) use ($handler) {
$request = $request->withHeader('Accept', 'application/json');
return $handler($command, $request);
};
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\ApiGateway\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS API Gateway** service.
*/
class ApiGatewayException extends AwsException {}

View File

@@ -0,0 +1,23 @@
<?php
namespace Aws\ApplicationAutoScaling;
use Aws\AwsClient;
/**
* This client is used to interact with the **Application Auto Scaling** service.
* @method \Aws\Result deleteScalingPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteScalingPolicyAsync(array $args = [])
* @method \Aws\Result deregisterScalableTarget(array $args = [])
* @method \GuzzleHttp\Promise\Promise deregisterScalableTargetAsync(array $args = [])
* @method \Aws\Result describeScalableTargets(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeScalableTargetsAsync(array $args = [])
* @method \Aws\Result describeScalingActivities(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeScalingActivitiesAsync(array $args = [])
* @method \Aws\Result describeScalingPolicies(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeScalingPoliciesAsync(array $args = [])
* @method \Aws\Result putScalingPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putScalingPolicyAsync(array $args = [])
* @method \Aws\Result registerScalableTarget(array $args = [])
* @method \GuzzleHttp\Promise\Promise registerScalableTargetAsync(array $args = [])
*/
class ApplicationAutoScalingClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\ApplicationAutoScaling\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **Application Auto Scaling** service.
*/
class ApplicationAutoScalingException extends AwsException {}

View File

@@ -0,0 +1,29 @@
<?php
namespace Aws\ApplicationDiscoveryService;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS Application Discovery Service** service.
* @method \Aws\Result createTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise createTagsAsync(array $args = [])
* @method \Aws\Result deleteTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteTagsAsync(array $args = [])
* @method \Aws\Result describeAgents(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAgentsAsync(array $args = [])
* @method \Aws\Result describeConfigurations(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeConfigurationsAsync(array $args = [])
* @method \Aws\Result describeExportConfigurations(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeExportConfigurationsAsync(array $args = [])
* @method \Aws\Result describeTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeTagsAsync(array $args = [])
* @method \Aws\Result exportConfigurations(array $args = [])
* @method \GuzzleHttp\Promise\Promise exportConfigurationsAsync(array $args = [])
* @method \Aws\Result listConfigurations(array $args = [])
* @method \GuzzleHttp\Promise\Promise listConfigurationsAsync(array $args = [])
* @method \Aws\Result startDataCollectionByAgentIds(array $args = [])
* @method \GuzzleHttp\Promise\Promise startDataCollectionByAgentIdsAsync(array $args = [])
* @method \Aws\Result stopDataCollectionByAgentIds(array $args = [])
* @method \GuzzleHttp\Promise\Promise stopDataCollectionByAgentIdsAsync(array $args = [])
*/
class ApplicationDiscoveryServiceClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\ApplicationDiscoveryService\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS Application Discovery Service** service.
*/
class ApplicationDiscoveryServiceException extends AwsException {}

View File

@@ -0,0 +1,114 @@
<?php
namespace Aws\AutoScaling;
use Aws\AwsClient;
/**
* Auto Scaling client.
*
* @method \Aws\Result attachInstances(array $args = [])
* @method \GuzzleHttp\Promise\Promise attachInstancesAsync(array $args = [])
* @method \Aws\Result attachLoadBalancerTargetGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise attachLoadBalancerTargetGroupsAsync(array $args = [])
* @method \Aws\Result attachLoadBalancers(array $args = [])
* @method \GuzzleHttp\Promise\Promise attachLoadBalancersAsync(array $args = [])
* @method \Aws\Result completeLifecycleAction(array $args = [])
* @method \GuzzleHttp\Promise\Promise completeLifecycleActionAsync(array $args = [])
* @method \Aws\Result createAutoScalingGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise createAutoScalingGroupAsync(array $args = [])
* @method \Aws\Result createLaunchConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise createLaunchConfigurationAsync(array $args = [])
* @method \Aws\Result createOrUpdateTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise createOrUpdateTagsAsync(array $args = [])
* @method \Aws\Result deleteAutoScalingGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAutoScalingGroupAsync(array $args = [])
* @method \Aws\Result deleteLaunchConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteLaunchConfigurationAsync(array $args = [])
* @method \Aws\Result deleteLifecycleHook(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteLifecycleHookAsync(array $args = [])
* @method \Aws\Result deleteNotificationConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteNotificationConfigurationAsync(array $args = [])
* @method \Aws\Result deletePolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise deletePolicyAsync(array $args = [])
* @method \Aws\Result deleteScheduledAction(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteScheduledActionAsync(array $args = [])
* @method \Aws\Result deleteTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteTagsAsync(array $args = [])
* @method \Aws\Result describeAccountLimits(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAccountLimitsAsync(array $args = [])
* @method \Aws\Result describeAdjustmentTypes(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAdjustmentTypesAsync(array $args = [])
* @method \Aws\Result describeAutoScalingGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAutoScalingGroupsAsync(array $args = [])
* @method \Aws\Result describeAutoScalingInstances(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAutoScalingInstancesAsync(array $args = [])
* @method \Aws\Result describeAutoScalingNotificationTypes(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAutoScalingNotificationTypesAsync(array $args = [])
* @method \Aws\Result describeLaunchConfigurations(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeLaunchConfigurationsAsync(array $args = [])
* @method \Aws\Result describeLifecycleHookTypes(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeLifecycleHookTypesAsync(array $args = [])
* @method \Aws\Result describeLifecycleHooks(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeLifecycleHooksAsync(array $args = [])
* @method \Aws\Result describeLoadBalancerTargetGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeLoadBalancerTargetGroupsAsync(array $args = [])
* @method \Aws\Result describeLoadBalancers(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeLoadBalancersAsync(array $args = [])
* @method \Aws\Result describeMetricCollectionTypes(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeMetricCollectionTypesAsync(array $args = [])
* @method \Aws\Result describeNotificationConfigurations(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeNotificationConfigurationsAsync(array $args = [])
* @method \Aws\Result describePolicies(array $args = [])
* @method \GuzzleHttp\Promise\Promise describePoliciesAsync(array $args = [])
* @method \Aws\Result describeScalingActivities(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeScalingActivitiesAsync(array $args = [])
* @method \Aws\Result describeScalingProcessTypes(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeScalingProcessTypesAsync(array $args = [])
* @method \Aws\Result describeScheduledActions(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeScheduledActionsAsync(array $args = [])
* @method \Aws\Result describeTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeTagsAsync(array $args = [])
* @method \Aws\Result describeTerminationPolicyTypes(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeTerminationPolicyTypesAsync(array $args = [])
* @method \Aws\Result detachInstances(array $args = [])
* @method \GuzzleHttp\Promise\Promise detachInstancesAsync(array $args = [])
* @method \Aws\Result detachLoadBalancerTargetGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise detachLoadBalancerTargetGroupsAsync(array $args = [])
* @method \Aws\Result detachLoadBalancers(array $args = [])
* @method \GuzzleHttp\Promise\Promise detachLoadBalancersAsync(array $args = [])
* @method \Aws\Result disableMetricsCollection(array $args = [])
* @method \GuzzleHttp\Promise\Promise disableMetricsCollectionAsync(array $args = [])
* @method \Aws\Result enableMetricsCollection(array $args = [])
* @method \GuzzleHttp\Promise\Promise enableMetricsCollectionAsync(array $args = [])
* @method \Aws\Result enterStandby(array $args = [])
* @method \GuzzleHttp\Promise\Promise enterStandbyAsync(array $args = [])
* @method \Aws\Result executePolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise executePolicyAsync(array $args = [])
* @method \Aws\Result exitStandby(array $args = [])
* @method \GuzzleHttp\Promise\Promise exitStandbyAsync(array $args = [])
* @method \Aws\Result putLifecycleHook(array $args = [])
* @method \GuzzleHttp\Promise\Promise putLifecycleHookAsync(array $args = [])
* @method \Aws\Result putNotificationConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise putNotificationConfigurationAsync(array $args = [])
* @method \Aws\Result putScalingPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putScalingPolicyAsync(array $args = [])
* @method \Aws\Result putScheduledUpdateGroupAction(array $args = [])
* @method \GuzzleHttp\Promise\Promise putScheduledUpdateGroupActionAsync(array $args = [])
* @method \Aws\Result recordLifecycleActionHeartbeat(array $args = [])
* @method \GuzzleHttp\Promise\Promise recordLifecycleActionHeartbeatAsync(array $args = [])
* @method \Aws\Result resumeProcesses(array $args = [])
* @method \GuzzleHttp\Promise\Promise resumeProcessesAsync(array $args = [])
* @method \Aws\Result setDesiredCapacity(array $args = [])
* @method \GuzzleHttp\Promise\Promise setDesiredCapacityAsync(array $args = [])
* @method \Aws\Result setInstanceHealth(array $args = [])
* @method \GuzzleHttp\Promise\Promise setInstanceHealthAsync(array $args = [])
* @method \Aws\Result setInstanceProtection(array $args = [])
* @method \GuzzleHttp\Promise\Promise setInstanceProtectionAsync(array $args = [])
* @method \Aws\Result suspendProcesses(array $args = [])
* @method \GuzzleHttp\Promise\Promise suspendProcessesAsync(array $args = [])
* @method \Aws\Result terminateInstanceInAutoScalingGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise terminateInstanceInAutoScalingGroupAsync(array $args = [])
* @method \Aws\Result updateAutoScalingGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateAutoScalingGroupAsync(array $args = [])
*/
class AutoScalingClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\AutoScaling\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error while interacting with the Auto Scaling service.
*/
class AutoScalingException extends AwsException {}

317
vendor/aws/aws-sdk-php/src/AwsClient.php vendored Normal file
View File

@@ -0,0 +1,317 @@
<?php
namespace Aws;
use Aws\Api\ApiProvider;
use Aws\Api\DocModel;
use Aws\Api\Service;
use Aws\Signature\SignatureProvider;
use GuzzleHttp\Psr7\Uri;
/**
* Default AWS client implementation
*/
class AwsClient implements AwsClientInterface
{
use AwsClientTrait;
/** @var array */
private $config;
/** @var string */
private $region;
/** @var string */
private $endpoint;
/** @var Service */
private $api;
/** @var callable */
private $signatureProvider;
/** @var callable */
private $credentialProvider;
/** @var HandlerList */
private $handlerList;
/** @var array*/
private $defaultRequestOptions;
/**
* Get an array of client constructor arguments used by the client.
*
* @return array
*/
public static function getArguments()
{
return ClientResolver::getDefaultArguments();
}
/**
* The client constructor accepts the following options:
*
* - api_provider: (callable) An optional PHP callable that accepts a
* type, service, and version argument, and returns an array of
* corresponding configuration data. The type value can be one of api,
* waiter, or paginator.
* - credentials:
* (Aws\Credentials\CredentialsInterface|array|bool|callable) Specifies
* the credentials used to sign requests. Provide an
* Aws\Credentials\CredentialsInterface object, an associative array of
* "key", "secret", and an optional "token" key, `false` to use null
* credentials, or a callable credentials provider used to create
* credentials or return null. See Aws\Credentials\CredentialProvider for
* a list of built-in credentials providers. If no credentials are
* provided, the SDK will attempt to load them from the environment.
* - debug: (bool|array) Set to true to display debug information when
* sending requests. Alternatively, you can provide an associative array
* with the following keys: logfn: (callable) Function that is invoked
* with log messages; stream_size: (int) When the size of a stream is
* greater than this number, the stream data will not be logged (set to
* "0" to not log any stream data); scrub_auth: (bool) Set to false to
* disable the scrubbing of auth data from the logged messages; http:
* (bool) Set to false to disable the "debug" feature of lower level HTTP
* adapters (e.g., verbose curl output).
* - stats: (bool|array) Set to true to gather transfer statistics on
* requests sent. Alternatively, you can provide an associative array with
* the following keys: retries: (bool) Set to false to disable reporting
* on retries attempted; http: (bool) Set to true to enable collecting
* statistics from lower level HTTP adapters (e.g., values returned in
* GuzzleHttp\TransferStats). HTTP handlers must support an
* `http_stats_receiver` option for this to have an effect; timer: (bool)
* Set to true to enable a command timer that reports the total wall clock
* time spent on an operation in seconds.
* - endpoint: (string) The full URI of the webservice. This is only
* required when connecting to a custom endpoint (e.g., a local version
* of S3).
* - endpoint_provider: (callable) An optional PHP callable that
* accepts a hash of options including a "service" and "region" key and
* returns NULL or a hash of endpoint data, of which the "endpoint" key
* is required. See Aws\Endpoint\EndpointProvider for a list of built-in
* providers.
* - handler: (callable) A handler that accepts a command object,
* request object and returns a promise that is fulfilled with an
* Aws\ResultInterface object or rejected with an
* Aws\Exception\AwsException. A handler does not accept a next handler
* as it is terminal and expected to fulfill a command. If no handler is
* provided, a default Guzzle handler will be utilized.
* - http: (array, default=array(0)) Set to an array of SDK request
* options to apply to each request (e.g., proxy, verify, etc.).
* - http_handler: (callable) An HTTP handler is a function that
* accepts a PSR-7 request object and returns a promise that is fulfilled
* with a PSR-7 response object or rejected with an array of exception
* data. NOTE: This option supersedes any provided "handler" option.
* - profile: (string) Allows you to specify which profile to use when
* credentials are created from the AWS credentials file in your HOME
* directory. This setting overrides the AWS_PROFILE environment
* variable. Note: Specifying "profile" will cause the "credentials" key
* to be ignored.
* - region: (string, required) Region to connect to. See
* http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of
* available regions.
* - retries: (int, default=int(3)) Configures the maximum number of
* allowed retries for a client (pass 0 to disable retries).
* - scheme: (string, default=string(5) "https") URI scheme to use when
* connecting connect. The SDK will utilize "https" endpoints (i.e.,
* utilize SSL/TLS connections) by default. You can attempt to connect to
* a service over an unencrypted "http" endpoint by setting ``scheme`` to
* "http".
* - signature_provider: (callable) A callable that accepts a signature
* version name (e.g., "v4"), a service name, and region, and
* returns a SignatureInterface object or null. This provider is used to
* create signers utilized by the client. See
* Aws\Signature\SignatureProvider for a list of built-in providers
* - signature_version: (string) A string representing a custom
* signature version to use with a service (e.g., v4). Note that
* per/operation signature version MAY override this requested signature
* version.
* - validate: (bool, default=bool(true)) Set to false to disable
* client-side parameter validation.
* - version: (string, required) The version of the webservice to
* utilize (e.g., 2006-03-01).
*
* @param array $args Client configuration arguments.
*
* @throws \InvalidArgumentException if any required options are missing or
* the service is not supported.
*/
public function __construct(array $args)
{
list($service, $exceptionClass) = $this->parseClass();
if (!isset($args['service'])) {
$args['service'] = manifest($service)['endpoint'];
}
if (!isset($args['exception_class'])) {
$args['exception_class'] = $exceptionClass;
}
$this->handlerList = new HandlerList();
$resolver = new ClientResolver(static::getArguments());
$config = $resolver->resolve($args, $this->handlerList);
$this->api = $config['api'];
$this->signatureProvider = $config['signature_provider'];
$this->endpoint = new Uri($config['endpoint']);
$this->credentialProvider = $config['credentials'];
$this->region = isset($config['region']) ? $config['region'] : null;
$this->config = $config['config'];
$this->defaultRequestOptions = $config['http'];
$this->addSignatureMiddleware();
$this->addInvocationId();
if (isset($args['with_resolved'])) {
$args['with_resolved']($config);
}
}
public function getHandlerList()
{
return $this->handlerList;
}
public function getConfig($option = null)
{
return $option === null
? $this->config
: (isset($this->config[$option])
? $this->config[$option]
: null);
}
public function getCredentials()
{
$fn = $this->credentialProvider;
return $fn();
}
public function getEndpoint()
{
return $this->endpoint;
}
public function getRegion()
{
return $this->region;
}
public function getApi()
{
return $this->api;
}
public function getCommand($name, array $args = [])
{
// Fail fast if the command cannot be found in the description.
if (!isset($this->getApi()['operations'][$name])) {
$name = ucfirst($name);
if (!isset($this->getApi()['operations'][$name])) {
throw new \InvalidArgumentException("Operation not found: $name");
}
}
if (!isset($args['@http'])) {
$args['@http'] = $this->defaultRequestOptions;
} else {
$args['@http'] += $this->defaultRequestOptions;
}
return new Command($name, $args, clone $this->getHandlerList());
}
public function __sleep()
{
throw new \RuntimeException('Instances of ' . static::class
. ' cannot be serialized');
}
/**
* Get the signature_provider function of the client.
*
* @return callable
*/
final protected function getSignatureProvider()
{
return $this->signatureProvider;
}
/**
* Parse the class name and setup the custom exception class of the client
* and return the "service" name of the client and "exception_class".
*
* @return array
*/
private function parseClass()
{
$klass = get_class($this);
if ($klass === __CLASS__) {
return ['', 'Aws\Exception\AwsException'];
}
$service = substr($klass, strrpos($klass, '\\') + 1, -6);
return [
strtolower($service),
"Aws\\{$service}\\Exception\\{$service}Exception"
];
}
private function addSignatureMiddleware()
{
$api = $this->getApi();
$provider = $this->signatureProvider;
$version = $this->config['signature_version'];
$name = $this->config['signing_name'];
$region = $this->config['signing_region'];
$resolver = static function (
CommandInterface $c
) use ($api, $provider, $name, $region, $version) {
if ('none' === $api->getOperation($c->getName())['authtype']) {
$version = 'anonymous';
}
return SignatureProvider::resolve($provider, $version, $name, $region);
};
$this->handlerList->appendSign(
Middleware::signer($this->credentialProvider, $resolver),
'signer'
);
}
private function addInvocationId()
{
// Add invocation id to each request
$this->handlerList->prependSign(Middleware::invocationId(), 'invocation-id');
}
/**
* Returns a service model and doc model with any necessary changes
* applied.
*
* @param array $api Array of service data being documented.
* @param array $docs Array of doc model data.
*
* @return array Tuple containing a [Service, DocModel]
*
* @internal This should only used to document the service API.
* @codeCoverageIgnore
*/
public static function applyDocFilters(array $api, array $docs)
{
return [
new Service($api, ApiProvider::defaultProvider()),
new DocModel($docs)
];
}
/**
* @deprecated
* @return static
*/
public static function factory(array $config = [])
{
return new static($config);
}
}

View File

@@ -0,0 +1,169 @@
<?php
namespace Aws;
use Psr\Http\Message\UriInterface;
use GuzzleHttp\Promise\PromiseInterface;
/**
* Represents an AWS client.
*/
interface AwsClientInterface
{
/**
* Creates and executes a command for an operation by name.
*
* Suffixing an operation name with "Async" will return a
* promise that can be used to execute commands asynchronously.
*
* @param string $name Name of the command to execute.
* @param array $arguments Arguments to pass to the getCommand method.
*
* @return ResultInterface
* @throws \Exception
*/
public function __call($name, array $arguments);
/**
* Create a command for an operation name.
*
* Special keys may be set on the command to control how it behaves,
* including:
*
* - @http: Associative array of transfer specific options to apply to the
* request that is serialized for this command. Available keys include
* "proxy", "verify", "timeout", "connect_timeout", "debug", "delay", and
* "headers".
*
* @param string $name Name of the operation to use in the command
* @param array $args Arguments to pass to the command
*
* @return CommandInterface
* @throws \InvalidArgumentException if no command can be found by name
*/
public function getCommand($name, array $args = []);
/**
* Execute a single command.
*
* @param CommandInterface $command Command to execute
*
* @return ResultInterface
* @throws \Exception
*/
public function execute(CommandInterface $command);
/**
* Execute a command asynchronously.
*
* @param CommandInterface $command Command to execute
*
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function executeAsync(CommandInterface $command);
/**
* Returns a promise that is fulfilled with an
* {@see \Aws\Credentials\CredentialsInterface} object.
*
* If you need the credentials synchronously, then call the wait() method
* on the returned promise.
*
* @return PromiseInterface
*/
public function getCredentials();
/**
* Get the region to which the client is configured to send requests.
*
* @return string
*/
public function getRegion();
/**
* Gets the default endpoint, or base URL, used by the client.
*
* @return UriInterface
*/
public function getEndpoint();
/**
* Get the service description associated with the client.
*
* @return \Aws\Api\Service
*/
public function getApi();
/**
* Get a client configuration value.
*
* @param string|null $option The option to retrieve. Pass null to retrieve
* all options.
* @return mixed|null
*/
public function getConfig($option = null);
/**
* Get the handler list used to transfer commands.
*
* This list can be modified to add middleware or to change the underlying
* handler used to send HTTP requests.
*
* @return HandlerList
*/
public function getHandlerList();
/**
* Get a resource iterator for the specified operation.
*
* @param string $name Name of the iterator to retrieve.
* @param array $args Command arguments to use with each command.
*
* @return \Iterator
* @throws \UnexpectedValueException if the iterator config is invalid.
*/
public function getIterator($name, array $args = []);
/**
* Get a result paginator for the specified operation.
*
* @param string $name Name of the operation used for iterator
* @param array $args Command args to be used with each command
*
* @return \Aws\ResultPaginator
* @throws \UnexpectedValueException if the iterator config is invalid.
*/
public function getPaginator($name, array $args = []);
/**
* Wait until a resource is in a particular state.
*
* @param string|callable $name Name of the waiter that defines the wait
* configuration and conditions.
* @param array $args Args to be used with each command executed
* by the waiter. Waiter configuration options
* can be provided in an associative array in
* the @waiter key.
* @return void
* @throws \UnexpectedValueException if the waiter is invalid.
*/
public function waitUntil($name, array $args = []);
/**
* Get a waiter that waits until a resource is in a particular state.
*
* Retrieving a waiter can be useful when you wish to wait asynchronously:
*
* $waiter = $client->getWaiter('foo', ['bar' => 'baz']);
* $waiter->promise()->then(function () { echo 'Done!'; });
*
* @param string|callable $name Name of the waiter that defines the wait
* configuration and conditions.
* @param array $args Args to be used with each command executed
* by the waiter. Waiter configuration options
* can be provided in an associative array in
* the @waiter key.
* @return \Aws\Waiter
* @throws \UnexpectedValueException if the waiter is invalid.
*/
public function getWaiter($name, array $args = []);
}

View File

@@ -0,0 +1,93 @@
<?php
namespace Aws;
use Aws\Api\Service;
use GuzzleHttp\Promise\Promise;
/**
* A trait providing generic functionality for interacting with Amazon Web
* Services. This is meant to be used in classes implementing
* \Aws\AwsClientInterface
*/
trait AwsClientTrait
{
public function getPaginator($name, array $args = [])
{
$config = $this->getApi()->getPaginatorConfig($name);
return new ResultPaginator($this, $name, $args, $config);
}
public function getIterator($name, array $args = [])
{
$config = $this->getApi()->getPaginatorConfig($name);
if (!$config['result_key']) {
throw new \UnexpectedValueException(sprintf(
'There are no resources to iterate for the %s operation of %s',
$name, $this->getApi()['serviceFullName']
));
}
$key = is_array($config['result_key'])
? $config['result_key'][0]
: $config['result_key'];
if ($config['output_token'] && $config['input_token']) {
return $this->getPaginator($name, $args)->search($key);
}
$result = $this->execute($this->getCommand($name, $args))->search($key);
return new \ArrayIterator((array) $result);
}
public function waitUntil($name, array $args = [])
{
return $this->getWaiter($name, $args)->promise()->wait();
}
public function getWaiter($name, array $args = [])
{
$config = isset($args['@waiter']) ? $args['@waiter'] : [];
$config += $this->getApi()->getWaiterConfig($name);
return new Waiter($this, $name, $args, $config);
}
public function execute(CommandInterface $command)
{
return $this->executeAsync($command)->wait();
}
public function executeAsync(CommandInterface $command)
{
$handler = $command->getHandlerList()->resolve();
return $handler($command);
}
public function __call($name, array $args)
{
$params = isset($args[0]) ? $args[0] : [];
if (substr($name, -5) === 'Async') {
return $this->executeAsync(
$this->getCommand(substr($name, 0, -5), $params)
);
}
return $this->execute($this->getCommand($name, $params));
}
/**
* @param string $name
* @param array $args
*
* @return CommandInterface
*/
abstract public function getCommand($name, array $args = []);
/**
* @return Service
*/
abstract public function getApi();
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Aws;
/**
* Represents a simple cache interface.
*/
interface CacheInterface
{
/**
* Get a cache item by key.
*
* @param string $key Key to retrieve.
*
* @return mixed|null Returns the value or null if not found.
*/
public function get($key);
/**
* Set a cache key value.
*
* @param string $key Key to set
* @param mixed $value Value to set.
* @param int $ttl Number of seconds the item is allowed to live. Set
* to 0 to allow an unlimited lifetime.
*/
public function set($key, $value, $ttl = 0);
/**
* Remove a cache key.
*
* @param string $key Key to remove.
*/
public function remove($key);
}

View File

@@ -0,0 +1,658 @@
<?php
namespace Aws;
use Aws\Api\Validator;
use Aws\Api\ApiProvider;
use Aws\Api\Service;
use Aws\Credentials\Credentials;
use Aws\Credentials\CredentialsInterface;
use Aws\Endpoint\Partition;
use Aws\Endpoint\PartitionEndpointProvider;
use Aws\Endpoint\PartitionProviderInterface;
use Aws\Signature\SignatureProvider;
use Aws\Endpoint\EndpointProvider;
use Aws\Credentials\CredentialProvider;
use GuzzleHttp\Promise;
use InvalidArgumentException as IAE;
use Psr\Http\Message\RequestInterface;
/**
* @internal Resolves a hash of client arguments to construct a client.
*/
class ClientResolver
{
/** @var array */
private $argDefinitions;
/** @var array Map of types to a corresponding function */
private static $typeMap = [
'resource' => 'is_resource',
'callable' => 'is_callable',
'int' => 'is_int',
'bool' => 'is_bool',
'string' => 'is_string',
'object' => 'is_object',
'array' => 'is_array',
];
private static $defaultArgs = [
'service' => [
'type' => 'value',
'valid' => ['string'],
'doc' => 'Name of the service to utilize. This value will be supplied by default when using one of the SDK clients (e.g., Aws\\S3\\S3Client).',
'required' => true,
'internal' => true
],
'exception_class' => [
'type' => 'value',
'valid' => ['string'],
'doc' => 'Exception class to create when an error occurs.',
'default' => 'Aws\Exception\AwsException',
'internal' => true
],
'scheme' => [
'type' => 'value',
'valid' => ['string'],
'default' => 'https',
'doc' => 'URI scheme to use when connecting connect. The SDK will utilize "https" endpoints (i.e., utilize SSL/TLS connections) by default. You can attempt to connect to a service over an unencrypted "http" endpoint by setting ``scheme`` to "http".',
],
'endpoint' => [
'type' => 'value',
'valid' => ['string'],
'doc' => 'The full URI of the webservice. This is only required when connecting to a custom endpoint (e.g., a local version of S3).',
'fn' => [__CLASS__, '_apply_endpoint'],
],
'region' => [
'type' => 'value',
'valid' => ['string'],
'required' => [__CLASS__, '_missing_region'],
'doc' => 'Region to connect to. See http://docs.aws.amazon.com/general/latest/gr/rande.html for a list of available regions.',
],
'version' => [
'type' => 'value',
'valid' => ['string'],
'required' => [__CLASS__, '_missing_version'],
'doc' => 'The version of the webservice to utilize (e.g., 2006-03-01).',
],
'signature_provider' => [
'type' => 'value',
'valid' => ['callable'],
'doc' => 'A callable that accepts a signature version name (e.g., "v4"), a service name, and region, and returns a SignatureInterface object or null. This provider is used to create signers utilized by the client. See Aws\\Signature\\SignatureProvider for a list of built-in providers',
'default' => [__CLASS__, '_default_signature_provider'],
],
'endpoint_provider' => [
'type' => 'value',
'valid' => ['callable'],
'fn' => [__CLASS__, '_apply_endpoint_provider'],
'doc' => 'An optional PHP callable that accepts a hash of options including a "service" and "region" key and returns NULL or a hash of endpoint data, of which the "endpoint" key is required. See Aws\\Endpoint\\EndpointProvider for a list of built-in providers.',
'default' => [__CLASS__, '_default_endpoint_provider'],
],
'api_provider' => [
'type' => 'value',
'valid' => ['callable'],
'doc' => 'An optional PHP callable that accepts a type, service, and version argument, and returns an array of corresponding configuration data. The type value can be one of api, waiter, or paginator.',
'fn' => [__CLASS__, '_apply_api_provider'],
'default' => [ApiProvider::class, 'defaultProvider'],
],
'signature_version' => [
'type' => 'config',
'valid' => ['string'],
'doc' => 'A string representing a custom signature version to use with a service (e.g., v4). Note that per/operation signature version MAY override this requested signature version.',
'default' => [__CLASS__, '_default_signature_version'],
],
'signing_name' => [
'type' => 'config',
'valid' => ['string'],
'doc' => 'A string representing a custom service name to be used when calculating a request signature.',
'default' => [__CLASS__, '_default_signing_name'],
],
'signing_region' => [
'type' => 'config',
'valid' => ['string'],
'doc' => 'A string representing a custom region name to be used when calculating a request signature.',
'default' => [__CLASS__, '_default_signing_region'],
],
'profile' => [
'type' => 'config',
'valid' => ['string'],
'doc' => 'Allows you to specify which profile to use when credentials are created from the AWS credentials file in your HOME directory. This setting overrides the AWS_PROFILE environment variable. Note: Specifying "profile" will cause the "credentials" key to be ignored.',
'fn' => [__CLASS__, '_apply_profile'],
],
'credentials' => [
'type' => 'value',
'valid' => [CredentialsInterface::class, CacheInterface::class, 'array', 'bool', 'callable'],
'doc' => 'Specifies the credentials used to sign requests. Provide an Aws\Credentials\CredentialsInterface object, an associative array of "key", "secret", and an optional "token" key, `false` to use null credentials, or a callable credentials provider used to create credentials or return null. See Aws\\Credentials\\CredentialProvider for a list of built-in credentials providers. If no credentials are provided, the SDK will attempt to load them from the environment.',
'fn' => [__CLASS__, '_apply_credentials'],
'default' => [CredentialProvider::class, 'defaultProvider'],
],
'stats' => [
'type' => 'value',
'valid' => ['bool', 'array'],
'default' => false,
'doc' => 'Set to true to gather transfer statistics on requests sent. Alternatively, you can provide an associative array with the following keys: retries: (bool) Set to false to disable reporting on retries attempted; http: (bool) Set to true to enable collecting statistics from lower level HTTP adapters (e.g., values returned in GuzzleHttp\TransferStats). HTTP handlers must support an http_stats_receiver option for this to have an effect; timer: (bool) Set to true to enable a command timer that reports the total wall clock time spent on an operation in seconds.',
'fn' => [__CLASS__, '_apply_stats'],
],
'retries' => [
'type' => 'value',
'valid' => ['int'],
'doc' => 'Configures the maximum number of allowed retries for a client (pass 0 to disable retries). ',
'fn' => [__CLASS__, '_apply_retries'],
'default' => 3,
],
'validate' => [
'type' => 'value',
'valid' => ['bool', 'array'],
'default' => true,
'doc' => 'Set to false to disable client-side parameter validation. Set to true to utilize default validation constraints. Set to an associative array of validation options to enable specific validation constraints.',
'fn' => [__CLASS__, '_apply_validate'],
],
'debug' => [
'type' => 'value',
'valid' => ['bool', 'array'],
'doc' => 'Set to true to display debug information when sending requests. Alternatively, you can provide an associative array with the following keys: logfn: (callable) Function that is invoked with log messages; stream_size: (int) When the size of a stream is greater than this number, the stream data will not be logged (set to "0" to not log any stream data); scrub_auth: (bool) Set to false to disable the scrubbing of auth data from the logged messages; http: (bool) Set to false to disable the "debug" feature of lower level HTTP adapters (e.g., verbose curl output).',
'fn' => [__CLASS__, '_apply_debug'],
],
'http' => [
'type' => 'value',
'valid' => ['array'],
'default' => [],
'doc' => 'Set to an array of SDK request options to apply to each request (e.g., proxy, verify, etc.).',
],
'http_handler' => [
'type' => 'value',
'valid' => ['callable'],
'doc' => 'An HTTP handler is a function that accepts a PSR-7 request object and returns a promise that is fulfilled with a PSR-7 response object or rejected with an array of exception data. NOTE: This option supersedes any provided "handler" option.',
'fn' => [__CLASS__, '_apply_http_handler']
],
'handler' => [
'type' => 'value',
'valid' => ['callable'],
'doc' => 'A handler that accepts a command object, request object and returns a promise that is fulfilled with an Aws\ResultInterface object or rejected with an Aws\Exception\AwsException. A handler does not accept a next handler as it is terminal and expected to fulfill a command. If no handler is provided, a default Guzzle handler will be utilized.',
'fn' => [__CLASS__, '_apply_handler'],
'default' => [__CLASS__, '_default_handler']
],
'ua_append' => [
'type' => 'value',
'valid' => ['string', 'array'],
'doc' => 'Provide a string or array of strings to send in the User-Agent header.',
'fn' => [__CLASS__, '_apply_user_agent'],
'default' => [],
],
];
/**
* Gets an array of default client arguments, each argument containing a
* hash of the following:
*
* - type: (string, required) option type described as follows:
* - value: The default option type.
* - config: The provided value is made available in the client's
* getConfig() method.
* - valid: (array, required) Valid PHP types or class names. Note: null
* is not an allowed type.
* - required: (bool, callable) Whether or not the argument is required.
* Provide a function that accepts an array of arguments and returns a
* string to provide a custom error message.
* - default: (mixed) The default value of the argument if not provided. If
* a function is provided, then it will be invoked to provide a default
* value. The function is provided the array of options and is expected
* to return the default value of the option.
* - doc: (string) The argument documentation string.
* - fn: (callable) Function used to apply the argument. The function
* accepts the provided value, array of arguments by reference, and an
* event emitter.
*
* Note: Order is honored and important when applying arguments.
*
* @return array
*/
public static function getDefaultArguments()
{
return self::$defaultArgs;
}
/**
* @param array $argDefinitions Client arguments.
*/
public function __construct(array $argDefinitions)
{
$this->argDefinitions = $argDefinitions;
}
/**
* Resolves client configuration options and attached event listeners.
*
* @param array $args Provided constructor arguments.
* @param HandlerList $list Handler list to augment.
*
* @return array Returns the array of provided options.
* @throws \InvalidArgumentException
* @see Aws\AwsClient::__construct for a list of available options.
*/
public function resolve(array $args, HandlerList $list)
{
$args['config'] = [];
foreach ($this->argDefinitions as $key => $a) {
// Add defaults, validate required values, and skip if not set.
if (!isset($args[$key])) {
if (isset($a['default'])) {
// Merge defaults in when not present.
$args[$key] = is_callable($a['default'])
? $a['default']($args)
: $a['default'];
} elseif (empty($a['required'])) {
continue;
} else {
$this->throwRequired($args);
}
}
// Validate the types against the provided value.
foreach ($a['valid'] as $check) {
if (isset(self::$typeMap[$check])) {
$fn = self::$typeMap[$check];
if ($fn($args[$key])) {
goto is_valid;
}
} elseif ($args[$key] instanceof $check) {
goto is_valid;
}
}
$this->invalidType($key, $args[$key]);
// Apply the value
is_valid:
if (isset($a['fn'])) {
$a['fn']($args[$key], $args, $list);
}
if ($a['type'] === 'config') {
$args['config'][$key] = $args[$key];
}
}
return $args;
}
/**
* Creates a verbose error message for an invalid argument.
*
* @param string $name Name of the argument that is missing.
* @param array $args Provided arguments
* @param bool $useRequired Set to true to show the required fn text if
* available instead of the documentation.
* @return string
*/
private function getArgMessage($name, $args = [], $useRequired = false)
{
$arg = $this->argDefinitions[$name];
$msg = '';
$modifiers = [];
if (isset($arg['valid'])) {
$modifiers[] = implode('|', $arg['valid']);
}
if (isset($arg['choice'])) {
$modifiers[] = 'One of ' . implode(', ', $arg['choice']);
}
if ($modifiers) {
$msg .= '(' . implode('; ', $modifiers) . ')';
}
$msg = wordwrap("{$name}: {$msg}", 75, "\n ");
if ($useRequired && is_callable($arg['required'])) {
$msg .= "\n\n ";
$msg .= str_replace("\n", "\n ", call_user_func($arg['required'], $args));
} elseif (isset($arg['doc'])) {
$msg .= wordwrap("\n\n {$arg['doc']}", 75, "\n ");
}
return $msg;
}
/**
* Throw when an invalid type is encountered.
*
* @param string $name Name of the value being validated.
* @param mixed $provided The provided value.
* @throws \InvalidArgumentException
*/
private function invalidType($name, $provided)
{
$expected = implode('|', $this->argDefinitions[$name]['valid']);
$msg = "Invalid configuration value "
. "provided for \"{$name}\". Expected {$expected}, but got "
. describe_type($provided) . "\n\n"
. $this->getArgMessage($name);
throw new IAE($msg);
}
/**
* Throws an exception for missing required arguments.
*
* @param array $args Passed in arguments.
* @throws \InvalidArgumentException
*/
private function throwRequired(array $args)
{
$missing = [];
foreach ($this->argDefinitions as $k => $a) {
if (empty($a['required'])
|| isset($a['default'])
|| array_key_exists($k, $args)
) {
continue;
}
$missing[] = $this->getArgMessage($k, $args, true);
}
$msg = "Missing required client configuration options: \n\n";
$msg .= implode("\n\n", $missing);
throw new IAE($msg);
}
public static function _apply_retries($value, array &$args, HandlerList $list)
{
if ($value) {
$decider = RetryMiddleware::createDefaultDecider($value);
$list->appendSign(
Middleware::retry($decider, null, $args['stats']['retries']),
'retry'
);
}
}
public static function _apply_credentials($value, array &$args)
{
if (is_callable($value)) {
return;
} elseif ($value instanceof CredentialsInterface) {
$args['credentials'] = CredentialProvider::fromCredentials($value);
} elseif (is_array($value)
&& isset($value['key'])
&& isset($value['secret'])
) {
$args['credentials'] = CredentialProvider::fromCredentials(
new Credentials(
$value['key'],
$value['secret'],
isset($value['token']) ? $value['token'] : null,
isset($value['expires']) ? $value['expires'] : null
)
);
} elseif ($value === false) {
$args['credentials'] = CredentialProvider::fromCredentials(
new Credentials('', '')
);
$args['config']['signature_version'] = 'anonymous';
} elseif ($value instanceof CacheInterface) {
$args['credentials'] = CredentialProvider::defaultProvider($args);
} else {
throw new IAE('Credentials must be an instance of '
. 'Aws\Credentials\CredentialsInterface, an associative '
. 'array that contains "key", "secret", and an optional "token" '
. 'key-value pairs, a credentials provider function, or false.');
}
}
public static function _apply_api_provider(callable $value, array &$args, HandlerList $list)
{
$api = new Service(
ApiProvider::resolve(
$value,
'api',
$args['service'],
$args['version']
),
$value
);
$args['api'] = $api;
$args['serializer'] = Service::createSerializer($api, $args['endpoint']);
$args['parser'] = Service::createParser($api);
$args['error_parser'] = Service::createErrorParser($api->getProtocol());
$list->prependBuild(Middleware::requestBuilder($args['serializer']), 'builder');
}
public static function _apply_endpoint_provider(callable $value, array &$args)
{
if (!isset($args['endpoint'])) {
// Invoke the endpoint provider and throw if it does not resolve.
$result = EndpointProvider::resolve($value, [
'service' => $args['service'],
'region' => $args['region'],
'scheme' => $args['scheme']
]);
$args['endpoint'] = $result['endpoint'];
if (isset($result['signatureVersion'])) {
$args['config']['signature_version'] = $result['signatureVersion'];
}
if (isset($result['signingRegion'])) {
$args['config']['signing_region'] = $result['signingRegion'];
}
if (isset($result['signingName'])) {
$args['config']['signing_name'] = $result['signingName'];
}
}
}
public static function _apply_debug($value, array &$args, HandlerList $list)
{
if ($value !== false) {
$list->interpose(new TraceMiddleware($value === true ? [] : $value));
}
}
public static function _apply_stats($value, array &$args, HandlerList $list)
{
// Create an array of stat collectors that are disabled (set to false)
// by default. If the user has passed in true, enable all stat
// collectors.
$defaults = array_fill_keys(
['http', 'retries', 'timer'],
$value === true
);
$args['stats'] = is_array($value)
? array_replace($defaults, $value)
: $defaults;
if ($args['stats']['timer']) {
$list->prependInit(Middleware::timer(), 'timer');
}
}
public static function _apply_profile($_, array &$args)
{
$args['credentials'] = CredentialProvider::ini($args['profile']);
}
public static function _apply_validate($value, array &$args, HandlerList $list)
{
if ($value === false) {
return;
}
$validator = $value === true
? new Validator()
: new Validator($value);
$list->appendValidate(
Middleware::validation($args['api'], $validator),
'validation'
);
}
public static function _apply_handler($value, array &$args, HandlerList $list)
{
$list->setHandler($value);
}
public static function _default_handler(array &$args)
{
return new WrappedHttpHandler(
default_http_handler(),
$args['parser'],
$args['error_parser'],
$args['exception_class'],
$args['stats']['http']
);
}
public static function _apply_http_handler($value, array &$args, HandlerList $list)
{
$args['handler'] = new WrappedHttpHandler(
$value,
$args['parser'],
$args['error_parser'],
$args['exception_class'],
$args['stats']['http']
);
}
public static function _apply_user_agent($value, array &$args, HandlerList $list)
{
if (!is_array($value)) {
$value = [$value];
}
$value = array_map('strval', $value);
array_unshift($value, 'aws-sdk-php/' . Sdk::VERSION);
$args['ua_append'] = $value;
$list->appendBuild(static function (callable $handler) use ($value) {
return function (
CommandInterface $command,
RequestInterface $request
) use ($handler, $value) {
return $handler($command, $request->withHeader(
'User-Agent',
implode(' ', array_merge(
$value,
$request->getHeader('User-Agent')
))
));
};
});
}
public static function _apply_endpoint($value, array &$args, HandlerList $list)
{
$parts = parse_url($value);
if (empty($parts['scheme']) || empty($parts['host'])) {
throw new IAE(
'Endpoints must be full URIs and include a scheme and host'
);
}
$args['endpoint'] = $value;
}
public static function _default_endpoint_provider(array $args)
{
return PartitionEndpointProvider::defaultProvider()
->getPartition($args['region'], $args['service']);
}
public static function _default_signature_provider()
{
return SignatureProvider::defaultProvider();
}
public static function _default_signature_version(array &$args)
{
if (isset($args['config']['signature_version'])) {
return $args['config']['signature_version'];
}
$args['__partition_result'] = isset($args['__partition_result'])
? isset($args['__partition_result'])
: call_user_func(PartitionEndpointProvider::defaultProvider(), [
'service' => $args['service'],
'region' => $args['region'],
]);
return isset($args['__partition_result']['signatureVersion'])
? $args['__partition_result']['signatureVersion']
: $args['api']->getSignatureVersion();
}
public static function _default_signing_name(array &$args)
{
if (isset($args['config']['signing_name'])) {
return $args['config']['signing_name'];
}
$args['__partition_result'] = isset($args['__partition_result'])
? isset($args['__partition_result'])
: call_user_func(PartitionEndpointProvider::defaultProvider(), [
'service' => $args['service'],
'region' => $args['region'],
]);
if (isset($args['__partition_result']['signingName'])) {
return $args['__partition_result']['signingName'];
}
if ($signingName = $args['api']->getSigningName()) {
return $signingName;
}
return $args['service'];
}
public static function _default_signing_region(array &$args)
{
if (isset($args['config']['signing_region'])) {
return $args['config']['signing_region'];
}
$args['__partition_result'] = isset($args['__partition_result'])
? isset($args['__partition_result'])
: call_user_func(PartitionEndpointProvider::defaultProvider(), [
'service' => $args['service'],
'region' => $args['region'],
]);
return isset($args['__partition_result']['signingRegion'])
? $args['__partition_result']['signingRegion']
: $args['region'];
}
public static function _missing_version(array $args)
{
$service = isset($args['service']) ? $args['service'] : '';
$versions = ApiProvider::defaultProvider()->getVersions($service);
$versions = implode("\n", array_map(function ($v) {
return "* \"$v\"";
}, $versions)) ?: '* (none found)';
return <<<EOT
A "version" configuration value is required. Specifying a version constraint
ensures that your code will not be affected by a breaking change made to the
service. For example, when using Amazon S3, you can lock your API version to
"2006-03-01".
Your build of the SDK has the following version(s) of "{$service}": {$versions}
You may provide "latest" to the "version" configuration value to utilize the
most recent available API version that your client's API provider can find.
Note: Using 'latest' in a production application is not recommended.
A list of available API versions can be found on each client's API documentation
page: http://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html. If you are
unable to load a specific API version, then you may need to update your copy of
the SDK.
EOT;
}
public static function _missing_region(array $args)
{
$service = isset($args['service']) ? $args['service'] : '';
return <<<EOT
A "region" configuration value is required for the "{$service}" service
(e.g., "us-west-2"). A list of available public regions and endpoints can be
found at http://docs.aws.amazon.com/general/latest/gr/rande.html.
EOT;
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace Aws\CloudFormation;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS CloudFormation** service.
*
* @method \Aws\Result cancelUpdateStack(array $args = [])
* @method \GuzzleHttp\Promise\Promise cancelUpdateStackAsync(array $args = [])
* @method \Aws\Result continueUpdateRollback(array $args = [])
* @method \GuzzleHttp\Promise\Promise continueUpdateRollbackAsync(array $args = [])
* @method \Aws\Result createChangeSet(array $args = [])
* @method \GuzzleHttp\Promise\Promise createChangeSetAsync(array $args = [])
* @method \Aws\Result createStack(array $args = [])
* @method \GuzzleHttp\Promise\Promise createStackAsync(array $args = [])
* @method \Aws\Result deleteChangeSet(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteChangeSetAsync(array $args = [])
* @method \Aws\Result deleteStack(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteStackAsync(array $args = [])
* @method \Aws\Result describeAccountLimits(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAccountLimitsAsync(array $args = [])
* @method \Aws\Result describeChangeSet(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeChangeSetAsync(array $args = [])
* @method \Aws\Result describeStackEvents(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeStackEventsAsync(array $args = [])
* @method \Aws\Result describeStackResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeStackResourceAsync(array $args = [])
* @method \Aws\Result describeStackResources(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeStackResourcesAsync(array $args = [])
* @method \Aws\Result describeStacks(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeStacksAsync(array $args = [])
* @method \Aws\Result estimateTemplateCost(array $args = [])
* @method \GuzzleHttp\Promise\Promise estimateTemplateCostAsync(array $args = [])
* @method \Aws\Result executeChangeSet(array $args = [])
* @method \GuzzleHttp\Promise\Promise executeChangeSetAsync(array $args = [])
* @method \Aws\Result getStackPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise getStackPolicyAsync(array $args = [])
* @method \Aws\Result getTemplate(array $args = [])
* @method \GuzzleHttp\Promise\Promise getTemplateAsync(array $args = [])
* @method \Aws\Result getTemplateSummary(array $args = [])
* @method \GuzzleHttp\Promise\Promise getTemplateSummaryAsync(array $args = [])
* @method \Aws\Result listChangeSets(array $args = [])
* @method \GuzzleHttp\Promise\Promise listChangeSetsAsync(array $args = [])
* @method \Aws\Result listStackResources(array $args = [])
* @method \GuzzleHttp\Promise\Promise listStackResourcesAsync(array $args = [])
* @method \Aws\Result listStacks(array $args = [])
* @method \GuzzleHttp\Promise\Promise listStacksAsync(array $args = [])
* @method \Aws\Result setStackPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise setStackPolicyAsync(array $args = [])
* @method \Aws\Result signalResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise signalResourceAsync(array $args = [])
* @method \Aws\Result updateStack(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateStackAsync(array $args = [])
* @method \Aws\Result validateTemplate(array $args = [])
* @method \GuzzleHttp\Promise\Promise validateTemplateAsync(array $args = [])
*/
class CloudFormationClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CloudFormation\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the AWS CloudFormation service.
*/
class CloudFormationException extends AwsException {}

View File

@@ -0,0 +1,152 @@
<?php
namespace Aws\CloudFront;
use Aws\AwsClient;
/**
* This client is used to interact with the **Amazon CloudFront** service.
*
* @method \Aws\Result createCloudFrontOriginAccessIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise createCloudFrontOriginAccessIdentityAsync(array $args = [])
* @method \Aws\Result createDistribution(array $args = [])
* @method \GuzzleHttp\Promise\Promise createDistributionAsync(array $args = [])
* @method \Aws\Result createInvalidation(array $args = [])
* @method \GuzzleHttp\Promise\Promise createInvalidationAsync(array $args = [])
* @method \Aws\Result createStreamingDistribution(array $args = [])
* @method \GuzzleHttp\Promise\Promise createStreamingDistributionAsync(array $args = [])
* @method \Aws\Result deleteCloudFrontOriginAccessIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteCloudFrontOriginAccessIdentityAsync(array $args = [])
* @method \Aws\Result deleteDistribution(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDistributionAsync(array $args = [])
* @method \Aws\Result deleteStreamingDistribution(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteStreamingDistributionAsync(array $args = [])
* @method \Aws\Result getCloudFrontOriginAccessIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCloudFrontOriginAccessIdentityAsync(array $args = [])
* @method \Aws\Result getCloudFrontOriginAccessIdentityConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCloudFrontOriginAccessIdentityConfigAsync(array $args = [])
* @method \Aws\Result getDistribution(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDistributionAsync(array $args = [])
* @method \Aws\Result getDistributionConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDistributionConfigAsync(array $args = [])
* @method \Aws\Result getInvalidation(array $args = [])
* @method \GuzzleHttp\Promise\Promise getInvalidationAsync(array $args = [])
* @method \Aws\Result getStreamingDistribution(array $args = [])
* @method \GuzzleHttp\Promise\Promise getStreamingDistributionAsync(array $args = [])
* @method \Aws\Result getStreamingDistributionConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise getStreamingDistributionConfigAsync(array $args = [])
* @method \Aws\Result listCloudFrontOriginAccessIdentities(array $args = [])
* @method \GuzzleHttp\Promise\Promise listCloudFrontOriginAccessIdentitiesAsync(array $args = [])
* @method \Aws\Result listDistributions(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDistributionsAsync(array $args = [])
* @method \Aws\Result listDistributionsByWebACLId(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDistributionsByWebACLIdAsync(array $args = [])
* @method \Aws\Result listInvalidations(array $args = [])
* @method \GuzzleHttp\Promise\Promise listInvalidationsAsync(array $args = [])
* @method \Aws\Result listStreamingDistributions(array $args = [])
* @method \GuzzleHttp\Promise\Promise listStreamingDistributionsAsync(array $args = [])
* @method \Aws\Result updateCloudFrontOriginAccessIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateCloudFrontOriginAccessIdentityAsync(array $args = [])
* @method \Aws\Result updateDistribution(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateDistributionAsync(array $args = [])
* @method \Aws\Result updateStreamingDistribution(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateStreamingDistributionAsync(array $args = [])
* @method \Aws\Result createDistributionWithTags(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
* @method \GuzzleHttp\Promise\Promise createDistributionWithTagsAsync(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
* @method \Aws\Result createStreamingDistributionWithTags(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
* @method \GuzzleHttp\Promise\Promise createStreamingDistributionWithTagsAsync(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
* @method \Aws\Result listTagsForResource(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
* @method \GuzzleHttp\Promise\Promise listTagsForResourceAsync(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
* @method \Aws\Result tagResource(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
* @method \GuzzleHttp\Promise\Promise tagResourceAsync(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
* @method \Aws\Result untagResource(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
* @method \GuzzleHttp\Promise\Promise untagResourceAsync(array $args = []) (supported in versions 2016-08-01, 2016-08-20)
*/
class CloudFrontClient extends AwsClient
{
/**
* Create a signed Amazon CloudFront URL.
*
* This method accepts an array of configuration options:
*
* - url: (string) URL of the resource being signed (can include query
* string and wildcards). For example: rtmp://s5c39gqb8ow64r.cloudfront.net/videos/mp3_name.mp3
* http://d111111abcdef8.cloudfront.net/images/horizon.jpg?size=large&license=yes
* - policy: (string) JSON policy. Use this option when creating a signed
* URL for a custom policy.
* - expires: (int) UTC Unix timestamp used when signing with a canned
* policy. Not required when passing a custom 'policy' option.
* - key_pair_id: (string) The ID of the key pair used to sign CloudFront
* URLs for private distributions.
* - private_key: (string) The filepath ot the private key used to sign
* CloudFront URLs for private distributions.
*
* @param array $options Array of configuration options used when signing
*
* @return string Signed URL with authentication parameters
* @throws \InvalidArgumentException if url, key_pair_id, or private_key
* were not specified.
* @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/WorkingWithStreamingDistributions.html
*/
public function getSignedUrl(array $options)
{
foreach (['url', 'key_pair_id', 'private_key'] as $required) {
if (!isset($options[$required])) {
throw new \InvalidArgumentException("$required is required");
}
}
$urlSigner = new UrlSigner(
$options['key_pair_id'],
$options['private_key']
);
return $urlSigner->getSignedUrl(
$options['url'],
isset($options['expires']) ? $options['expires'] : null,
isset($options['policy']) ? $options['policy'] : null
);
}
/**
* Create a signed Amazon CloudFront cookie.
*
* This method accepts an array of configuration options:
*
* - url: (string) URL of the resource being signed (can include query
* string and wildcards). For example: http://d111111abcdef8.cloudfront.net/images/horizon.jpg?size=large&license=yes
* - policy: (string) JSON policy. Use this option when creating a signed
* URL for a custom policy.
* - expires: (int) UTC Unix timestamp used when signing with a canned
* policy. Not required when passing a custom 'policy' option.
* - key_pair_id: (string) The ID of the key pair used to sign CloudFront
* URLs for private distributions.
* - private_key: (string) The filepath ot the private key used to sign
* CloudFront URLs for private distributions.
*
* @param array $options Array of configuration options used when signing
*
* @return array Key => value pairs of signed cookies to set
* @throws \InvalidArgumentException if url, key_pair_id, or private_key
* were not specified.
* @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/WorkingWithStreamingDistributions.html
*/
public function getSignedCookie(array $options)
{
foreach (['key_pair_id', 'private_key'] as $required) {
if (!isset($options[$required])) {
throw new \InvalidArgumentException("$required is required");
}
}
$cookieSigner = new CookieSigner(
$options['key_pair_id'],
$options['private_key']
);
return $cookieSigner->getSignedCookie(
isset($options['url']) ? $options['url'] : null,
isset($options['expires']) ? $options['expires'] : null,
isset($options['policy']) ? $options['policy'] : null
);
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Aws\CloudFront;
class CookieSigner
{
/** @var Signer */
private $signer;
private static $schemes = [
'http' => true,
'https' => true,
];
/**
* @param $keyPairId string ID of the key pair
* @param $privateKey string Path to the private key used for signing
*
* @throws \RuntimeException if the openssl extension is missing
* @throws \InvalidArgumentException if the private key cannot be found.
*/
public function __construct($keyPairId, $privateKey)
{
$this->signer = new Signer($keyPairId, $privateKey);
}
/**
* Create a signed Amazon CloudFront Cookie.
*
* @param string $url URL to sign (can include query string
* and wildcards). Not required
* when passing a custom $policy.
* @param string|integer|null $expires UTC Unix timestamp used when signing
* with a canned policy. Not required
* when passing a custom $policy.
* @param string $policy JSON policy. Use this option when
* creating a signed cookie for a custom
* policy.
*
* @return array The authenticated cookie parameters
* @throws \InvalidArgumentException if the URL provided is invalid
* @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-cookies.html
*/
public function getSignedCookie($url = null, $expires = null, $policy = null)
{
if ($url) {
$this->validateUrl($url);
}
$cookieParameters = [];
$signature = $this->signer->getSignature($url, $expires, $policy);
foreach ($signature as $key => $value) {
$cookieParameters["CloudFront-$key"] = $value;
}
return $cookieParameters;
}
private function validateUrl($url)
{
$scheme = str_replace('*', '', explode('://', $url)[0]);
if (empty(self::$schemes[strtolower($scheme)])) {
throw new \InvalidArgumentException('Invalid or missing URI scheme');
}
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CloudFront\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the Amazon CloudFront service.
*/
class CloudFrontException extends AwsException {}

View File

@@ -0,0 +1,108 @@
<?php
namespace Aws\CloudFront;
/**
* @internal
*/
class Signer
{
private $keyPairId;
private $pk;
/**
* A signer for creating the signature values used in CloudFront signed URLs
* and signed cookies.
*
* @param $keyPairId string ID of the key pair
* @param $privateKey string Path to the private key used for signing
*
* @throws \RuntimeException if the openssl extension is missing
* @throws \InvalidArgumentException if the private key cannot be found.
*/
public function __construct($keyPairId, $privateKey)
{
if (!extension_loaded('openssl')) {
//@codeCoverageIgnoreStart
throw new \RuntimeException('The openssl extension is required to '
. 'sign CloudFront urls.');
//@codeCoverageIgnoreEnd
}
$this->keyPairId = $keyPairId;
if (!file_exists($privateKey)) {
throw new \InvalidArgumentException("PK file not found: $privateKey");
}
$this->pk = file_get_contents($privateKey);
}
/**
* Create the values used to construct signed URLs and cookies.
*
* @param string $resource The CloudFront resource to which
* this signature will grant access.
* Not used when a custom policy is
* provided.
* @param string|integer|null $expires UTC Unix timestamp used when
* signing with a canned policy.
* Not required when passing a
* custom $policy.
* @param string $policy JSON policy. Use this option when
* creating a signature for a custom
* policy.
*
* @return array The values needed to construct a signed URL or cookie
* @throws \InvalidArgumentException when not provided either a policy or a
* resource and a expires
*
* @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-cookies.html
*/
public function getSignature($resource = null, $expires = null, $policy = null)
{
$signatureHash = [];
if ($policy) {
$policy = preg_replace('/\s/s', '', $policy);
$signatureHash['Policy'] = $this->encode($policy);
} elseif ($resource && $expires) {
$policy = $this->createCannedPolicy($resource, $expires);
$signatureHash['Expires'] = $expires;
} else {
throw new \InvalidArgumentException('Either a policy or a resource'
. ' and an expiration time must be provided.');
}
$signatureHash['Signature'] = $this->encode($this->sign($policy));
$signatureHash['Key-Pair-Id'] = $this->keyPairId;
return $signatureHash;
}
private function createCannedPolicy($resource, $expiration)
{
return json_encode([
'Statement' => [
[
'Resource' => $resource,
'Condition' => [
'DateLessThan' => ['AWS:EpochTime' => $expiration],
],
],
],
], JSON_UNESCAPED_SLASHES);
}
private function sign($policy)
{
$signature = '';
openssl_sign($policy, $signature, $this->pk);
return $signature;
}
private function encode($policy)
{
return strtr(base64_encode($policy), '+=/', '-_~');
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace Aws\CloudFront;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\UriInterface;
/**
* Creates signed URLs for Amazon CloudFront resources.
*/
class UrlSigner
{
private $signer;
/**
* @param $keyPairId string ID of the key pair
* @param $privateKey string Path to the private key used for signing
*
* @throws \RuntimeException if the openssl extension is missing
* @throws \InvalidArgumentException if the private key cannot be found.
*/
public function __construct($keyPairId, $privateKey)
{
$this->signer = new Signer($keyPairId, $privateKey);
}
/**
* Create a signed Amazon CloudFront URL.
*
* Keep in mind that URLs meant for use in media/flash players may have
* different requirements for URL formats (e.g. some require that the
* extension be removed, some require the file name to be prefixed
* - mp4:<path>, some require you to add "/cfx/st" into your URL).
*
* @param string $url URL to sign (can include query
* string string and wildcards)
* @param string|integer|null $expires UTC Unix timestamp used when signing
* with a canned policy. Not required
* when passing a custom $policy.
* @param string $policy JSON policy. Use this option when
* creating a signed URL for a custom
* policy.
*
* @return string The file URL with authentication parameters
* @throws \InvalidArgumentException if the URL provided is invalid
* @link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/WorkingWithStreamingDistributions.html
*/
public function getSignedUrl($url, $expires = null, $policy = null)
{
// Determine the scheme of the url
$urlSections = explode('://', $url);
if (count($urlSections) < 2) {
throw new \InvalidArgumentException("Invalid URL: {$url}");
}
// Get the real scheme by removing wildcards from the scheme
$scheme = str_replace('*', '', $urlSections[0]);
$uri = new Uri($scheme . '://' . $urlSections[1]);
$query = Psr7\parse_query($uri->getQuery(), PHP_QUERY_RFC3986);
$signature = $this->signer->getSignature(
$this->createResource($scheme, (string) $uri),
$expires,
$policy
);
$uri = $uri->withQuery(
http_build_query($query + $signature, null, '&', PHP_QUERY_RFC3986)
);
return $scheme === 'rtmp'
? $this->createRtmpUrl($uri)
: (string) $uri;
}
private function createRtmpUrl(UriInterface $uri)
{
// Use a relative URL when creating Flash player URLs
$result = ltrim($uri->getPath(), '/');
if ($query = $uri->getQuery()) {
$result .= '?' . $query;
}
return $result;
}
/**
* @param $scheme
* @param $url
*
* @return string
*/
private function createResource($scheme, $url)
{
switch ($scheme) {
case 'http':
case 'http*':
case 'https':
return $url;
case 'rtmp':
$parts = parse_url($url);
$pathParts = pathinfo($parts['path']);
$resource = ltrim(
$pathParts['dirname'] . '/' . $pathParts['basename'],
'/'
);
// Add a query string if present.
if (isset($parts['query'])) {
$resource .= "?{$parts['query']}";
}
return $resource;
}
throw new \InvalidArgumentException("Invalid URI scheme: {$scheme}. "
. "Scheme must be one of: http, https, or rtmp");
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace Aws\CloudHsm;
use Aws\Api\ApiProvider;
use Aws\Api\DocModel;
use Aws\Api\Service;
use Aws\AwsClient;
/**
* This client is used to interact with **AWS CloudHSM**.
*
* @method \Aws\Result addTagsToResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise addTagsToResourceAsync(array $args = [])
* @method \Aws\Result createHapg(array $args = [])
* @method \GuzzleHttp\Promise\Promise createHapgAsync(array $args = [])
* @method \Aws\Result createHsm(array $args = [])
* @method \GuzzleHttp\Promise\Promise createHsmAsync(array $args = [])
* @method \Aws\Result createLunaClient(array $args = [])
* @method \GuzzleHttp\Promise\Promise createLunaClientAsync(array $args = [])
* @method \Aws\Result deleteHapg(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteHapgAsync(array $args = [])
* @method \Aws\Result deleteHsm(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteHsmAsync(array $args = [])
* @method \Aws\Result deleteLunaClient(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteLunaClientAsync(array $args = [])
* @method \Aws\Result describeHapg(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeHapgAsync(array $args = [])
* @method \Aws\Result describeHsm(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeHsmAsync(array $args = [])
* @method \Aws\Result describeLunaClient(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeLunaClientAsync(array $args = [])
* @method \Aws\Result getConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise getConfigAsync(array $args = [])
* @method \Aws\Result listAvailableZones(array $args = [])
* @method \GuzzleHttp\Promise\Promise listAvailableZonesAsync(array $args = [])
* @method \Aws\Result listHapgs(array $args = [])
* @method \GuzzleHttp\Promise\Promise listHapgsAsync(array $args = [])
* @method \Aws\Result listHsms(array $args = [])
* @method \GuzzleHttp\Promise\Promise listHsmsAsync(array $args = [])
* @method \Aws\Result listLunaClients(array $args = [])
* @method \GuzzleHttp\Promise\Promise listLunaClientsAsync(array $args = [])
* @method \Aws\Result listTagsForResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsForResourceAsync(array $args = [])
* @method \Aws\Result modifyHapg(array $args = [])
* @method \GuzzleHttp\Promise\Promise modifyHapgAsync(array $args = [])
* @method \Aws\Result modifyHsm(array $args = [])
* @method \GuzzleHttp\Promise\Promise modifyHsmAsync(array $args = [])
* @method \Aws\Result modifyLunaClient(array $args = [])
* @method \GuzzleHttp\Promise\Promise modifyLunaClientAsync(array $args = [])
* @method \Aws\Result removeTagsFromResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise removeTagsFromResourceAsync(array $args = [])
*/
class CloudHsmClient extends AwsClient
{
public function __call($name, array $args)
{
// Overcomes a naming collision with `AwsClient::getConfig`.
if (lcfirst($name) === 'getConfigFiles') {
$name = 'GetConfig';
} elseif (lcfirst($name) === 'getConfigFilesAsync') {
$name = 'GetConfigAsync';
}
return parent::__call($name, $args);
}
/**
* @internal
* @codeCoverageIgnore
*/
public static function applyDocFilters(array $api, array $docs)
{
// Overcomes a naming collision with `AwsClient::getConfig`.
$api['operations']['GetConfigFiles'] = $api['operations']['GetConfig'];
$docs['operations']['GetConfigFiles'] = $docs['operations']['GetConfig'];
unset($api['operations']['GetConfig'], $docs['operations']['GetConfig']);
ksort($api['operations']);
return [
new Service($api, ApiProvider::defaultProvider()),
new DocModel($docs)
];
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CloudHsm\Exception;
use Aws\Exception\AwsException;
/**
* AWS CloudHSM exception.
*/
class CloudHsmException extends AwsException {}

View File

@@ -0,0 +1,58 @@
<?php
namespace Aws\CloudSearch;
use Aws\AwsClient;
/**
* This client is used to interact with the **Amazon CloudSearch** service.
*
* @method \Aws\Result buildSuggesters(array $args = [])
* @method \GuzzleHttp\Promise\Promise buildSuggestersAsync(array $args = [])
* @method \Aws\Result createDomain(array $args = [])
* @method \GuzzleHttp\Promise\Promise createDomainAsync(array $args = [])
* @method \Aws\Result defineAnalysisScheme(array $args = [])
* @method \GuzzleHttp\Promise\Promise defineAnalysisSchemeAsync(array $args = [])
* @method \Aws\Result defineExpression(array $args = [])
* @method \GuzzleHttp\Promise\Promise defineExpressionAsync(array $args = [])
* @method \Aws\Result defineIndexField(array $args = [])
* @method \GuzzleHttp\Promise\Promise defineIndexFieldAsync(array $args = [])
* @method \Aws\Result defineSuggester(array $args = [])
* @method \GuzzleHttp\Promise\Promise defineSuggesterAsync(array $args = [])
* @method \Aws\Result deleteAnalysisScheme(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAnalysisSchemeAsync(array $args = [])
* @method \Aws\Result deleteDomain(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDomainAsync(array $args = [])
* @method \Aws\Result deleteExpression(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteExpressionAsync(array $args = [])
* @method \Aws\Result deleteIndexField(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteIndexFieldAsync(array $args = [])
* @method \Aws\Result deleteSuggester(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteSuggesterAsync(array $args = [])
* @method \Aws\Result describeAnalysisSchemes(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAnalysisSchemesAsync(array $args = [])
* @method \Aws\Result describeAvailabilityOptions(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAvailabilityOptionsAsync(array $args = [])
* @method \Aws\Result describeDomains(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeDomainsAsync(array $args = [])
* @method \Aws\Result describeExpressions(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeExpressionsAsync(array $args = [])
* @method \Aws\Result describeIndexFields(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeIndexFieldsAsync(array $args = [])
* @method \Aws\Result describeScalingParameters(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeScalingParametersAsync(array $args = [])
* @method \Aws\Result describeServiceAccessPolicies(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeServiceAccessPoliciesAsync(array $args = [])
* @method \Aws\Result describeSuggesters(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeSuggestersAsync(array $args = [])
* @method \Aws\Result indexDocuments(array $args = [])
* @method \GuzzleHttp\Promise\Promise indexDocumentsAsync(array $args = [])
* @method \Aws\Result listDomainNames(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDomainNamesAsync(array $args = [])
* @method \Aws\Result updateAvailabilityOptions(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateAvailabilityOptionsAsync(array $args = [])
* @method \Aws\Result updateScalingParameters(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateScalingParametersAsync(array $args = [])
* @method \Aws\Result updateServiceAccessPolicies(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateServiceAccessPoliciesAsync(array $args = [])
*/
class CloudSearchClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CloudSearch\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the Amazon CloudSearch service.
*/
class CloudSearchException extends AwsException {}

View File

@@ -0,0 +1,84 @@
<?php
namespace Aws\CloudSearchDomain;
use Aws\AwsClient;
use Aws\CommandInterface;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Psr7;
/**
* This client is used to search and upload documents to an **Amazon CloudSearch** Domain.
*
* @method \Aws\Result search(array $args = [])
* @method \GuzzleHttp\Promise\Promise searchAsync(array $args = [])
* @method \Aws\Result suggest(array $args = [])
* @method \GuzzleHttp\Promise\Promise suggestAsync(array $args = [])
* @method \Aws\Result uploadDocuments(array $args = [])
* @method \GuzzleHttp\Promise\Promise uploadDocumentsAsync(array $args = [])
*/
class CloudSearchDomainClient extends AwsClient
{
public function __construct(array $args)
{
parent::__construct($args);
$list = $this->getHandlerList();
$list->appendBuild($this->searchByPost(), 'cloudsearchdomain.search_by_POST');
}
public static function getArguments()
{
$args = parent::getArguments();
$args['endpoint']['required'] = true;
$args['region']['default'] = function (array $args) {
// Determine the region from the provided endpoint.
// (e.g. http://search-blah.{region}.cloudsearch.amazonaws.com)
return explode('.', new Uri($args['endpoint']))[1];
};
return $args;
}
/**
* Use POST for search command
*
* Useful when query string is too long
*/
private function searchByPost()
{
return static function (callable $handler) {
return function (
CommandInterface $c,
RequestInterface $r = null
) use ($handler) {
if ($c->getName() !== 'Search') {
return $handler($c, $r);
}
return $handler($c, self::convertGetToPost($r));
};
};
}
/**
* Converts default GET request to a POST request
*
* Avoiding length restriction in query
*
* @param RequestInterface $r GET request to be converted
* @return RequestInterface $req converted POST request
*/
public static function convertGetToPost(RequestInterface $r)
{
if ($r->getMethod() === 'POST') {
return $r;
}
$query = $r->getUri()->getQuery();
$req = $r->withMethod('POST')
->withBody(Psr7\stream_for($query))
->withHeader('Content-Length', strlen($query))
->withHeader('Content-Type', 'application/x-www-form-urlencoded')
->withUri($r->getUri()->withQuery(''));
return $req;
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CloudSearchDomain\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with an Amazon CloudSearch Domain.
*/
class CloudSearchDomainException extends AwsException {}

View File

@@ -0,0 +1,34 @@
<?php
namespace Aws\CloudTrail;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS CloudTrail** service.
*
* @method \Aws\Result addTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise addTagsAsync(array $args = [])
* @method \Aws\Result createTrail(array $args = [])
* @method \GuzzleHttp\Promise\Promise createTrailAsync(array $args = [])
* @method \Aws\Result deleteTrail(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteTrailAsync(array $args = [])
* @method \Aws\Result describeTrails(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeTrailsAsync(array $args = [])
* @method \Aws\Result getTrailStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise getTrailStatusAsync(array $args = [])
* @method \Aws\Result listPublicKeys(array $args = [])
* @method \GuzzleHttp\Promise\Promise listPublicKeysAsync(array $args = [])
* @method \Aws\Result listTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTagsAsync(array $args = [])
* @method \Aws\Result lookupEvents(array $args = [])
* @method \GuzzleHttp\Promise\Promise lookupEventsAsync(array $args = [])
* @method \Aws\Result removeTags(array $args = [])
* @method \GuzzleHttp\Promise\Promise removeTagsAsync(array $args = [])
* @method \Aws\Result startLogging(array $args = [])
* @method \GuzzleHttp\Promise\Promise startLoggingAsync(array $args = [])
* @method \Aws\Result stopLogging(array $args = [])
* @method \GuzzleHttp\Promise\Promise stopLoggingAsync(array $args = [])
* @method \Aws\Result updateTrail(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateTrailAsync(array $args = [])
*/
class CloudTrailClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CloudTrail\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the AWS CloudTrail service.
*/
class CloudTrailException extends AwsException {}

View File

@@ -0,0 +1,324 @@
<?php
namespace Aws\CloudTrail;
use Aws\S3\S3Client;
use Aws\CloudTrail\Exception\CloudTrailException;
/**
* The `Aws\CloudTrail\LogFileIterator` provides an easy way to iterate over
* log file generated by AWS CloudTrail.
*
* CloudTrail log files contain data about your AWS API calls and are stored in
* Amazon S3 at a predictable path based on a bucket name, a key prefix, an
* account ID, a region, and date information. This class allows you to specify
* options, including a date range, and emits each log file that match the
* provided options.
*
* Yields an array containing the Amazon S3 bucket and key of the log file.
*/
class LogFileIterator extends \IteratorIterator
{
// For internal use
const DEFAULT_TRAIL_NAME = 'Default';
const PREFIX_TEMPLATE = 'prefix/AWSLogs/account/CloudTrail/region/date/';
const PREFIX_WILDCARD = '*';
// Option names used internally or externally
const TRAIL_NAME = 'trail_name';
const KEY_PREFIX = 'key_prefix';
const START_DATE = 'start_date';
const END_DATE = 'end_date';
const ACCOUNT_ID = 'account_id';
const LOG_REGION = 'log_region';
/** @var S3Client S3 client used to perform ListObjects operations */
private $s3Client;
/** @var string S3 bucket that contains the log files */
private $s3BucketName;
/**
* Constructs a LogRecordIterator. This factory method is used if the name
* of the S3 bucket containing your logs is not known. This factory method
* uses a CloudTrail client and the trail name (or "Default") to find the
* information about the trail necessary for constructing the
* LogRecordIterator.
*
* @param S3Client $s3Client
* @param CloudTrailClient $cloudTrailClient
* @param array $options
*
* @return LogRecordIterator
* @throws \InvalidArgumentException
* @see LogRecordIterator::__contruct
*/
public static function forTrail(
S3Client $s3Client,
CloudTrailClient $cloudTrailClient,
array $options = []
) {
$trailName = isset($options[self::TRAIL_NAME])
? $options[self::TRAIL_NAME]
: self::DEFAULT_TRAIL_NAME;
$s3BucketName = null;
// Use the CloudTrail client to get information about the trail,
// including the bucket name.
try {
$result = $cloudTrailClient->describeTrails([
'trailNameList' => [$trailName]
]);
$s3BucketName = $result->search('trailList[0].S3BucketName');
$options[self::KEY_PREFIX] = $result->search(
'trailList[0].S3KeyPrefix'
);
} catch (CloudTrailException $e) {
// There was an error describing the trail
}
// If the bucket name is still unknown, then throw an exception
if (!$s3BucketName) {
$prev = isset($e) ? $e : null;
throw new \InvalidArgumentException('The bucket name could not '
. 'be determined from the trail.', 0, $prev);
}
return new self($s3Client, $s3BucketName, $options);
}
/**
* Constructs a LogFileIterator using the specified options:
*
* - trail_name: The name of the trail that is generating our logs. If
* none is provided, then "Default" will be used, since that is the name
* of the trail created in the AWS Management Console.
* - key_prefix: The S3 key prefix of your log files. This value will be
* overwritten when using the `fromTrail()` method. However, if you are
* using the constructor, then this value will be used.
* - start_date: The timestamp of the beginning of date range of the log
* records you want to read. You can pass this in as a `DateTime` object,
* integer (unix timestamp), or a string compatible with `strtotime()`.
* - end_date: The timestamp of the end of date range of the log records
* you want to read. You can pass this in as a `DateTime` object, integer
* (unix timestamp), or a string compatible with `strtotime()`.
* - account_id: This is your AWS account ID, which is the 12-digit number
* found on the *Account Identifiers* section of the *AWS Security
* Credentials* page. See https://console.aws.amazon.com/iam/home?#security_credential
* - log_region: Region of the services of the log records you want to read.
*
* @param S3Client $s3Client
* @param string $s3BucketName
* @param array $options
*/
public function __construct(
S3Client $s3Client,
$s3BucketName,
array $options = []
) {
$this->s3Client = $s3Client;
$this->s3BucketName = $s3BucketName;
parent::__construct($this->buildListObjectsIterator($options));
}
/**
* An override of the typical current behavior of \IteratorIterator to
* format the output such that the bucket and key are returned in an array
*
* @return array|bool
*/
public function current()
{
if ($object = parent::current()) {
return [
'Bucket' => $this->s3BucketName,
'Key' => $object['Key']
];
}
return false;
}
/**
* Constructs an S3 ListObjects iterator, optionally decorated with
* FilterIterators, based on the provided options.
*
* @param array $options
*
* @return \Iterator
*/
private function buildListObjectsIterator(array $options)
{
// Extract and normalize the date values from the options
$startDate = isset($options[self::START_DATE])
? $this->normalizeDateValue($options[self::START_DATE])
: null;
$endDate = isset($options[self::END_DATE])
? $this->normalizeDateValue($options[self::END_DATE])
: null;
// Determine the parts of the key prefix of the log files being read
$parts = [
'prefix' => isset($options[self::KEY_PREFIX])
? $options[self::KEY_PREFIX]
: null,
'account' => isset($options[self::ACCOUNT_ID])
? $options[self::ACCOUNT_ID]
: self::PREFIX_WILDCARD,
'region' => isset($options[self::LOG_REGION])
? $options[self::LOG_REGION]
: self::PREFIX_WILDCARD,
'date' => $this->determineDateForPrefix($startDate, $endDate),
];
// Determine the longest key prefix that can be used to retrieve all
// of the relevant log files.
$candidatePrefix = ltrim(strtr(self::PREFIX_TEMPLATE, $parts), '/');
$logKeyPrefix = $candidatePrefix;
$index = strpos($candidatePrefix, self::PREFIX_WILDCARD);
if ($index !== false) {
$logKeyPrefix = substr($candidatePrefix, 0, $index);
}
// Create an iterator that will emit all of the objects matching the
// key prefix.
$objectsIterator = $this->s3Client->getIterator('ListObjects', [
'Bucket' => $this->s3BucketName,
'Prefix' => $logKeyPrefix,
]);
// Apply regex and/or date filters to the objects iterator to emit only
// log files matching the options.
$objectsIterator = $this->applyRegexFilter(
$objectsIterator,
$logKeyPrefix,
$candidatePrefix
);
$objectsIterator = $this->applyDateFilter(
$objectsIterator,
$startDate,
$endDate
);
return $objectsIterator;
}
/**
* Normalizes a date value to a unix timestamp
*
* @param string|\DateTime|int $date
*
* @return int
* @throws \InvalidArgumentException if the value cannot be converted to
* a timestamp
*/
private function normalizeDateValue($date)
{
if (is_string($date)) {
$date = strtotime($date);
} elseif ($date instanceof \DateTime) {
$date = $date->format('U');
} elseif (!is_int($date)) {
throw new \InvalidArgumentException('Date values must be a '
. 'string, an int, or a DateTime object.');
}
return $date;
}
/**
* Uses the provided date values to determine the date portion of the prefix
*/
private function determineDateForPrefix($startDate, $endDate)
{
// The default date value should look like "*/*/*" after joining
$dateParts = array_fill_keys(['Y', 'm', 'd'], self::PREFIX_WILDCARD);
// Narrow down the date by replacing the WILDCARDs with values if they
// are the same for the start and end date.
if ($startDate && $endDate) {
foreach ($dateParts as $key => &$value) {
$candidateValue = date($key, $startDate);
if ($candidateValue === date($key, $endDate)) {
$value = $candidateValue;
} else {
break;
}
}
}
return join('/', $dateParts);
}
/**
* Applies a regex iterator filter that limits the ListObjects result set
* based on the provided options.
*
* @param \Iterator $objectsIterator
* @param string $logKeyPrefix
* @param string $candidatePrefix
*
* @return \Iterator
*/
private function applyRegexFilter(
$objectsIterator,
$logKeyPrefix,
$candidatePrefix
) {
// If the prefix and candidate prefix are not the same, then there were
// WILDCARDs.
if ($logKeyPrefix !== $candidatePrefix) {
// Turn the candidate prefix into a regex by trimming and
// converting WILDCARDs to regex notation.
$regex = rtrim($candidatePrefix, '/' . self::PREFIX_WILDCARD) . '/';
$regex = strtr($regex, [self::PREFIX_WILDCARD => '[^/]+']);
// After trimming WILDCARDs or the end, if the regex is the same as
// the prefix, then no regex is needed.
if ($logKeyPrefix !== $regex) {
// Apply a regex filter iterator to remove files that don't
// match the provided options.
$objectsIterator = new \CallbackFilterIterator(
$objectsIterator,
function ($object) use ($regex) {
return preg_match("#{$regex}#", $object['Key']);
}
);
}
}
return $objectsIterator;
}
/**
* Applies an iterator filter to restrict the ListObjects result set to the
* specified date range.
*
* @param \Iterator $objectsIterator
* @param int $startDate
* @param int $endDate
*
* @return \Iterator
*/
private function applyDateFilter($objectsIterator, $startDate, $endDate)
{
// If either a start or end date was provided, filter out dates that
// don't match the date range.
if ($startDate || $endDate) {
$fn = function ($object) use ($startDate, $endDate) {
if (!preg_match('/[0-9]{8}T[0-9]{4}Z/', $object['Key'], $m)) {
return false;
}
$date = strtotime($m[0]);
return (!$startDate || $date >= $startDate)
&& (!$endDate || $date <= $endDate);
};
$objectsIterator = new \CallbackFilterIterator($objectsIterator, $fn);
}
return $objectsIterator;
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Aws\CloudTrail;
use Aws\S3\S3Client;
/**
* This class provides an easy way to read log files generated by AWS
* CloudTrail.
*
* CloudTrail log files contain data about your AWS API calls and are stored in
* Amazon S3. The log files are gzipped and contain structured data in JSON
* format. This class will automatically ungzip and decode the data, and return
* the data as a array of log records
*/
class LogFileReader
{
/** @var S3Client S3 client used to perform GetObject operations */
private $s3Client;
/**
* @param S3Client $s3Client S3 client used to retrieve objects
*/
public function __construct(S3Client $s3Client)
{
$this->s3Client = $s3Client;
}
/**
* Downloads, unzips, and reads a CloudTrail log file from Amazon S3
*
* @param string $s3BucketName The bucket name of the log file in Amazon S3
* @param string $logFileKey The key of the log file in Amazon S3
*
* @return array
*/
public function read($s3BucketName, $logFileKey)
{
// Create a command for getting the log file object
$command = $this->s3Client->getCommand('GetObject', [
'Bucket' => (string) $s3BucketName,
'Key' => (string) $logFileKey,
'ResponseContentEncoding' => 'x-gzip'
]);
// Make sure gzip encoding header is sent and accepted in order to
// inflate the response data.
$command['@http']['headers']['Accept-Encoding'] = 'gzip';
// Get the JSON response data and extract the log records
$result = $this->s3Client->execute($command);
$logData = json_decode($result['Body'], true);
return isset($logData['Records']) ? $logData['Records'] : [];
}
}

View File

@@ -0,0 +1,187 @@
<?php
namespace Aws\CloudTrail;
use Aws\S3\S3Client;
/**
* The `Aws\CloudTrail\LogRecordIterator` provides an easy way to iterate over
* log records from log files generated by AWS CloudTrail.
*
* CloudTrail log files contain data about your AWS API calls and are stored in
* Amazon S3 at a predictable path based on a bucket name, a key prefix, an
* account ID, a region, and date information. The files are gzipped and
* contain structured data in JSON format. This class allows you to specify
* options via its factory methods, including a date range, and emits each log
* record from any log files that match the provided options.
*
* A log record containing data about an AWS API call is yielded for each
* iteration on this object.
*/
class LogRecordIterator implements \OuterIterator
{
/** @var LogFileReader */
private $logFileReader;
/** @var \Iterator */
private $logFileIterator;
/** @var array */
private $records;
/** @var int */
private $recordIndex;
/**
* @param S3Client $s3Client
* @param CloudTrailClient $cloudTrailClient
* @param array $options
*
* @return LogRecordIterator
*/
public static function forTrail(
S3Client $s3Client,
CloudTrailClient $cloudTrailClient,
array $options = []
) {
$logFileIterator = LogFileIterator::forTrail(
$s3Client,
$cloudTrailClient,
$options
);
return new self(new LogFileReader($s3Client), $logFileIterator);
}
/**
* @param S3Client $s3Client
* @param string $s3BucketName
* @param array $options
*
* @return LogRecordIterator
*/
public static function forBucket(
S3Client $s3Client,
$s3BucketName,
array $options = []
) {
$logFileReader = new LogFileReader($s3Client);
$iter = new LogFileIterator($s3Client, $s3BucketName, $options);
return new self($logFileReader, $iter);
}
/**
* @param S3Client $s3Client
* @param string $s3BucketName
* @param string $s3ObjectKey
*
* @return LogRecordIterator
*/
public static function forFile(
S3Client $s3Client,
$s3BucketName,
$s3ObjectKey
) {
$logFileReader = new LogFileReader($s3Client);
$logFileIterator = new \ArrayIterator([[
'Bucket' => $s3BucketName,
'Key' => $s3ObjectKey,
]]);
return new self($logFileReader, $logFileIterator);
}
/**
* @param LogFileReader $logFileReader
* @param \Iterator $logFileIterator
*/
public function __construct(
LogFileReader $logFileReader,
\Iterator $logFileIterator
) {
$this->logFileReader = $logFileReader;
$this->logFileIterator = $logFileIterator;
$this->records = array();
$this->recordIndex = 0;
}
/**
* Returns the current log record as an array.
*
* @return array|false
*/
public function current()
{
return $this->valid() ? $this->records[$this->recordIndex] : false;
}
public function next()
{
$this->recordIndex++;
// If all the records have been exhausted, get more records from the
// next log file.
while (!$this->valid()) {
$this->logFileIterator->next();
$success = $this->loadRecordsFromCurrentLogFile();
if (!$success) {
// The objects iterator is exhausted as well, so stop trying
break;
}
}
}
public function key()
{
if ($logFile = $this->logFileIterator->current()) {
return $logFile['Key'] . '.' . $this->recordIndex;
}
return null;
}
public function valid()
{
return isset($this->records[$this->recordIndex]);
}
public function rewind()
{
$this->logFileIterator->rewind();
$this->loadRecordsFromCurrentLogFile();
}
public function getInnerIterator()
{
return $this->logFileIterator;
}
/**
* Examines the current file in the `logFileIterator` and attempts to read
* it and load log records from it using the `logFileReader`. This method
* expects that items pulled from the iterator will take the form:
*
* [
* 'Bucket' => '...',
* 'Key' => '...',
* ]
*
* @return bool Returns `true` if records were loaded and `false` if no
* records were found
*/
private function loadRecordsFromCurrentLogFile()
{
$this->recordIndex = 0;
$this->records = array();
$logFile = $this->logFileIterator->current();
if ($logFile && isset($logFile['Bucket']) && isset($logFile['Key'])) {
$this->records = $this->logFileReader->read(
$logFile['Bucket'],
$logFile['Key']
);
}
return (bool) $logFile;
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Aws\CloudWatch;
use Aws\AwsClient;
/**
* This client is used to interact with the **Amazon CloudWatch** service.
*
* @method \Aws\Result deleteAlarms(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteAlarmsAsync(array $args = [])
* @method \Aws\Result describeAlarmHistory(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAlarmHistoryAsync(array $args = [])
* @method \Aws\Result describeAlarms(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAlarmsAsync(array $args = [])
* @method \Aws\Result describeAlarmsForMetric(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeAlarmsForMetricAsync(array $args = [])
* @method \Aws\Result disableAlarmActions(array $args = [])
* @method \GuzzleHttp\Promise\Promise disableAlarmActionsAsync(array $args = [])
* @method \Aws\Result enableAlarmActions(array $args = [])
* @method \GuzzleHttp\Promise\Promise enableAlarmActionsAsync(array $args = [])
* @method \Aws\Result getMetricStatistics(array $args = [])
* @method \GuzzleHttp\Promise\Promise getMetricStatisticsAsync(array $args = [])
* @method \Aws\Result listMetrics(array $args = [])
* @method \GuzzleHttp\Promise\Promise listMetricsAsync(array $args = [])
* @method \Aws\Result putMetricAlarm(array $args = [])
* @method \GuzzleHttp\Promise\Promise putMetricAlarmAsync(array $args = [])
* @method \Aws\Result putMetricData(array $args = [])
* @method \GuzzleHttp\Promise\Promise putMetricDataAsync(array $args = [])
* @method \Aws\Result setAlarmState(array $args = [])
* @method \GuzzleHttp\Promise\Promise setAlarmStateAsync(array $args = [])
*/
class CloudWatchClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CloudWatch\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the Amazon CloudWatch service.
*/
class CloudWatchException extends AwsException {}

View File

@@ -0,0 +1,34 @@
<?php
namespace Aws\CloudWatchEvents;
use Aws\AwsClient;
/**
* This client is used to interact with the **Amazon CloudWatch Events** service.
*
* @method \Aws\Result deleteRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteRuleAsync(array $args = [])
* @method \Aws\Result describeRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeRuleAsync(array $args = [])
* @method \Aws\Result disableRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise disableRuleAsync(array $args = [])
* @method \Aws\Result enableRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise enableRuleAsync(array $args = [])
* @method \Aws\Result listRuleNamesByTarget(array $args = [])
* @method \GuzzleHttp\Promise\Promise listRuleNamesByTargetAsync(array $args = [])
* @method \Aws\Result listRules(array $args = [])
* @method \GuzzleHttp\Promise\Promise listRulesAsync(array $args = [])
* @method \Aws\Result listTargetsByRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise listTargetsByRuleAsync(array $args = [])
* @method \Aws\Result putEvents(array $args = [])
* @method \GuzzleHttp\Promise\Promise putEventsAsync(array $args = [])
* @method \Aws\Result putRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise putRuleAsync(array $args = [])
* @method \Aws\Result putTargets(array $args = [])
* @method \GuzzleHttp\Promise\Promise putTargetsAsync(array $args = [])
* @method \Aws\Result removeTargets(array $args = [])
* @method \GuzzleHttp\Promise\Promise removeTargetsAsync(array $args = [])
* @method \Aws\Result testEventPattern(array $args = [])
* @method \GuzzleHttp\Promise\Promise testEventPatternAsync(array $args = [])
*/
class CloudWatchEventsClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CloudWatchEvents\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **Amazon CloudWatch Events** service.
*/
class CloudWatchEventsException extends AwsException {}

View File

@@ -0,0 +1,60 @@
<?php
namespace Aws\CloudWatchLogs;
use Aws\AwsClient;
/**
* This client is used to interact with the **Amazon CloudWatch Logs** service.
*
* @method \Aws\Result cancelExportTask(array $args = [])
* @method \GuzzleHttp\Promise\Promise cancelExportTaskAsync(array $args = [])
* @method \Aws\Result createExportTask(array $args = [])
* @method \GuzzleHttp\Promise\Promise createExportTaskAsync(array $args = [])
* @method \Aws\Result createLogGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise createLogGroupAsync(array $args = [])
* @method \Aws\Result createLogStream(array $args = [])
* @method \GuzzleHttp\Promise\Promise createLogStreamAsync(array $args = [])
* @method \Aws\Result deleteDestination(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDestinationAsync(array $args = [])
* @method \Aws\Result deleteLogGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteLogGroupAsync(array $args = [])
* @method \Aws\Result deleteLogStream(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteLogStreamAsync(array $args = [])
* @method \Aws\Result deleteMetricFilter(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteMetricFilterAsync(array $args = [])
* @method \Aws\Result deleteRetentionPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteRetentionPolicyAsync(array $args = [])
* @method \Aws\Result deleteSubscriptionFilter(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteSubscriptionFilterAsync(array $args = [])
* @method \Aws\Result describeDestinations(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeDestinationsAsync(array $args = [])
* @method \Aws\Result describeExportTasks(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeExportTasksAsync(array $args = [])
* @method \Aws\Result describeLogGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeLogGroupsAsync(array $args = [])
* @method \Aws\Result describeLogStreams(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeLogStreamsAsync(array $args = [])
* @method \Aws\Result describeMetricFilters(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeMetricFiltersAsync(array $args = [])
* @method \Aws\Result describeSubscriptionFilters(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeSubscriptionFiltersAsync(array $args = [])
* @method \Aws\Result filterLogEvents(array $args = [])
* @method \GuzzleHttp\Promise\Promise filterLogEventsAsync(array $args = [])
* @method \Aws\Result getLogEvents(array $args = [])
* @method \GuzzleHttp\Promise\Promise getLogEventsAsync(array $args = [])
* @method \Aws\Result putDestination(array $args = [])
* @method \GuzzleHttp\Promise\Promise putDestinationAsync(array $args = [])
* @method \Aws\Result putDestinationPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putDestinationPolicyAsync(array $args = [])
* @method \Aws\Result putLogEvents(array $args = [])
* @method \GuzzleHttp\Promise\Promise putLogEventsAsync(array $args = [])
* @method \Aws\Result putMetricFilter(array $args = [])
* @method \GuzzleHttp\Promise\Promise putMetricFilterAsync(array $args = [])
* @method \Aws\Result putRetentionPolicy(array $args = [])
* @method \GuzzleHttp\Promise\Promise putRetentionPolicyAsync(array $args = [])
* @method \Aws\Result putSubscriptionFilter(array $args = [])
* @method \GuzzleHttp\Promise\Promise putSubscriptionFilterAsync(array $args = [])
* @method \Aws\Result testMetricFilter(array $args = [])
* @method \GuzzleHttp\Promise\Promise testMetricFilterAsync(array $args = [])
*/
class CloudWatchLogsClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CloudWatchLogs\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the Amazon CloudWatch Logs service.
*/
class CloudWatchLogsException extends AwsException {}

View File

@@ -0,0 +1,40 @@
<?php
namespace Aws\CodeCommit;
use Aws\AwsClient;
/**
* This client is used to interact with the **AWS CodeCommit** service.
*
* @method \Aws\Result batchGetRepositories(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetRepositoriesAsync(array $args = [])
* @method \Aws\Result createBranch(array $args = [])
* @method \GuzzleHttp\Promise\Promise createBranchAsync(array $args = [])
* @method \Aws\Result createRepository(array $args = [])
* @method \GuzzleHttp\Promise\Promise createRepositoryAsync(array $args = [])
* @method \Aws\Result deleteRepository(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteRepositoryAsync(array $args = [])
* @method \Aws\Result getBranch(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBranchAsync(array $args = [])
* @method \Aws\Result getCommit(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCommitAsync(array $args = [])
* @method \Aws\Result getRepository(array $args = [])
* @method \GuzzleHttp\Promise\Promise getRepositoryAsync(array $args = [])
* @method \Aws\Result getRepositoryTriggers(array $args = [])
* @method \GuzzleHttp\Promise\Promise getRepositoryTriggersAsync(array $args = [])
* @method \Aws\Result listBranches(array $args = [])
* @method \GuzzleHttp\Promise\Promise listBranchesAsync(array $args = [])
* @method \Aws\Result listRepositories(array $args = [])
* @method \GuzzleHttp\Promise\Promise listRepositoriesAsync(array $args = [])
* @method \Aws\Result putRepositoryTriggers(array $args = [])
* @method \GuzzleHttp\Promise\Promise putRepositoryTriggersAsync(array $args = [])
* @method \Aws\Result testRepositoryTriggers(array $args = [])
* @method \GuzzleHttp\Promise\Promise testRepositoryTriggersAsync(array $args = [])
* @method \Aws\Result updateDefaultBranch(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateDefaultBranchAsync(array $args = [])
* @method \Aws\Result updateRepositoryDescription(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateRepositoryDescriptionAsync(array $args = [])
* @method \Aws\Result updateRepositoryName(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateRepositoryNameAsync(array $args = [])
*/
class CodeCommitClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CodeCommit\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **AWS CodeCommit** service.
*/
class CodeCommitException extends AwsException {}

View File

@@ -0,0 +1,80 @@
<?php
namespace Aws\CodeDeploy;
use Aws\AwsClient;
/**
* This client is used to interact with AWS CodeDeploy
*
* @method \Aws\Result addTagsToOnPremisesInstances(array $args = [])
* @method \GuzzleHttp\Promise\Promise addTagsToOnPremisesInstancesAsync(array $args = [])
* @method \Aws\Result batchGetApplicationRevisions(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetApplicationRevisionsAsync(array $args = [])
* @method \Aws\Result batchGetApplications(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetApplicationsAsync(array $args = [])
* @method \Aws\Result batchGetDeploymentGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetDeploymentGroupsAsync(array $args = [])
* @method \Aws\Result batchGetDeploymentInstances(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetDeploymentInstancesAsync(array $args = [])
* @method \Aws\Result batchGetDeployments(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetDeploymentsAsync(array $args = [])
* @method \Aws\Result batchGetOnPremisesInstances(array $args = [])
* @method \GuzzleHttp\Promise\Promise batchGetOnPremisesInstancesAsync(array $args = [])
* @method \Aws\Result createApplication(array $args = [])
* @method \GuzzleHttp\Promise\Promise createApplicationAsync(array $args = [])
* @method \Aws\Result createDeployment(array $args = [])
* @method \GuzzleHttp\Promise\Promise createDeploymentAsync(array $args = [])
* @method \Aws\Result createDeploymentConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise createDeploymentConfigAsync(array $args = [])
* @method \Aws\Result createDeploymentGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise createDeploymentGroupAsync(array $args = [])
* @method \Aws\Result deleteApplication(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteApplicationAsync(array $args = [])
* @method \Aws\Result deleteDeploymentConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDeploymentConfigAsync(array $args = [])
* @method \Aws\Result deleteDeploymentGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDeploymentGroupAsync(array $args = [])
* @method \Aws\Result deregisterOnPremisesInstance(array $args = [])
* @method \GuzzleHttp\Promise\Promise deregisterOnPremisesInstanceAsync(array $args = [])
* @method \Aws\Result getApplication(array $args = [])
* @method \GuzzleHttp\Promise\Promise getApplicationAsync(array $args = [])
* @method \Aws\Result getApplicationRevision(array $args = [])
* @method \GuzzleHttp\Promise\Promise getApplicationRevisionAsync(array $args = [])
* @method \Aws\Result getDeployment(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDeploymentAsync(array $args = [])
* @method \Aws\Result getDeploymentConfig(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDeploymentConfigAsync(array $args = [])
* @method \Aws\Result getDeploymentGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDeploymentGroupAsync(array $args = [])
* @method \Aws\Result getDeploymentInstance(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDeploymentInstanceAsync(array $args = [])
* @method \Aws\Result getOnPremisesInstance(array $args = [])
* @method \GuzzleHttp\Promise\Promise getOnPremisesInstanceAsync(array $args = [])
* @method \Aws\Result listApplicationRevisions(array $args = [])
* @method \GuzzleHttp\Promise\Promise listApplicationRevisionsAsync(array $args = [])
* @method \Aws\Result listApplications(array $args = [])
* @method \GuzzleHttp\Promise\Promise listApplicationsAsync(array $args = [])
* @method \Aws\Result listDeploymentConfigs(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDeploymentConfigsAsync(array $args = [])
* @method \Aws\Result listDeploymentGroups(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDeploymentGroupsAsync(array $args = [])
* @method \Aws\Result listDeploymentInstances(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDeploymentInstancesAsync(array $args = [])
* @method \Aws\Result listDeployments(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDeploymentsAsync(array $args = [])
* @method \Aws\Result listOnPremisesInstances(array $args = [])
* @method \GuzzleHttp\Promise\Promise listOnPremisesInstancesAsync(array $args = [])
* @method \Aws\Result registerApplicationRevision(array $args = [])
* @method \GuzzleHttp\Promise\Promise registerApplicationRevisionAsync(array $args = [])
* @method \Aws\Result registerOnPremisesInstance(array $args = [])
* @method \GuzzleHttp\Promise\Promise registerOnPremisesInstanceAsync(array $args = [])
* @method \Aws\Result removeTagsFromOnPremisesInstances(array $args = [])
* @method \GuzzleHttp\Promise\Promise removeTagsFromOnPremisesInstancesAsync(array $args = [])
* @method \Aws\Result stopDeployment(array $args = [])
* @method \GuzzleHttp\Promise\Promise stopDeploymentAsync(array $args = [])
* @method \Aws\Result updateApplication(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateApplicationAsync(array $args = [])
* @method \Aws\Result updateDeploymentGroup(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateDeploymentGroupAsync(array $args = [])
*/
class CodeDeployClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CodeDeploy\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with AWS CodeDeploy.
*/
class CodeDeployException extends AwsException {}

View File

@@ -0,0 +1,62 @@
<?php
namespace Aws\CodePipeline;
use Aws\AwsClient;
/**
* This client is used to interact with the **Amazon CodePipeline** service.
*
* @method \Aws\Result acknowledgeJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise acknowledgeJobAsync(array $args = [])
* @method \Aws\Result acknowledgeThirdPartyJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise acknowledgeThirdPartyJobAsync(array $args = [])
* @method \Aws\Result createCustomActionType(array $args = [])
* @method \GuzzleHttp\Promise\Promise createCustomActionTypeAsync(array $args = [])
* @method \Aws\Result createPipeline(array $args = [])
* @method \GuzzleHttp\Promise\Promise createPipelineAsync(array $args = [])
* @method \Aws\Result deleteCustomActionType(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteCustomActionTypeAsync(array $args = [])
* @method \Aws\Result deletePipeline(array $args = [])
* @method \GuzzleHttp\Promise\Promise deletePipelineAsync(array $args = [])
* @method \Aws\Result disableStageTransition(array $args = [])
* @method \GuzzleHttp\Promise\Promise disableStageTransitionAsync(array $args = [])
* @method \Aws\Result enableStageTransition(array $args = [])
* @method \GuzzleHttp\Promise\Promise enableStageTransitionAsync(array $args = [])
* @method \Aws\Result getJobDetails(array $args = [])
* @method \GuzzleHttp\Promise\Promise getJobDetailsAsync(array $args = [])
* @method \Aws\Result getPipeline(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPipelineAsync(array $args = [])
* @method \Aws\Result getPipelineExecution(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPipelineExecutionAsync(array $args = [])
* @method \Aws\Result getPipelineState(array $args = [])
* @method \GuzzleHttp\Promise\Promise getPipelineStateAsync(array $args = [])
* @method \Aws\Result getThirdPartyJobDetails(array $args = [])
* @method \GuzzleHttp\Promise\Promise getThirdPartyJobDetailsAsync(array $args = [])
* @method \Aws\Result listActionTypes(array $args = [])
* @method \GuzzleHttp\Promise\Promise listActionTypesAsync(array $args = [])
* @method \Aws\Result listPipelines(array $args = [])
* @method \GuzzleHttp\Promise\Promise listPipelinesAsync(array $args = [])
* @method \Aws\Result pollForJobs(array $args = [])
* @method \GuzzleHttp\Promise\Promise pollForJobsAsync(array $args = [])
* @method \Aws\Result pollForThirdPartyJobs(array $args = [])
* @method \GuzzleHttp\Promise\Promise pollForThirdPartyJobsAsync(array $args = [])
* @method \Aws\Result putActionRevision(array $args = [])
* @method \GuzzleHttp\Promise\Promise putActionRevisionAsync(array $args = [])
* @method \Aws\Result putApprovalResult(array $args = [])
* @method \GuzzleHttp\Promise\Promise putApprovalResultAsync(array $args = [])
* @method \Aws\Result putJobFailureResult(array $args = [])
* @method \GuzzleHttp\Promise\Promise putJobFailureResultAsync(array $args = [])
* @method \Aws\Result putJobSuccessResult(array $args = [])
* @method \GuzzleHttp\Promise\Promise putJobSuccessResultAsync(array $args = [])
* @method \Aws\Result putThirdPartyJobFailureResult(array $args = [])
* @method \GuzzleHttp\Promise\Promise putThirdPartyJobFailureResultAsync(array $args = [])
* @method \Aws\Result putThirdPartyJobSuccessResult(array $args = [])
* @method \GuzzleHttp\Promise\Promise putThirdPartyJobSuccessResultAsync(array $args = [])
* @method \Aws\Result retryStageExecution(array $args = [])
* @method \GuzzleHttp\Promise\Promise retryStageExecutionAsync(array $args = [])
* @method \Aws\Result startPipelineExecution(array $args = [])
* @method \GuzzleHttp\Promise\Promise startPipelineExecutionAsync(array $args = [])
* @method \Aws\Result updatePipeline(array $args = [])
* @method \GuzzleHttp\Promise\Promise updatePipelineAsync(array $args = [])
*/
class CodePipelineClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CodePipeline\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the Amazon CodePipeline service.
*/
class CodePipelineException extends AwsException {}

View File

@@ -0,0 +1,46 @@
<?php
namespace Aws\CognitoIdentity;
use Aws\AwsClient;
/**
* This client is used to interact with the **Amazon Cognito Identity** service.
*
* @method \Aws\Result createIdentityPool(array $args = [])
* @method \GuzzleHttp\Promise\Promise createIdentityPoolAsync(array $args = [])
* @method \Aws\Result deleteIdentities(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteIdentitiesAsync(array $args = [])
* @method \Aws\Result deleteIdentityPool(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteIdentityPoolAsync(array $args = [])
* @method \Aws\Result describeIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeIdentityAsync(array $args = [])
* @method \Aws\Result describeIdentityPool(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeIdentityPoolAsync(array $args = [])
* @method \Aws\Result getCredentialsForIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCredentialsForIdentityAsync(array $args = [])
* @method \Aws\Result getId(array $args = [])
* @method \GuzzleHttp\Promise\Promise getIdAsync(array $args = [])
* @method \Aws\Result getIdentityPoolRoles(array $args = [])
* @method \GuzzleHttp\Promise\Promise getIdentityPoolRolesAsync(array $args = [])
* @method \Aws\Result getOpenIdToken(array $args = [])
* @method \GuzzleHttp\Promise\Promise getOpenIdTokenAsync(array $args = [])
* @method \Aws\Result getOpenIdTokenForDeveloperIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise getOpenIdTokenForDeveloperIdentityAsync(array $args = [])
* @method \Aws\Result listIdentities(array $args = [])
* @method \GuzzleHttp\Promise\Promise listIdentitiesAsync(array $args = [])
* @method \Aws\Result listIdentityPools(array $args = [])
* @method \GuzzleHttp\Promise\Promise listIdentityPoolsAsync(array $args = [])
* @method \Aws\Result lookupDeveloperIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise lookupDeveloperIdentityAsync(array $args = [])
* @method \Aws\Result mergeDeveloperIdentities(array $args = [])
* @method \GuzzleHttp\Promise\Promise mergeDeveloperIdentitiesAsync(array $args = [])
* @method \Aws\Result setIdentityPoolRoles(array $args = [])
* @method \GuzzleHttp\Promise\Promise setIdentityPoolRolesAsync(array $args = [])
* @method \Aws\Result unlinkDeveloperIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise unlinkDeveloperIdentityAsync(array $args = [])
* @method \Aws\Result unlinkIdentity(array $args = [])
* @method \GuzzleHttp\Promise\Promise unlinkIdentityAsync(array $args = [])
* @method \Aws\Result updateIdentityPool(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateIdentityPoolAsync(array $args = [])
*/
class CognitoIdentityClient extends AwsClient {}

View File

@@ -0,0 +1,61 @@
<?php
namespace Aws\CognitoIdentity;
use Aws\Credentials\Credentials;
use GuzzleHttp\Promise;
class CognitoIdentityProvider
{
/** @var CognitoIdentityClient */
private $client;
/** @var string */
private $identityPoolId;
/** @var string|null */
private $accountId;
/** @var array */
private $logins;
public function __construct(
$poolId,
array $clientOptions,
array $logins = [],
$accountId = null
) {
$this->identityPoolId = $poolId;
$this->logins = $logins;
$this->accountId = $accountId;
$this->client = new CognitoIdentityClient($clientOptions + [
'credentials' => false,
]);
}
public function __invoke()
{
return Promise\coroutine(function () {
$params = $this->logins ? ['Logins' => $this->logins] : [];
$getIdParams = $params + ['IdentityPoolId' => $this->identityPoolId];
if ($this->accountId) {
$getIdParams['AccountId'] = $this->accountId;
}
$id = (yield $this->client->getId($getIdParams));
$result = (yield $this->client->getCredentialsForIdentity([
'IdentityId' => $id['IdentityId'],
] + $params));
yield new Credentials(
$result['Credentials']['AccessKeyId'],
$result['Credentials']['SecretKey'],
$result['Credentials']['SessionToken'],
(int) $result['Credentials']['Expiration']->format('U')
);
});
}
public function updateLogin($key, $value)
{
$this->logins[$key] = $value;
return $this;
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CognitoIdentity\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the Amazon Cognito Identity Logs service.
*/
class CognitoIdentityException extends AwsException {}

View File

@@ -0,0 +1,120 @@
<?php
namespace Aws\CognitoIdentityProvider;
use Aws\AwsClient;
/**
* This client is used to interact with the **Amazon Cognito Identity Provider** service.
*
* @method \Aws\Result addCustomAttributes(array $args = [])
* @method \GuzzleHttp\Promise\Promise addCustomAttributesAsync(array $args = [])
* @method \Aws\Result adminConfirmSignUp(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminConfirmSignUpAsync(array $args = [])
* @method \Aws\Result adminDeleteUser(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminDeleteUserAsync(array $args = [])
* @method \Aws\Result adminDeleteUserAttributes(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminDeleteUserAttributesAsync(array $args = [])
* @method \Aws\Result adminDisableUser(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminDisableUserAsync(array $args = [])
* @method \Aws\Result adminEnableUser(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminEnableUserAsync(array $args = [])
* @method \Aws\Result adminForgetDevice(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminForgetDeviceAsync(array $args = [])
* @method \Aws\Result adminGetDevice(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminGetDeviceAsync(array $args = [])
* @method \Aws\Result adminGetUser(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminGetUserAsync(array $args = [])
* @method \Aws\Result adminInitiateAuth(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminInitiateAuthAsync(array $args = [])
* @method \Aws\Result adminListDevices(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminListDevicesAsync(array $args = [])
* @method \Aws\Result adminResetUserPassword(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminResetUserPasswordAsync(array $args = [])
* @method \Aws\Result adminRespondToAuthChallenge(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminRespondToAuthChallengeAsync(array $args = [])
* @method \Aws\Result adminSetUserSettings(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminSetUserSettingsAsync(array $args = [])
* @method \Aws\Result adminUpdateDeviceStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminUpdateDeviceStatusAsync(array $args = [])
* @method \Aws\Result adminUpdateUserAttributes(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminUpdateUserAttributesAsync(array $args = [])
* @method \Aws\Result adminUserGlobalSignOut(array $args = [])
* @method \GuzzleHttp\Promise\Promise adminUserGlobalSignOutAsync(array $args = [])
* @method \Aws\Result changePassword(array $args = [])
* @method \GuzzleHttp\Promise\Promise changePasswordAsync(array $args = [])
* @method \Aws\Result confirmDevice(array $args = [])
* @method \GuzzleHttp\Promise\Promise confirmDeviceAsync(array $args = [])
* @method \Aws\Result confirmForgotPassword(array $args = [])
* @method \GuzzleHttp\Promise\Promise confirmForgotPasswordAsync(array $args = [])
* @method \Aws\Result confirmSignUp(array $args = [])
* @method \GuzzleHttp\Promise\Promise confirmSignUpAsync(array $args = [])
* @method \Aws\Result createUserImportJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise createUserImportJobAsync(array $args = [])
* @method \Aws\Result createUserPool(array $args = [])
* @method \GuzzleHttp\Promise\Promise createUserPoolAsync(array $args = [])
* @method \Aws\Result createUserPoolClient(array $args = [])
* @method \GuzzleHttp\Promise\Promise createUserPoolClientAsync(array $args = [])
* @method \Aws\Result deleteUser(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteUserAsync(array $args = [])
* @method \Aws\Result deleteUserAttributes(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteUserAttributesAsync(array $args = [])
* @method \Aws\Result deleteUserPool(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteUserPoolAsync(array $args = [])
* @method \Aws\Result deleteUserPoolClient(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteUserPoolClientAsync(array $args = [])
* @method \Aws\Result describeUserImportJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeUserImportJobAsync(array $args = [])
* @method \Aws\Result describeUserPool(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeUserPoolAsync(array $args = [])
* @method \Aws\Result describeUserPoolClient(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeUserPoolClientAsync(array $args = [])
* @method \Aws\Result forgetDevice(array $args = [])
* @method \GuzzleHttp\Promise\Promise forgetDeviceAsync(array $args = [])
* @method \Aws\Result forgotPassword(array $args = [])
* @method \GuzzleHttp\Promise\Promise forgotPasswordAsync(array $args = [])
* @method \Aws\Result getCSVHeader(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCSVHeaderAsync(array $args = [])
* @method \Aws\Result getDevice(array $args = [])
* @method \GuzzleHttp\Promise\Promise getDeviceAsync(array $args = [])
* @method \Aws\Result getUser(array $args = [])
* @method \GuzzleHttp\Promise\Promise getUserAsync(array $args = [])
* @method \Aws\Result getUserAttributeVerificationCode(array $args = [])
* @method \GuzzleHttp\Promise\Promise getUserAttributeVerificationCodeAsync(array $args = [])
* @method \Aws\Result globalSignOut(array $args = [])
* @method \GuzzleHttp\Promise\Promise globalSignOutAsync(array $args = [])
* @method \Aws\Result initiateAuth(array $args = [])
* @method \GuzzleHttp\Promise\Promise initiateAuthAsync(array $args = [])
* @method \Aws\Result listDevices(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDevicesAsync(array $args = [])
* @method \Aws\Result listUserImportJobs(array $args = [])
* @method \GuzzleHttp\Promise\Promise listUserImportJobsAsync(array $args = [])
* @method \Aws\Result listUserPoolClients(array $args = [])
* @method \GuzzleHttp\Promise\Promise listUserPoolClientsAsync(array $args = [])
* @method \Aws\Result listUserPools(array $args = [])
* @method \GuzzleHttp\Promise\Promise listUserPoolsAsync(array $args = [])
* @method \Aws\Result listUsers(array $args = [])
* @method \GuzzleHttp\Promise\Promise listUsersAsync(array $args = [])
* @method \Aws\Result resendConfirmationCode(array $args = [])
* @method \GuzzleHttp\Promise\Promise resendConfirmationCodeAsync(array $args = [])
* @method \Aws\Result respondToAuthChallenge(array $args = [])
* @method \GuzzleHttp\Promise\Promise respondToAuthChallengeAsync(array $args = [])
* @method \Aws\Result setUserSettings(array $args = [])
* @method \GuzzleHttp\Promise\Promise setUserSettingsAsync(array $args = [])
* @method \Aws\Result signUp(array $args = [])
* @method \GuzzleHttp\Promise\Promise signUpAsync(array $args = [])
* @method \Aws\Result startUserImportJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise startUserImportJobAsync(array $args = [])
* @method \Aws\Result stopUserImportJob(array $args = [])
* @method \GuzzleHttp\Promise\Promise stopUserImportJobAsync(array $args = [])
* @method \Aws\Result updateDeviceStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateDeviceStatusAsync(array $args = [])
* @method \Aws\Result updateUserAttributes(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateUserAttributesAsync(array $args = [])
* @method \Aws\Result updateUserPool(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateUserPoolAsync(array $args = [])
* @method \Aws\Result updateUserPoolClient(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateUserPoolClientAsync(array $args = [])
* @method \Aws\Result verifyUserAttribute(array $args = [])
* @method \GuzzleHttp\Promise\Promise verifyUserAttributeAsync(array $args = [])
*/
class CognitoIdentityProviderClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CognitoIdentityProvider\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the **Amazon Cognito Identity Provider** service.
*/
class CognitoIdentityProviderException extends AwsException {}

View File

@@ -0,0 +1,44 @@
<?php
namespace Aws\CognitoSync;
use Aws\AwsClient;
/**
* This client is used to interact with the **Amazon Cognito Sync** service.
*
* @method \Aws\Result bulkPublish(array $args = [])
* @method \GuzzleHttp\Promise\Promise bulkPublishAsync(array $args = [])
* @method \Aws\Result deleteDataset(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDatasetAsync(array $args = [])
* @method \Aws\Result describeDataset(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeDatasetAsync(array $args = [])
* @method \Aws\Result describeIdentityPoolUsage(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeIdentityPoolUsageAsync(array $args = [])
* @method \Aws\Result describeIdentityUsage(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeIdentityUsageAsync(array $args = [])
* @method \Aws\Result getBulkPublishDetails(array $args = [])
* @method \GuzzleHttp\Promise\Promise getBulkPublishDetailsAsync(array $args = [])
* @method \Aws\Result getCognitoEvents(array $args = [])
* @method \GuzzleHttp\Promise\Promise getCognitoEventsAsync(array $args = [])
* @method \Aws\Result getIdentityPoolConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise getIdentityPoolConfigurationAsync(array $args = [])
* @method \Aws\Result listDatasets(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDatasetsAsync(array $args = [])
* @method \Aws\Result listIdentityPoolUsage(array $args = [])
* @method \GuzzleHttp\Promise\Promise listIdentityPoolUsageAsync(array $args = [])
* @method \Aws\Result listRecords(array $args = [])
* @method \GuzzleHttp\Promise\Promise listRecordsAsync(array $args = [])
* @method \Aws\Result registerDevice(array $args = [])
* @method \GuzzleHttp\Promise\Promise registerDeviceAsync(array $args = [])
* @method \Aws\Result setCognitoEvents(array $args = [])
* @method \GuzzleHttp\Promise\Promise setCognitoEventsAsync(array $args = [])
* @method \Aws\Result setIdentityPoolConfiguration(array $args = [])
* @method \GuzzleHttp\Promise\Promise setIdentityPoolConfigurationAsync(array $args = [])
* @method \Aws\Result subscribeToDataset(array $args = [])
* @method \GuzzleHttp\Promise\Promise subscribeToDatasetAsync(array $args = [])
* @method \Aws\Result unsubscribeFromDataset(array $args = [])
* @method \GuzzleHttp\Promise\Promise unsubscribeFromDatasetAsync(array $args = [])
* @method \Aws\Result updateRecords(array $args = [])
* @method \GuzzleHttp\Promise\Promise updateRecordsAsync(array $args = [])
*/
class CognitoSyncClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\CognitoSync\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the Amazon Cognito Sync service.
*/
class CognitoSyncException extends AwsException {}

62
vendor/aws/aws-sdk-php/src/Command.php vendored Normal file
View File

@@ -0,0 +1,62 @@
<?php
namespace Aws;
/**
* AWS command object.
*/
class Command implements CommandInterface
{
use HasDataTrait;
/** @var string */
private $name;
/** @var HandlerList */
private $handlerList;
/**
* Accepts an associative array of command options, including:
*
* - @http: (array) Associative array of transfer options.
*
* @param string $name Name of the command
* @param array $args Arguments to pass to the command
* @param HandlerList $list Handler list
*/
public function __construct($name, array $args = [], HandlerList $list = null)
{
$this->name = $name;
$this->data = $args;
$this->handlerList = $list ?: new HandlerList();
if (!isset($this->data['@http'])) {
$this->data['@http'] = [];
}
}
public function __clone()
{
$this->handlerList = clone $this->handlerList;
}
public function getName()
{
return $this->name;
}
public function hasParam($name)
{
return array_key_exists($name, $this->data);
}
public function getHandlerList()
{
return $this->handlerList;
}
/** @deprecated */
public function get($name)
{
return $this[$name];
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Aws;
/**
* A command object encapsulates the input parameters used to control the
* creation of a HTTP request and processing of a HTTP response.
*
* Using the toArray() method will return the input parameters of the command
* as an associative array.
*/
interface CommandInterface extends \ArrayAccess, \Countable, \IteratorAggregate
{
/**
* Converts the command parameters to an array
*
* @return array
*/
public function toArray();
/**
* Get the name of the command
*
* @return string
*/
public function getName();
/**
* Check if the command has a parameter by name.
*
* @param string $name Name of the parameter to check
*
* @return bool
*/
public function hasParam($name);
/**
* Get the handler list used to transfer the command.
*
* @return HandlerList
*/
public function getHandlerList();
}

View File

@@ -0,0 +1,144 @@
<?php
namespace Aws;
use GuzzleHttp\Promise\PromisorInterface;
use GuzzleHttp\Promise\EachPromise;
/**
* Sends and iterator of commands concurrently using a capped pool size.
*
* The pool will read command objects from an iterator until it is cancelled or
* until the iterator is consumed.
*/
class CommandPool implements PromisorInterface
{
/** @var EachPromise */
private $each;
/**
* The CommandPool constructor accepts a hash of configuration options:
*
* - concurrency: (callable|int) Maximum number of commands to execute
* concurrently. Provide a function to resize the pool dynamically. The
* function will be provided the current number of pending requests and
* is expected to return an integer representing the new pool size limit.
* - before: (callable) function to invoke before sending each command. The
* before function accepts the command and the key of the iterator of the
* command. You can mutate the command as needed in the before function
* before sending the command.
* - fulfilled: (callable) Function to invoke when a promise is fulfilled.
* The function is provided the result object, id of the iterator that the
* result came from, and the aggregate promise that can be resolved/rejected
* if you need to short-circuit the pool.
* - rejected: (callable) Function to invoke when a promise is rejected.
* The function is provided an AwsException object, id of the iterator that
* the exception came from, and the aggregate promise that can be
* resolved/rejected if you need to short-circuit the pool.
*
* @param AwsClientInterface $client Client used to execute commands.
* @param array|\Iterator $commands Iterable that yields commands.
* @param array $config Associative array of options.
*/
public function __construct(
AwsClientInterface $client,
$commands,
array $config = []
) {
if (!isset($config['concurrency'])) {
$config['concurrency'] = 25;
}
$before = $this->getBefore($config);
$mapFn = function ($commands) use ($client, $before) {
foreach ($commands as $key => $command) {
if (!($command instanceof CommandInterface)) {
throw new \InvalidArgumentException('Each value yielded by '
. 'the iterator must be an Aws\CommandInterface.');
}
if ($before) {
$before($command, $key);
}
yield $client->executeAsync($command);
}
};
$this->each = new EachPromise($mapFn($commands), $config);
}
/**
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public function promise()
{
return $this->each->promise();
}
/**
* Executes a pool synchronously and aggregates the results of the pool
* into an indexed array in the same order as the passed in array.
*
* @param AwsClientInterface $client Client used to execute commands.
* @param mixed $commands Iterable that yields commands.
* @param array $config Configuration options.
*
* @return array
* @see \Aws\CommandPool::__construct for available configuration options.
*/
public static function batch(
AwsClientInterface $client,
$commands,
array $config = []
) {
$results = [];
self::cmpCallback($config, 'fulfilled', $results);
self::cmpCallback($config, 'rejected', $results);
return (new self($client, $commands, $config))
->promise()
->then(static function () use (&$results) {
ksort($results);
return $results;
})
->wait();
}
/**
* @return callable
*/
private function getBefore(array $config)
{
if (!isset($config['before'])) {
return null;
}
if (is_callable($config['before'])) {
return $config['before'];
}
throw new \InvalidArgumentException('before must be callable');
}
/**
* Adds an onFulfilled or onRejected callback that aggregates results into
* an array. If a callback is already present, it is replaced with the
* composed function.
*
* @param array $config
* @param $name
* @param array $results
*/
private static function cmpCallback(array &$config, $name, array &$results)
{
if (!isset($config[$name])) {
$config[$name] = function ($v, $k) use (&$results) {
$results[$k] = $v;
};
} else {
$currentFn = $config[$name];
$config[$name] = function ($v, $k) use (&$results, $currentFn) {
$currentFn($v, $k);
$results[$k] = $v;
};
}
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace Aws\ConfigService;
use Aws\AwsClient;
/**
* This client is used to interact with AWS Config.
*
* @method \Aws\Result deleteConfigRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteConfigRuleAsync(array $args = [])
* @method \Aws\Result deleteConfigurationRecorder(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteConfigurationRecorderAsync(array $args = [])
* @method \Aws\Result deleteDeliveryChannel(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteDeliveryChannelAsync(array $args = [])
* @method \Aws\Result deleteEvaluationResults(array $args = [])
* @method \GuzzleHttp\Promise\Promise deleteEvaluationResultsAsync(array $args = [])
* @method \Aws\Result deliverConfigSnapshot(array $args = [])
* @method \GuzzleHttp\Promise\Promise deliverConfigSnapshotAsync(array $args = [])
* @method \Aws\Result describeComplianceByConfigRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeComplianceByConfigRuleAsync(array $args = [])
* @method \Aws\Result describeComplianceByResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeComplianceByResourceAsync(array $args = [])
* @method \Aws\Result describeConfigRuleEvaluationStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeConfigRuleEvaluationStatusAsync(array $args = [])
* @method \Aws\Result describeConfigRules(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeConfigRulesAsync(array $args = [])
* @method \Aws\Result describeConfigurationRecorderStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeConfigurationRecorderStatusAsync(array $args = [])
* @method \Aws\Result describeConfigurationRecorders(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeConfigurationRecordersAsync(array $args = [])
* @method \Aws\Result describeDeliveryChannelStatus(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeDeliveryChannelStatusAsync(array $args = [])
* @method \Aws\Result describeDeliveryChannels(array $args = [])
* @method \GuzzleHttp\Promise\Promise describeDeliveryChannelsAsync(array $args = [])
* @method \Aws\Result getComplianceDetailsByConfigRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise getComplianceDetailsByConfigRuleAsync(array $args = [])
* @method \Aws\Result getComplianceDetailsByResource(array $args = [])
* @method \GuzzleHttp\Promise\Promise getComplianceDetailsByResourceAsync(array $args = [])
* @method \Aws\Result getComplianceSummaryByConfigRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise getComplianceSummaryByConfigRuleAsync(array $args = [])
* @method \Aws\Result getComplianceSummaryByResourceType(array $args = [])
* @method \GuzzleHttp\Promise\Promise getComplianceSummaryByResourceTypeAsync(array $args = [])
* @method \Aws\Result getResourceConfigHistory(array $args = [])
* @method \GuzzleHttp\Promise\Promise getResourceConfigHistoryAsync(array $args = [])
* @method \Aws\Result listDiscoveredResources(array $args = [])
* @method \GuzzleHttp\Promise\Promise listDiscoveredResourcesAsync(array $args = [])
* @method \Aws\Result putConfigRule(array $args = [])
* @method \GuzzleHttp\Promise\Promise putConfigRuleAsync(array $args = [])
* @method \Aws\Result putConfigurationRecorder(array $args = [])
* @method \GuzzleHttp\Promise\Promise putConfigurationRecorderAsync(array $args = [])
* @method \Aws\Result putDeliveryChannel(array $args = [])
* @method \GuzzleHttp\Promise\Promise putDeliveryChannelAsync(array $args = [])
* @method \Aws\Result putEvaluations(array $args = [])
* @method \GuzzleHttp\Promise\Promise putEvaluationsAsync(array $args = [])
* @method \Aws\Result startConfigRulesEvaluation(array $args = [])
* @method \GuzzleHttp\Promise\Promise startConfigRulesEvaluationAsync(array $args = [])
* @method \Aws\Result startConfigurationRecorder(array $args = [])
* @method \GuzzleHttp\Promise\Promise startConfigurationRecorderAsync(array $args = [])
* @method \Aws\Result stopConfigurationRecorder(array $args = [])
* @method \GuzzleHttp\Promise\Promise stopConfigurationRecorderAsync(array $args = [])
*/
class ConfigServiceClient extends AwsClient {}

View File

@@ -0,0 +1,9 @@
<?php
namespace Aws\ConfigService\Exception;
use Aws\Exception\AwsException;
/**
* Represents an error interacting with the AWS Config service.
*/
class ConfigServiceException extends AwsException {}

View File

@@ -0,0 +1,343 @@
<?php
namespace Aws\Credentials;
use Aws;
use Aws\CacheInterface;
use Aws\Exception\CredentialsException;
use GuzzleHttp\Promise;
/**
* Credential providers are functions that accept no arguments and return a
* promise that is fulfilled with an {@see \Aws\Credentials\CredentialsInterface}
* or rejected with an {@see \Aws\Exception\CredentialsException}.
*
* <code>
* use Aws\Credentials\CredentialProvider;
* $provider = CredentialProvider::defaultProvider();
* // Returns a CredentialsInterface or throws.
* $creds = $provider()->wait();
* </code>
*
* Credential providers can be composed to create credentials using conditional
* logic that can create different credentials in different environments. You
* can compose multiple providers into a single provider using
* {@see Aws\Credentials\CredentialProvider::chain}. This function accepts
* providers as variadic arguments and returns a new function that will invoke
* each provider until a successful set of credentials is returned.
*
* <code>
* // First try an INI file at this location.
* $a = CredentialProvider::ini(null, '/path/to/file.ini');
* // Then try an INI file at this location.
* $b = CredentialProvider::ini(null, '/path/to/other-file.ini');
* // Then try loading from environment variables.
* $c = CredentialProvider::env();
* // Combine the three providers together.
* $composed = CredentialProvider::chain($a, $b, $c);
* // Returns a promise that is fulfilled with credentials or throws.
* $promise = $composed();
* // Wait on the credentials to resolve.
* $creds = $promise->wait();
* </code>
*/
class CredentialProvider
{
const ENV_KEY = 'AWS_ACCESS_KEY_ID';
const ENV_SECRET = 'AWS_SECRET_ACCESS_KEY';
const ENV_SESSION = 'AWS_SESSION_TOKEN';
const ENV_PROFILE = 'AWS_PROFILE';
/**
* Create a default credential provider that first checks for environment
* variables, then checks for the "default" profile in ~/.aws/credentials,
* then tries to make GET Request to fetch credentials if Ecs environment
* variable is presented, and finally checks for EC2 instance profile
* credentials.
*
* This provider is automatically wrapped in a memoize function that caches
* previously provided credentials.
*
* @param array $config Optional array of instance profile credentials
* provider options.
* @return callable
*/
public static function defaultProvider(array $config = [])
{
$instanceProfileProvider = self::instanceProfile($config);
$ecsCredentialProvider = self::ecsCredentials($config);
if (isset($config['credentials'])
&& $config['credentials'] instanceof CacheInterface
) {
$instanceProfileProvider = self::cache(
$instanceProfileProvider,
$config['credentials']
);
}
return self::memoize(
self::chain(
self::env(),
self::ini(),
$ecsCredentialProvider,
$instanceProfileProvider
)
);
}
/**
* Create a credential provider function from a set of static credentials.
*
* @param CredentialsInterface $creds
*
* @return callable
*/
public static function fromCredentials(CredentialsInterface $creds)
{
$promise = Promise\promise_for($creds);
return function () use ($promise) {
return $promise;
};
}
/**
* Creates an aggregate credentials provider that invokes the provided
* variadic providers one after the other until a provider returns
* credentials.
*
* @return callable
*/
public static function chain()
{
$links = func_get_args();
if (empty($links)) {
throw new \InvalidArgumentException('No providers in chain');
}
return function () use ($links) {
/** @var callable $parent */
$parent = array_shift($links);
$promise = $parent();
while ($next = array_shift($links)) {
$promise = $promise->otherwise($next);
}
return $promise;
};
}
/**
* Wraps a credential provider and caches previously provided credentials.
*
* Ensures that cached credentials are refreshed when they expire.
*
* @param callable $provider Credentials provider function to wrap.
*
* @return callable
*/
public static function memoize(callable $provider)
{
return function () use ($provider) {
static $result;
static $isConstant;
// Constant credentials will be returned constantly.
if ($isConstant) {
return $result;
}
// Create the initial promise that will be used as the cached value
// until it expires.
if (null === $result) {
$result = $provider();
}
// Return credentials that could expire and refresh when needed.
return $result
->then(function (CredentialsInterface $creds) use ($provider, &$isConstant, &$result) {
// Determine if these are constant credentials.
if (!$creds->getExpiration()) {
$isConstant = true;
return $creds;
}
// Refresh expired credentials.
if (!$creds->isExpired()) {
return $creds;
}
// Refresh the result and forward the promise.
return $result = $provider();
});
};
}
/**
* Wraps a credential provider and saves provided credentials in an
* instance of Aws\CacheInterface. Forwards calls when no credentials found
* in cache and updates cache with the results.
*
* Defaults to using a simple file-based cache when none provided.
*
* @param callable $provider Credentials provider function to wrap
* @param CacheInterface $cache (optional) Cache to store credentials
* @param string|null $cacheKey (optional) Cache key to use
*
* @return callable
*/
public static function cache(
callable $provider,
CacheInterface $cache,
$cacheKey = null
) {
$cacheKey = $cacheKey ?: 'aws_cached_credentials';
return function () use ($provider, $cache, $cacheKey) {
$found = $cache->get($cacheKey);
if ($found instanceof CredentialsInterface && !$found->isExpired()) {
return Promise\promise_for($found);
}
return $provider()
->then(function (CredentialsInterface $creds) use (
$cache,
$cacheKey
) {
$cache->set(
$cacheKey,
$creds,
null === $creds->getExpiration() ?
0 : $creds->getExpiration() - time()
);
return $creds;
});
};
}
/**
* Provider that creates credentials from environment variables
* AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN.
*
* @return callable
*/
public static function env()
{
return function () {
// Use credentials from environment variables, if available
$key = getenv(self::ENV_KEY);
$secret = getenv(self::ENV_SECRET);
if ($key && $secret) {
return Promise\promise_for(
new Credentials($key, $secret, getenv(self::ENV_SESSION))
);
}
return self::reject('Could not find environment variable '
. 'credentials in ' . self::ENV_KEY . '/' . self::ENV_SECRET);
};
}
/**
* Credential provider that creates credentials using instance profile
* credentials.
*
* @param array $config Array of configuration data.
*
* @return InstanceProfileProvider
* @see Aws\Credentials\InstanceProfileProvider for $config details.
*/
public static function instanceProfile(array $config = [])
{
return new InstanceProfileProvider($config);
}
/**
* Credential provider that creates credentials using
* ecs credentials by a GET request, whose uri is specified
* by environment variable
*
* @param array $config Array of configuration data.
*
* @return EcsCredentialProvider
* @see Aws\Credentials\EcsCredentialProvider for $config details.
*/
public static function ecsCredentials(array $config = [])
{
return new EcsCredentialProvider($config);
}
/**
* Credentials provider that creates credentials using an ini file stored
* in the current user's home directory.
*
* @param string|null $profile Profile to use. If not specified will use
* the "default" profile.
* @param string|null $filename If provided, uses a custom filename rather
* than looking in the home directory for the
*
* @return callable
*/
public static function ini($profile = null, $filename = null)
{
$filename = $filename ?: (self::getHomeDir() . '/.aws/credentials');
$profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
return function () use ($profile, $filename) {
if (!is_readable($filename)) {
return self::reject("Cannot read credentials from $filename");
}
$data = parse_ini_file($filename, true);
if ($data === false) {
return self::reject("Invalid credentials file: $filename");
}
if (!isset($data[$profile])) {
return self::reject("'$profile' not found in credentials file");
}
if (!isset($data[$profile]['aws_access_key_id'])
|| !isset($data[$profile]['aws_secret_access_key'])
) {
return self::reject("No credentials present in INI profile "
. "'$profile' ($filename)");
}
if (empty($data[$profile]['aws_session_token'])) {
$data[$profile]['aws_session_token']
= isset($data[$profile]['aws_security_token'])
? $data[$profile]['aws_security_token']
: null;
}
return Promise\promise_for(
new Credentials(
$data[$profile]['aws_access_key_id'],
$data[$profile]['aws_secret_access_key'],
$data[$profile]['aws_session_token']
)
);
};
}
/**
* Gets the environment's HOME directory if available.
*
* @return null|string
*/
private static function getHomeDir()
{
// On Linux/Unix-like systems, use the HOME environment variable
if ($homeDir = getenv('HOME')) {
return $homeDir;
}
// Get the HOMEDRIVE and HOMEPATH values for Windows hosts
$homeDrive = getenv('HOMEDRIVE');
$homePath = getenv('HOMEPATH');
return ($homeDrive && $homePath) ? $homeDrive . $homePath : null;
}
private static function reject($msg)
{
return new Promise\RejectedPromise(new CredentialsException($msg));
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace Aws\Credentials;
/**
* Basic implementation of the AWS Credentials interface that allows callers to
* pass in the AWS Access Key and AWS Secret Access Key in the constructor.
*/
class Credentials implements CredentialsInterface, \Serializable
{
private $key;
private $secret;
private $token;
private $expires;
/**
* Constructs a new BasicAWSCredentials object, with the specified AWS
* access key and AWS secret key
*
* @param string $key AWS access key ID
* @param string $secret AWS secret access key
* @param string $token Security token to use
* @param int $expires UNIX timestamp for when credentials expire
*/
public function __construct($key, $secret, $token = null, $expires = null)
{
$this->key = trim($key);
$this->secret = trim($secret);
$this->token = $token;
$this->expires = $expires;
}
public static function __set_state(array $state)
{
return new self(
$state['key'],
$state['secret'],
$state['token'],
$state['expires']
);
}
public function getAccessKeyId()
{
return $this->key;
}
public function getSecretKey()
{
return $this->secret;
}
public function getSecurityToken()
{
return $this->token;
}
public function getExpiration()
{
return $this->expires;
}
public function isExpired()
{
return $this->expires !== null && time() >= $this->expires;
}
public function toArray()
{
return [
'key' => $this->key,
'secret' => $this->secret,
'token' => $this->token,
'expires' => $this->expires
];
}
public function serialize()
{
return json_encode($this->toArray());
}
public function unserialize($serialized)
{
$data = json_decode($serialized, true);
$this->key = $data['key'];
$this->secret = $data['secret'];
$this->token = $data['token'];
$this->expires = $data['expires'];
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Aws\Credentials;
/**
* Provides access to the AWS credentials used for accessing AWS services: AWS
* access key ID, secret access key, and security token. These credentials are
* used to securely sign requests to AWS services.
*/
interface CredentialsInterface
{
/**
* Returns the AWS access key ID for this credentials object.
*
* @return string
*/
public function getAccessKeyId();
/**
* Returns the AWS secret access key for this credentials object.
*
* @return string
*/
public function getSecretKey();
/**
* Get the associated security token if available
*
* @return string|null
*/
public function getSecurityToken();
/**
* Get the UNIX timestamp in which the credentials will expire
*
* @return int|null
*/
public function getExpiration();
/**
* Check if the credentials are expired
*
* @return bool
*/
public function isExpired();
/**
* Converts the credentials to an associative array.
*
* @return array
*/
public function toArray();
}

Some files were not shown because too many files have changed in this diff Show More