repo
stringlengths 6
63
| path
stringlengths 5
140
| func_name
stringlengths 3
151
| original_string
stringlengths 84
13k
| language
stringclasses 1
value | code
stringlengths 84
13k
| code_tokens
sequence | docstring
stringlengths 3
47.2k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
aws/aws-sdk-php | src/EndpointDiscovery/EndpointDiscoveryMiddleware.php | EndpointDiscoveryMiddleware.parseEndpoint | private function parseEndpoint($endpoint)
{
$parsed = parse_url($endpoint);
// parse_url() will correctly parse full URIs with schemes
if (isset($parsed['host'])) {
return $parsed;
}
// parse_url() will put host & path in 'path' if scheme is not provided
if (isset($parsed['path'])) {
$split = explode('/', $parsed['path'], 2);
$parsed['host'] = $split[0];
if (isset($split[1])) {
$parsed['path'] = $split[1];
} else {
$parsed['path'] = '';
}
return $parsed;
}
throw new UnresolvedEndpointException("The supplied endpoint '"
. "{$endpoint}' is invalid.");
} | php | private function parseEndpoint($endpoint)
{
$parsed = parse_url($endpoint);
// parse_url() will correctly parse full URIs with schemes
if (isset($parsed['host'])) {
return $parsed;
}
// parse_url() will put host & path in 'path' if scheme is not provided
if (isset($parsed['path'])) {
$split = explode('/', $parsed['path'], 2);
$parsed['host'] = $split[0];
if (isset($split[1])) {
$parsed['path'] = $split[1];
} else {
$parsed['path'] = '';
}
return $parsed;
}
throw new UnresolvedEndpointException("The supplied endpoint '"
. "{$endpoint}' is invalid.");
} | [
"private",
"function",
"parseEndpoint",
"(",
"$",
"endpoint",
")",
"{",
"$",
"parsed",
"=",
"parse_url",
"(",
"$",
"endpoint",
")",
";",
"// parse_url() will correctly parse full URIs with schemes",
"if",
"(",
"isset",
"(",
"$",
"parsed",
"[",
"'host'",
"]",
")",
")",
"{",
"return",
"$",
"parsed",
";",
"}",
"// parse_url() will put host & path in 'path' if scheme is not provided",
"if",
"(",
"isset",
"(",
"$",
"parsed",
"[",
"'path'",
"]",
")",
")",
"{",
"$",
"split",
"=",
"explode",
"(",
"'/'",
",",
"$",
"parsed",
"[",
"'path'",
"]",
",",
"2",
")",
";",
"$",
"parsed",
"[",
"'host'",
"]",
"=",
"$",
"split",
"[",
"0",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"split",
"[",
"1",
"]",
")",
")",
"{",
"$",
"parsed",
"[",
"'path'",
"]",
"=",
"$",
"split",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"$",
"parsed",
"[",
"'path'",
"]",
"=",
"''",
";",
"}",
"return",
"$",
"parsed",
";",
"}",
"throw",
"new",
"UnresolvedEndpointException",
"(",
"\"The supplied endpoint '\"",
".",
"\"{$endpoint}' is invalid.\"",
")",
";",
"}"
] | Parses an endpoint returned from the discovery API into an array with
'host' and 'path' keys.
@param $endpoint
@return array | [
"Parses",
"an",
"endpoint",
"returned",
"from",
"the",
"discovery",
"API",
"into",
"an",
"array",
"with",
"host",
"and",
"path",
"keys",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/EndpointDiscovery/EndpointDiscoveryMiddleware.php#L376-L399 | train |
aws/aws-sdk-php | src/MachineLearning/MachineLearningClient.php | MachineLearningClient.predictEndpoint | private function predictEndpoint()
{
return static function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
if ($command->getName() === 'Predict') {
$request = $request->withUri(new Uri($command['PredictEndpoint']));
}
return $handler($command, $request);
};
};
} | php | private function predictEndpoint()
{
return static function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
if ($command->getName() === 'Predict') {
$request = $request->withUri(new Uri($command['PredictEndpoint']));
}
return $handler($command, $request);
};
};
} | [
"private",
"function",
"predictEndpoint",
"(",
")",
"{",
"return",
"static",
"function",
"(",
"callable",
"$",
"handler",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
")",
"{",
"if",
"(",
"$",
"command",
"->",
"getName",
"(",
")",
"===",
"'Predict'",
")",
"{",
"$",
"request",
"=",
"$",
"request",
"->",
"withUri",
"(",
"new",
"Uri",
"(",
"$",
"command",
"[",
"'PredictEndpoint'",
"]",
")",
")",
";",
"}",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
")",
";",
"}",
";",
"}",
";",
"}"
] | Changes the endpoint of the Predict operation to the provided endpoint.
@return callable | [
"Changes",
"the",
"endpoint",
"of",
"the",
"Predict",
"operation",
"to",
"the",
"provided",
"endpoint",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/MachineLearning/MachineLearningClient.php#L83-L96 | train |
aws/aws-sdk-php | src/S3/S3Client.php | S3Client.isBucketDnsCompatible | public static function isBucketDnsCompatible($bucket)
{
$bucketLen = strlen($bucket);
return ($bucketLen >= 3 && $bucketLen <= 63) &&
// Cannot look like an IP address
!filter_var($bucket, FILTER_VALIDATE_IP) &&
preg_match('/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/', $bucket);
} | php | public static function isBucketDnsCompatible($bucket)
{
$bucketLen = strlen($bucket);
return ($bucketLen >= 3 && $bucketLen <= 63) &&
// Cannot look like an IP address
!filter_var($bucket, FILTER_VALIDATE_IP) &&
preg_match('/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/', $bucket);
} | [
"public",
"static",
"function",
"isBucketDnsCompatible",
"(",
"$",
"bucket",
")",
"{",
"$",
"bucketLen",
"=",
"strlen",
"(",
"$",
"bucket",
")",
";",
"return",
"(",
"$",
"bucketLen",
">=",
"3",
"&&",
"$",
"bucketLen",
"<=",
"63",
")",
"&&",
"// Cannot look like an IP address",
"!",
"filter_var",
"(",
"$",
"bucket",
",",
"FILTER_VALIDATE_IP",
")",
"&&",
"preg_match",
"(",
"'/^[a-z0-9]([a-z0-9\\-\\.]*[a-z0-9])?$/'",
",",
"$",
"bucket",
")",
";",
"}"
] | Determine if a string is a valid name for a DNS compatible Amazon S3
bucket.
DNS compatible bucket names can be used as a subdomain in a URL (e.g.,
"<bucket>.s3.amazonaws.com").
@param string $bucket Bucket name to check.
@return bool | [
"Determine",
"if",
"a",
"string",
"is",
"a",
"valid",
"name",
"for",
"a",
"DNS",
"compatible",
"Amazon",
"S3",
"bucket",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/S3Client.php#L330-L338 | train |
aws/aws-sdk-php | src/S3/S3Client.php | S3Client.getLocationConstraintMiddleware | private function getLocationConstraintMiddleware()
{
$region = $this->getRegion();
return static function (callable $handler) use ($region) {
return function (Command $command, $request = null) use ($handler, $region) {
if ($command->getName() === 'CreateBucket') {
$locationConstraint = isset($command['CreateBucketConfiguration']['LocationConstraint'])
? $command['CreateBucketConfiguration']['LocationConstraint']
: null;
if ($locationConstraint === 'us-east-1') {
unset($command['CreateBucketConfiguration']);
} elseif ('us-east-1' !== $region && empty($locationConstraint)) {
$command['CreateBucketConfiguration'] = ['LocationConstraint' => $region];
}
}
return $handler($command, $request);
};
};
} | php | private function getLocationConstraintMiddleware()
{
$region = $this->getRegion();
return static function (callable $handler) use ($region) {
return function (Command $command, $request = null) use ($handler, $region) {
if ($command->getName() === 'CreateBucket') {
$locationConstraint = isset($command['CreateBucketConfiguration']['LocationConstraint'])
? $command['CreateBucketConfiguration']['LocationConstraint']
: null;
if ($locationConstraint === 'us-east-1') {
unset($command['CreateBucketConfiguration']);
} elseif ('us-east-1' !== $region && empty($locationConstraint)) {
$command['CreateBucketConfiguration'] = ['LocationConstraint' => $region];
}
}
return $handler($command, $request);
};
};
} | [
"private",
"function",
"getLocationConstraintMiddleware",
"(",
")",
"{",
"$",
"region",
"=",
"$",
"this",
"->",
"getRegion",
"(",
")",
";",
"return",
"static",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"region",
")",
"{",
"return",
"function",
"(",
"Command",
"$",
"command",
",",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
",",
"$",
"region",
")",
"{",
"if",
"(",
"$",
"command",
"->",
"getName",
"(",
")",
"===",
"'CreateBucket'",
")",
"{",
"$",
"locationConstraint",
"=",
"isset",
"(",
"$",
"command",
"[",
"'CreateBucketConfiguration'",
"]",
"[",
"'LocationConstraint'",
"]",
")",
"?",
"$",
"command",
"[",
"'CreateBucketConfiguration'",
"]",
"[",
"'LocationConstraint'",
"]",
":",
"null",
";",
"if",
"(",
"$",
"locationConstraint",
"===",
"'us-east-1'",
")",
"{",
"unset",
"(",
"$",
"command",
"[",
"'CreateBucketConfiguration'",
"]",
")",
";",
"}",
"elseif",
"(",
"'us-east-1'",
"!==",
"$",
"region",
"&&",
"empty",
"(",
"$",
"locationConstraint",
")",
")",
"{",
"$",
"command",
"[",
"'CreateBucketConfiguration'",
"]",
"=",
"[",
"'LocationConstraint'",
"=>",
"$",
"region",
"]",
";",
"}",
"}",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
")",
";",
"}",
";",
"}",
";",
"}"
] | Provides a middleware that removes the need to specify LocationConstraint on CreateBucket.
@return \Closure | [
"Provides",
"a",
"middleware",
"that",
"removes",
"the",
"need",
"to",
"specify",
"LocationConstraint",
"on",
"CreateBucket",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/S3Client.php#L387-L407 | train |
aws/aws-sdk-php | src/S3/S3Client.php | S3Client.getSaveAsParameter | private function getSaveAsParameter()
{
return static function (callable $handler) {
return function (Command $command, $request = null) use ($handler) {
if ($command->getName() === 'GetObject' && isset($command['SaveAs'])) {
$command['@http']['sink'] = $command['SaveAs'];
unset($command['SaveAs']);
}
return $handler($command, $request);
};
};
} | php | private function getSaveAsParameter()
{
return static function (callable $handler) {
return function (Command $command, $request = null) use ($handler) {
if ($command->getName() === 'GetObject' && isset($command['SaveAs'])) {
$command['@http']['sink'] = $command['SaveAs'];
unset($command['SaveAs']);
}
return $handler($command, $request);
};
};
} | [
"private",
"function",
"getSaveAsParameter",
"(",
")",
"{",
"return",
"static",
"function",
"(",
"callable",
"$",
"handler",
")",
"{",
"return",
"function",
"(",
"Command",
"$",
"command",
",",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
")",
"{",
"if",
"(",
"$",
"command",
"->",
"getName",
"(",
")",
"===",
"'GetObject'",
"&&",
"isset",
"(",
"$",
"command",
"[",
"'SaveAs'",
"]",
")",
")",
"{",
"$",
"command",
"[",
"'@http'",
"]",
"[",
"'sink'",
"]",
"=",
"$",
"command",
"[",
"'SaveAs'",
"]",
";",
"unset",
"(",
"$",
"command",
"[",
"'SaveAs'",
"]",
")",
";",
"}",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
")",
";",
"}",
";",
"}",
";",
"}"
] | Provides a middleware that supports the `SaveAs` parameter.
@return \Closure | [
"Provides",
"a",
"middleware",
"that",
"supports",
"the",
"SaveAs",
"parameter",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/S3Client.php#L414-L426 | train |
aws/aws-sdk-php | src/S3/S3Client.php | S3Client.getHeadObjectMiddleware | private function getHeadObjectMiddleware()
{
return static function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
if ($command->getName() === 'HeadObject'
&& !isset($command['@http']['decode_content'])
) {
$command['@http']['decode_content'] = false;
}
return $handler($command, $request);
};
};
} | php | private function getHeadObjectMiddleware()
{
return static function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
if ($command->getName() === 'HeadObject'
&& !isset($command['@http']['decode_content'])
) {
$command['@http']['decode_content'] = false;
}
return $handler($command, $request);
};
};
} | [
"private",
"function",
"getHeadObjectMiddleware",
"(",
")",
"{",
"return",
"static",
"function",
"(",
"callable",
"$",
"handler",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
")",
"{",
"if",
"(",
"$",
"command",
"->",
"getName",
"(",
")",
"===",
"'HeadObject'",
"&&",
"!",
"isset",
"(",
"$",
"command",
"[",
"'@http'",
"]",
"[",
"'decode_content'",
"]",
")",
")",
"{",
"$",
"command",
"[",
"'@http'",
"]",
"[",
"'decode_content'",
"]",
"=",
"false",
";",
"}",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
")",
";",
"}",
";",
"}",
";",
"}"
] | Provides a middleware that disables content decoding on HeadObject
commands.
@return \Closure | [
"Provides",
"a",
"middleware",
"that",
"disables",
"content",
"decoding",
"on",
"HeadObject",
"commands",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/S3Client.php#L434-L450 | train |
aws/aws-sdk-php | src/S3/MultipartUploader.php | MultipartUploader.decorateWithHashes | private function decorateWithHashes(Stream $stream, array &$data)
{
// Decorate source with a hashing stream
$hash = new PhpHash('sha256');
return new HashingStream($stream, $hash, function ($result) use (&$data) {
$data['ContentSHA256'] = bin2hex($result);
});
} | php | private function decorateWithHashes(Stream $stream, array &$data)
{
// Decorate source with a hashing stream
$hash = new PhpHash('sha256');
return new HashingStream($stream, $hash, function ($result) use (&$data) {
$data['ContentSHA256'] = bin2hex($result);
});
} | [
"private",
"function",
"decorateWithHashes",
"(",
"Stream",
"$",
"stream",
",",
"array",
"&",
"$",
"data",
")",
"{",
"// Decorate source with a hashing stream",
"$",
"hash",
"=",
"new",
"PhpHash",
"(",
"'sha256'",
")",
";",
"return",
"new",
"HashingStream",
"(",
"$",
"stream",
",",
"$",
"hash",
",",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"&",
"$",
"data",
")",
"{",
"$",
"data",
"[",
"'ContentSHA256'",
"]",
"=",
"bin2hex",
"(",
"$",
"result",
")",
";",
"}",
")",
";",
"}"
] | Decorates a stream with a sha256 linear hashing stream.
@param Stream $stream Stream to decorate.
@param array $data Part data to augment with the hash result.
@return Stream | [
"Decorates",
"a",
"stream",
"with",
"a",
"sha256",
"linear",
"hashing",
"stream",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/MultipartUploader.php#L160-L167 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.appendInit | public function appendInit(callable $middleware, $name = null)
{
$this->add(self::INIT, $name, $middleware);
} | php | public function appendInit(callable $middleware, $name = null)
{
$this->add(self::INIT, $name, $middleware);
} | [
"public",
"function",
"appendInit",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"INIT",
",",
"$",
"name",
",",
"$",
"middleware",
")",
";",
"}"
] | Append a middleware to the init step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Append",
"a",
"middleware",
"to",
"the",
"init",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L124-L127 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.prependInit | public function prependInit(callable $middleware, $name = null)
{
$this->add(self::INIT, $name, $middleware, true);
} | php | public function prependInit(callable $middleware, $name = null)
{
$this->add(self::INIT, $name, $middleware, true);
} | [
"public",
"function",
"prependInit",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"INIT",
",",
"$",
"name",
",",
"$",
"middleware",
",",
"true",
")",
";",
"}"
] | Prepend a middleware to the init step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Prepend",
"a",
"middleware",
"to",
"the",
"init",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L135-L138 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.appendValidate | public function appendValidate(callable $middleware, $name = null)
{
$this->add(self::VALIDATE, $name, $middleware);
} | php | public function appendValidate(callable $middleware, $name = null)
{
$this->add(self::VALIDATE, $name, $middleware);
} | [
"public",
"function",
"appendValidate",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"VALIDATE",
",",
"$",
"name",
",",
"$",
"middleware",
")",
";",
"}"
] | Append a middleware to the validate step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Append",
"a",
"middleware",
"to",
"the",
"validate",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L146-L149 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.prependValidate | public function prependValidate(callable $middleware, $name = null)
{
$this->add(self::VALIDATE, $name, $middleware, true);
} | php | public function prependValidate(callable $middleware, $name = null)
{
$this->add(self::VALIDATE, $name, $middleware, true);
} | [
"public",
"function",
"prependValidate",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"VALIDATE",
",",
"$",
"name",
",",
"$",
"middleware",
",",
"true",
")",
";",
"}"
] | Prepend a middleware to the validate step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Prepend",
"a",
"middleware",
"to",
"the",
"validate",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L157-L160 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.appendBuild | public function appendBuild(callable $middleware, $name = null)
{
$this->add(self::BUILD, $name, $middleware);
} | php | public function appendBuild(callable $middleware, $name = null)
{
$this->add(self::BUILD, $name, $middleware);
} | [
"public",
"function",
"appendBuild",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"BUILD",
",",
"$",
"name",
",",
"$",
"middleware",
")",
";",
"}"
] | Append a middleware to the build step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Append",
"a",
"middleware",
"to",
"the",
"build",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L168-L171 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.prependBuild | public function prependBuild(callable $middleware, $name = null)
{
$this->add(self::BUILD, $name, $middleware, true);
} | php | public function prependBuild(callable $middleware, $name = null)
{
$this->add(self::BUILD, $name, $middleware, true);
} | [
"public",
"function",
"prependBuild",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"BUILD",
",",
"$",
"name",
",",
"$",
"middleware",
",",
"true",
")",
";",
"}"
] | Prepend a middleware to the build step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Prepend",
"a",
"middleware",
"to",
"the",
"build",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L179-L182 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.appendSign | public function appendSign(callable $middleware, $name = null)
{
$this->add(self::SIGN, $name, $middleware);
} | php | public function appendSign(callable $middleware, $name = null)
{
$this->add(self::SIGN, $name, $middleware);
} | [
"public",
"function",
"appendSign",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"SIGN",
",",
"$",
"name",
",",
"$",
"middleware",
")",
";",
"}"
] | Append a middleware to the sign step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Append",
"a",
"middleware",
"to",
"the",
"sign",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L190-L193 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.prependSign | public function prependSign(callable $middleware, $name = null)
{
$this->add(self::SIGN, $name, $middleware, true);
} | php | public function prependSign(callable $middleware, $name = null)
{
$this->add(self::SIGN, $name, $middleware, true);
} | [
"public",
"function",
"prependSign",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"SIGN",
",",
"$",
"name",
",",
"$",
"middleware",
",",
"true",
")",
";",
"}"
] | Prepend a middleware to the sign step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Prepend",
"a",
"middleware",
"to",
"the",
"sign",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L201-L204 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.appendAttempt | public function appendAttempt(callable $middleware, $name = null)
{
$this->add(self::ATTEMPT, $name, $middleware);
} | php | public function appendAttempt(callable $middleware, $name = null)
{
$this->add(self::ATTEMPT, $name, $middleware);
} | [
"public",
"function",
"appendAttempt",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"ATTEMPT",
",",
"$",
"name",
",",
"$",
"middleware",
")",
";",
"}"
] | Append a middleware to the attempt step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Append",
"a",
"middleware",
"to",
"the",
"attempt",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L212-L215 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.prependAttempt | public function prependAttempt(callable $middleware, $name = null)
{
$this->add(self::ATTEMPT, $name, $middleware, true);
} | php | public function prependAttempt(callable $middleware, $name = null)
{
$this->add(self::ATTEMPT, $name, $middleware, true);
} | [
"public",
"function",
"prependAttempt",
"(",
"callable",
"$",
"middleware",
",",
"$",
"name",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"add",
"(",
"self",
"::",
"ATTEMPT",
",",
"$",
"name",
",",
"$",
"middleware",
",",
"true",
")",
";",
"}"
] | Prepend a middleware to the attempt step.
@param callable $middleware Middleware function to add.
@param string $name Name of the middleware. | [
"Prepend",
"a",
"middleware",
"to",
"the",
"attempt",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L223-L226 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.before | public function before($findName, $withName, callable $middleware)
{
$this->splice($findName, $withName, $middleware, true);
} | php | public function before($findName, $withName, callable $middleware)
{
$this->splice($findName, $withName, $middleware, true);
} | [
"public",
"function",
"before",
"(",
"$",
"findName",
",",
"$",
"withName",
",",
"callable",
"$",
"middleware",
")",
"{",
"$",
"this",
"->",
"splice",
"(",
"$",
"findName",
",",
"$",
"withName",
",",
"$",
"middleware",
",",
"true",
")",
";",
"}"
] | Add a middleware before the given middleware by name.
@param string|callable $findName Add before this
@param string $withName Optional name to give the middleware
@param callable $middleware Middleware to add. | [
"Add",
"a",
"middleware",
"before",
"the",
"given",
"middleware",
"by",
"name",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L235-L238 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.remove | public function remove($nameOrInstance)
{
if (is_callable($nameOrInstance)) {
$this->removeByInstance($nameOrInstance);
} elseif (is_string($nameOrInstance)) {
$this->removeByName($nameOrInstance);
}
} | php | public function remove($nameOrInstance)
{
if (is_callable($nameOrInstance)) {
$this->removeByInstance($nameOrInstance);
} elseif (is_string($nameOrInstance)) {
$this->removeByName($nameOrInstance);
}
} | [
"public",
"function",
"remove",
"(",
"$",
"nameOrInstance",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"nameOrInstance",
")",
")",
"{",
"$",
"this",
"->",
"removeByInstance",
"(",
"$",
"nameOrInstance",
")",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"nameOrInstance",
")",
")",
"{",
"$",
"this",
"->",
"removeByName",
"(",
"$",
"nameOrInstance",
")",
";",
"}",
"}"
] | Remove a middleware by name or by instance from the list.
@param string|callable $nameOrInstance Middleware to remove. | [
"Remove",
"a",
"middleware",
"by",
"name",
"or",
"by",
"instance",
"from",
"the",
"list",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L257-L264 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.sortMiddleware | private function sortMiddleware()
{
$this->sorted = [];
if (!$this->interposeFn) {
foreach ($this->steps as $step) {
foreach ($step as $fn) {
$this->sorted[] = $fn[0];
}
}
return;
}
$ifn = $this->interposeFn;
// Interpose the interposeFn into the handler stack.
foreach ($this->steps as $stepName => $step) {
foreach ($step as $fn) {
$this->sorted[] = $ifn($stepName, $fn[1]);
$this->sorted[] = $fn[0];
}
}
} | php | private function sortMiddleware()
{
$this->sorted = [];
if (!$this->interposeFn) {
foreach ($this->steps as $step) {
foreach ($step as $fn) {
$this->sorted[] = $fn[0];
}
}
return;
}
$ifn = $this->interposeFn;
// Interpose the interposeFn into the handler stack.
foreach ($this->steps as $stepName => $step) {
foreach ($step as $fn) {
$this->sorted[] = $ifn($stepName, $fn[1]);
$this->sorted[] = $fn[0];
}
}
} | [
"private",
"function",
"sortMiddleware",
"(",
")",
"{",
"$",
"this",
"->",
"sorted",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"interposeFn",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"steps",
"as",
"$",
"step",
")",
"{",
"foreach",
"(",
"$",
"step",
"as",
"$",
"fn",
")",
"{",
"$",
"this",
"->",
"sorted",
"[",
"]",
"=",
"$",
"fn",
"[",
"0",
"]",
";",
"}",
"}",
"return",
";",
"}",
"$",
"ifn",
"=",
"$",
"this",
"->",
"interposeFn",
";",
"// Interpose the interposeFn into the handler stack.",
"foreach",
"(",
"$",
"this",
"->",
"steps",
"as",
"$",
"stepName",
"=>",
"$",
"step",
")",
"{",
"foreach",
"(",
"$",
"step",
"as",
"$",
"fn",
")",
"{",
"$",
"this",
"->",
"sorted",
"[",
"]",
"=",
"$",
"ifn",
"(",
"$",
"stepName",
",",
"$",
"fn",
"[",
"1",
"]",
")",
";",
"$",
"this",
"->",
"sorted",
"[",
"]",
"=",
"$",
"fn",
"[",
"0",
"]",
";",
"}",
"}",
"}"
] | Sort the middleware, and interpose if needed in the sorted list. | [
"Sort",
"the",
"middleware",
"and",
"interpose",
"if",
"needed",
"in",
"the",
"sorted",
"list",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L375-L396 | train |
aws/aws-sdk-php | src/HandlerList.php | HandlerList.add | private function add($step, $name, callable $middleware, $prepend = false)
{
$this->sorted = null;
if ($prepend) {
$this->steps[$step][] = [$middleware, $name];
} else {
array_unshift($this->steps[$step], [$middleware, $name]);
}
if ($name) {
$this->named[$name] = $step;
}
} | php | private function add($step, $name, callable $middleware, $prepend = false)
{
$this->sorted = null;
if ($prepend) {
$this->steps[$step][] = [$middleware, $name];
} else {
array_unshift($this->steps[$step], [$middleware, $name]);
}
if ($name) {
$this->named[$name] = $step;
}
} | [
"private",
"function",
"add",
"(",
"$",
"step",
",",
"$",
"name",
",",
"callable",
"$",
"middleware",
",",
"$",
"prepend",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"sorted",
"=",
"null",
";",
"if",
"(",
"$",
"prepend",
")",
"{",
"$",
"this",
"->",
"steps",
"[",
"$",
"step",
"]",
"[",
"]",
"=",
"[",
"$",
"middleware",
",",
"$",
"name",
"]",
";",
"}",
"else",
"{",
"array_unshift",
"(",
"$",
"this",
"->",
"steps",
"[",
"$",
"step",
"]",
",",
"[",
"$",
"middleware",
",",
"$",
"name",
"]",
")",
";",
"}",
"if",
"(",
"$",
"name",
")",
"{",
"$",
"this",
"->",
"named",
"[",
"$",
"name",
"]",
"=",
"$",
"step",
";",
"}",
"}"
] | Add a middleware to a step.
@param string $step Middleware step.
@param string $name Middleware name.
@param callable $middleware Middleware function to add.
@param bool $prepend Prepend instead of append. | [
"Add",
"a",
"middleware",
"to",
"a",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/HandlerList.php#L437-L450 | train |
aws/aws-sdk-php | src/ResultPaginator.php | ResultPaginator.each | public function each(callable $handleResult)
{
return Promise\coroutine(function () use ($handleResult) {
$nextToken = null;
do {
$command = $this->createNextCommand($this->args, $nextToken);
$result = (yield $this->client->executeAsync($command));
$nextToken = $this->determineNextToken($result);
$retVal = $handleResult($result);
if ($retVal !== null) {
yield Promise\promise_for($retVal);
}
} while ($nextToken);
});
} | php | public function each(callable $handleResult)
{
return Promise\coroutine(function () use ($handleResult) {
$nextToken = null;
do {
$command = $this->createNextCommand($this->args, $nextToken);
$result = (yield $this->client->executeAsync($command));
$nextToken = $this->determineNextToken($result);
$retVal = $handleResult($result);
if ($retVal !== null) {
yield Promise\promise_for($retVal);
}
} while ($nextToken);
});
} | [
"public",
"function",
"each",
"(",
"callable",
"$",
"handleResult",
")",
"{",
"return",
"Promise",
"\\",
"coroutine",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"handleResult",
")",
"{",
"$",
"nextToken",
"=",
"null",
";",
"do",
"{",
"$",
"command",
"=",
"$",
"this",
"->",
"createNextCommand",
"(",
"$",
"this",
"->",
"args",
",",
"$",
"nextToken",
")",
";",
"$",
"result",
"=",
"(",
"yield",
"$",
"this",
"->",
"client",
"->",
"executeAsync",
"(",
"$",
"command",
")",
")",
";",
"$",
"nextToken",
"=",
"$",
"this",
"->",
"determineNextToken",
"(",
"$",
"result",
")",
";",
"$",
"retVal",
"=",
"$",
"handleResult",
"(",
"$",
"result",
")",
";",
"if",
"(",
"$",
"retVal",
"!==",
"null",
")",
"{",
"yield",
"Promise",
"\\",
"promise_for",
"(",
"$",
"retVal",
")",
";",
"}",
"}",
"while",
"(",
"$",
"nextToken",
")",
";",
"}",
")",
";",
"}"
] | Runs a paginator asynchronously and uses a callback to handle results.
The callback should have the signature: function (Aws\Result $result).
A non-null return value from the callback will be yielded by the
promise. This means that you can return promises from the callback that
will need to be resolved before continuing iteration over the remaining
items, essentially merging in other promises to the iteration. The last
non-null value returned by the callback will be the result that fulfills
the promise to any downstream promises.
@param callable $handleResult Callback for handling each page of results.
The callback accepts the result that was
yielded as a single argument. If the
callback returns a promise, the promise
will be merged into the coroutine.
@return Promise\Promise | [
"Runs",
"a",
"paginator",
"asynchronously",
"and",
"uses",
"a",
"callback",
"to",
"handle",
"results",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ResultPaginator.php#L69-L83 | train |
aws/aws-sdk-php | src/ResultPaginator.php | ResultPaginator.search | public function search($expression)
{
// Apply JMESPath expression on each result, but as a flat sequence.
return flatmap($this, function (Result $result) use ($expression) {
return (array) $result->search($expression);
});
} | php | public function search($expression)
{
// Apply JMESPath expression on each result, but as a flat sequence.
return flatmap($this, function (Result $result) use ($expression) {
return (array) $result->search($expression);
});
} | [
"public",
"function",
"search",
"(",
"$",
"expression",
")",
"{",
"// Apply JMESPath expression on each result, but as a flat sequence.",
"return",
"flatmap",
"(",
"$",
"this",
",",
"function",
"(",
"Result",
"$",
"result",
")",
"use",
"(",
"$",
"expression",
")",
"{",
"return",
"(",
"array",
")",
"$",
"result",
"->",
"search",
"(",
"$",
"expression",
")",
";",
"}",
")",
";",
"}"
] | Returns an iterator that iterates over the values of applying a JMESPath
search to each result yielded by the iterator as a flat sequence.
@param string $expression JMESPath expression to apply to each result.
@return \Iterator | [
"Returns",
"an",
"iterator",
"that",
"iterates",
"over",
"the",
"values",
"of",
"applying",
"a",
"JMESPath",
"search",
"to",
"each",
"result",
"yielded",
"by",
"the",
"iterator",
"as",
"a",
"flat",
"sequence",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ResultPaginator.php#L93-L99 | train |
aws/aws-sdk-php | src/Api/ShapeMap.php | ShapeMap.resolve | 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;
} | php | 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;
} | [
"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",
";",
"}"
] | Resolve a shape reference
@param array $shapeRef Shape reference shape
@return Shape
@throws \InvalidArgumentException | [
"Resolve",
"a",
"shape",
"reference"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/ShapeMap.php#L41-L65 | train |
aws/aws-sdk-php | src/Crypto/EncryptionTrait.php | EncryptionTrait.encrypt | protected function encrypt(
Stream $plaintext,
array $cipherOptions,
MaterialsProvider $provider,
MetadataEnvelope $envelope
) {
$materialsDescription = $provider->getMaterialsDescription();
$cipherOptions = array_intersect_key(
$cipherOptions,
self::$allowedOptions
);
if (empty($cipherOptions['Cipher'])) {
throw new \InvalidArgumentException('An encryption cipher must be'
. ' specified in the "cipher_options".');
}
if (!self::isSupportedCipher($cipherOptions['Cipher'])) {
throw new \InvalidArgumentException('The cipher requested is not'
. ' supported by the SDK.');
}
if (empty($cipherOptions['KeySize'])) {
$cipherOptions['KeySize'] = 256;
}
if (!is_int($cipherOptions['KeySize'])) {
throw new \InvalidArgumentException('The cipher "KeySize" must be'
. ' an integer.');
}
if (!MaterialsProvider::isSupportedKeySize(
$cipherOptions['KeySize']
)) {
throw new \InvalidArgumentException('The cipher "KeySize" requested'
. ' is not supported by AES (128, 192, or 256).');
}
$cipherOptions['Iv'] = $provider->generateIv(
$this->getCipherOpenSslName(
$cipherOptions['Cipher'],
$cipherOptions['KeySize']
)
);
$cek = $provider->generateCek($cipherOptions['KeySize']);
list($encryptingStream, $aesName) = $this->getEncryptingStream(
$plaintext,
$cek,
$cipherOptions
);
// Populate envelope data
$envelope[MetadataEnvelope::CONTENT_KEY_V2_HEADER] =
$provider->encryptCek(
$cek,
$materialsDescription
);
unset($cek);
$envelope[MetadataEnvelope::IV_HEADER] =
base64_encode($cipherOptions['Iv']);
$envelope[MetadataEnvelope::KEY_WRAP_ALGORITHM_HEADER] =
$provider->getWrapAlgorithmName();
$envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER] = $aesName;
$envelope[MetadataEnvelope::UNENCRYPTED_CONTENT_LENGTH_HEADER] =
strlen($plaintext);
$envelope[MetadataEnvelope::UNENCRYPTED_CONTENT_MD5_HEADER] =
base64_encode(md5($plaintext));
$envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER] =
json_encode($materialsDescription);
if (!empty($cipherOptions['Tag'])) {
$envelope[MetadataEnvelope::CRYPTO_TAG_LENGTH_HEADER] =
strlen($cipherOptions['Tag']) * 8;
}
return $encryptingStream;
} | php | protected function encrypt(
Stream $plaintext,
array $cipherOptions,
MaterialsProvider $provider,
MetadataEnvelope $envelope
) {
$materialsDescription = $provider->getMaterialsDescription();
$cipherOptions = array_intersect_key(
$cipherOptions,
self::$allowedOptions
);
if (empty($cipherOptions['Cipher'])) {
throw new \InvalidArgumentException('An encryption cipher must be'
. ' specified in the "cipher_options".');
}
if (!self::isSupportedCipher($cipherOptions['Cipher'])) {
throw new \InvalidArgumentException('The cipher requested is not'
. ' supported by the SDK.');
}
if (empty($cipherOptions['KeySize'])) {
$cipherOptions['KeySize'] = 256;
}
if (!is_int($cipherOptions['KeySize'])) {
throw new \InvalidArgumentException('The cipher "KeySize" must be'
. ' an integer.');
}
if (!MaterialsProvider::isSupportedKeySize(
$cipherOptions['KeySize']
)) {
throw new \InvalidArgumentException('The cipher "KeySize" requested'
. ' is not supported by AES (128, 192, or 256).');
}
$cipherOptions['Iv'] = $provider->generateIv(
$this->getCipherOpenSslName(
$cipherOptions['Cipher'],
$cipherOptions['KeySize']
)
);
$cek = $provider->generateCek($cipherOptions['KeySize']);
list($encryptingStream, $aesName) = $this->getEncryptingStream(
$plaintext,
$cek,
$cipherOptions
);
// Populate envelope data
$envelope[MetadataEnvelope::CONTENT_KEY_V2_HEADER] =
$provider->encryptCek(
$cek,
$materialsDescription
);
unset($cek);
$envelope[MetadataEnvelope::IV_HEADER] =
base64_encode($cipherOptions['Iv']);
$envelope[MetadataEnvelope::KEY_WRAP_ALGORITHM_HEADER] =
$provider->getWrapAlgorithmName();
$envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER] = $aesName;
$envelope[MetadataEnvelope::UNENCRYPTED_CONTENT_LENGTH_HEADER] =
strlen($plaintext);
$envelope[MetadataEnvelope::UNENCRYPTED_CONTENT_MD5_HEADER] =
base64_encode(md5($plaintext));
$envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER] =
json_encode($materialsDescription);
if (!empty($cipherOptions['Tag'])) {
$envelope[MetadataEnvelope::CRYPTO_TAG_LENGTH_HEADER] =
strlen($cipherOptions['Tag']) * 8;
}
return $encryptingStream;
} | [
"protected",
"function",
"encrypt",
"(",
"Stream",
"$",
"plaintext",
",",
"array",
"$",
"cipherOptions",
",",
"MaterialsProvider",
"$",
"provider",
",",
"MetadataEnvelope",
"$",
"envelope",
")",
"{",
"$",
"materialsDescription",
"=",
"$",
"provider",
"->",
"getMaterialsDescription",
"(",
")",
";",
"$",
"cipherOptions",
"=",
"array_intersect_key",
"(",
"$",
"cipherOptions",
",",
"self",
"::",
"$",
"allowedOptions",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"cipherOptions",
"[",
"'Cipher'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'An encryption cipher must be'",
".",
"' specified in the \"cipher_options\".'",
")",
";",
"}",
"if",
"(",
"!",
"self",
"::",
"isSupportedCipher",
"(",
"$",
"cipherOptions",
"[",
"'Cipher'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The cipher requested is not'",
".",
"' supported by the SDK.'",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"cipherOptions",
"[",
"'KeySize'",
"]",
")",
")",
"{",
"$",
"cipherOptions",
"[",
"'KeySize'",
"]",
"=",
"256",
";",
"}",
"if",
"(",
"!",
"is_int",
"(",
"$",
"cipherOptions",
"[",
"'KeySize'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The cipher \"KeySize\" must be'",
".",
"' an integer.'",
")",
";",
"}",
"if",
"(",
"!",
"MaterialsProvider",
"::",
"isSupportedKeySize",
"(",
"$",
"cipherOptions",
"[",
"'KeySize'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The cipher \"KeySize\" requested'",
".",
"' is not supported by AES (128, 192, or 256).'",
")",
";",
"}",
"$",
"cipherOptions",
"[",
"'Iv'",
"]",
"=",
"$",
"provider",
"->",
"generateIv",
"(",
"$",
"this",
"->",
"getCipherOpenSslName",
"(",
"$",
"cipherOptions",
"[",
"'Cipher'",
"]",
",",
"$",
"cipherOptions",
"[",
"'KeySize'",
"]",
")",
")",
";",
"$",
"cek",
"=",
"$",
"provider",
"->",
"generateCek",
"(",
"$",
"cipherOptions",
"[",
"'KeySize'",
"]",
")",
";",
"list",
"(",
"$",
"encryptingStream",
",",
"$",
"aesName",
")",
"=",
"$",
"this",
"->",
"getEncryptingStream",
"(",
"$",
"plaintext",
",",
"$",
"cek",
",",
"$",
"cipherOptions",
")",
";",
"// Populate envelope data",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"CONTENT_KEY_V2_HEADER",
"]",
"=",
"$",
"provider",
"->",
"encryptCek",
"(",
"$",
"cek",
",",
"$",
"materialsDescription",
")",
";",
"unset",
"(",
"$",
"cek",
")",
";",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"IV_HEADER",
"]",
"=",
"base64_encode",
"(",
"$",
"cipherOptions",
"[",
"'Iv'",
"]",
")",
";",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"KEY_WRAP_ALGORITHM_HEADER",
"]",
"=",
"$",
"provider",
"->",
"getWrapAlgorithmName",
"(",
")",
";",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"CONTENT_CRYPTO_SCHEME_HEADER",
"]",
"=",
"$",
"aesName",
";",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"UNENCRYPTED_CONTENT_LENGTH_HEADER",
"]",
"=",
"strlen",
"(",
"$",
"plaintext",
")",
";",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"UNENCRYPTED_CONTENT_MD5_HEADER",
"]",
"=",
"base64_encode",
"(",
"md5",
"(",
"$",
"plaintext",
")",
")",
";",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"MATERIALS_DESCRIPTION_HEADER",
"]",
"=",
"json_encode",
"(",
"$",
"materialsDescription",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"cipherOptions",
"[",
"'Tag'",
"]",
")",
")",
"{",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"CRYPTO_TAG_LENGTH_HEADER",
"]",
"=",
"strlen",
"(",
"$",
"cipherOptions",
"[",
"'Tag'",
"]",
")",
"*",
"8",
";",
"}",
"return",
"$",
"encryptingStream",
";",
"}"
] | Builds an AesStreamInterface and populates encryption metadata into the
supplied envelope.
@param Stream $plaintext Plain-text data to be encrypted using the
materials, algorithm, and data provided.
@param array $cipherOptions Options for use in determining the cipher to
be used for encrypting data.
@param MaterialsProvider $provider A provider to supply and encrypt
materials used in encryption.
@param MetadataEnvelope $envelope A storage envelope for encryption
metadata to be added to.
@return AesStreamInterface
@throws \InvalidArgumentException Thrown when a value in $cipherOptions
is not valid.
@internal | [
"Builds",
"an",
"AesStreamInterface",
"and",
"populates",
"encryption",
"metadata",
"into",
"the",
"supplied",
"envelope",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Crypto/EncryptionTrait.php#L51-L129 | train |
aws/aws-sdk-php | src/Endpoint/PartitionEndpointProvider.php | PartitionEndpointProvider.getPartition | public function getPartition($region, $service)
{
foreach ($this->partitions as $partition) {
if ($partition->isRegionMatch($region, $service)) {
return $partition;
}
}
return $this->getPartitionByName($this->defaultPartition);
} | php | public function getPartition($region, $service)
{
foreach ($this->partitions as $partition) {
if ($partition->isRegionMatch($region, $service)) {
return $partition;
}
}
return $this->getPartitionByName($this->defaultPartition);
} | [
"public",
"function",
"getPartition",
"(",
"$",
"region",
",",
"$",
"service",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"partitions",
"as",
"$",
"partition",
")",
"{",
"if",
"(",
"$",
"partition",
"->",
"isRegionMatch",
"(",
"$",
"region",
",",
"$",
"service",
")",
")",
"{",
"return",
"$",
"partition",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"getPartitionByName",
"(",
"$",
"this",
"->",
"defaultPartition",
")",
";",
"}"
] | Returns the partition containing the provided region or the default
partition if no match is found.
@param string $region
@param string $service
@return Partition | [
"Returns",
"the",
"partition",
"containing",
"the",
"provided",
"region",
"or",
"the",
"default",
"partition",
"if",
"no",
"match",
"is",
"found",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Endpoint/PartitionEndpointProvider.php#L40-L49 | train |
aws/aws-sdk-php | src/Endpoint/PartitionEndpointProvider.php | PartitionEndpointProvider.getPartitionByName | public function getPartitionByName($name)
{
foreach ($this->partitions as $partition) {
if ($name === $partition->getName()) {
return $partition;
}
}
} | php | public function getPartitionByName($name)
{
foreach ($this->partitions as $partition) {
if ($name === $partition->getName()) {
return $partition;
}
}
} | [
"public",
"function",
"getPartitionByName",
"(",
"$",
"name",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"partitions",
"as",
"$",
"partition",
")",
"{",
"if",
"(",
"$",
"name",
"===",
"$",
"partition",
"->",
"getName",
"(",
")",
")",
"{",
"return",
"$",
"partition",
";",
"}",
"}",
"}"
] | Returns the partition with the provided name or null if no partition with
the provided name can be found.
@param string $name
@return Partition|null | [
"Returns",
"the",
"partition",
"with",
"the",
"provided",
"name",
"or",
"null",
"if",
"no",
"partition",
"with",
"the",
"provided",
"name",
"can",
"be",
"found",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Endpoint/PartitionEndpointProvider.php#L59-L66 | train |
aws/aws-sdk-php | src/Endpoint/PartitionEndpointProvider.php | PartitionEndpointProvider.mergePrefixData | public static function mergePrefixData($data, $prefixData)
{
$prefixGroups = $prefixData['prefix-groups'];
foreach ($data["partitions"] as $index => $partition) {
foreach ($prefixGroups as $current => $old) {
$serviceData = Env::search("services.{$current}", $partition);
if (!empty($serviceData)) {
foreach ($old as $prefix) {
if (empty(Env::search("services.{$prefix}", $partition))) {
$data["partitions"][$index]["services"][$prefix] = $serviceData;
}
}
}
}
}
return $data;
} | php | public static function mergePrefixData($data, $prefixData)
{
$prefixGroups = $prefixData['prefix-groups'];
foreach ($data["partitions"] as $index => $partition) {
foreach ($prefixGroups as $current => $old) {
$serviceData = Env::search("services.{$current}", $partition);
if (!empty($serviceData)) {
foreach ($old as $prefix) {
if (empty(Env::search("services.{$prefix}", $partition))) {
$data["partitions"][$index]["services"][$prefix] = $serviceData;
}
}
}
}
}
return $data;
} | [
"public",
"static",
"function",
"mergePrefixData",
"(",
"$",
"data",
",",
"$",
"prefixData",
")",
"{",
"$",
"prefixGroups",
"=",
"$",
"prefixData",
"[",
"'prefix-groups'",
"]",
";",
"foreach",
"(",
"$",
"data",
"[",
"\"partitions\"",
"]",
"as",
"$",
"index",
"=>",
"$",
"partition",
")",
"{",
"foreach",
"(",
"$",
"prefixGroups",
"as",
"$",
"current",
"=>",
"$",
"old",
")",
"{",
"$",
"serviceData",
"=",
"Env",
"::",
"search",
"(",
"\"services.{$current}\"",
",",
"$",
"partition",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"serviceData",
")",
")",
"{",
"foreach",
"(",
"$",
"old",
"as",
"$",
"prefix",
")",
"{",
"if",
"(",
"empty",
"(",
"Env",
"::",
"search",
"(",
"\"services.{$prefix}\"",
",",
"$",
"partition",
")",
")",
")",
"{",
"$",
"data",
"[",
"\"partitions\"",
"]",
"[",
"$",
"index",
"]",
"[",
"\"services\"",
"]",
"[",
"$",
"prefix",
"]",
"=",
"$",
"serviceData",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"$",
"data",
";",
"}"
] | Copy endpoint data for other prefixes used by a given service
@param $data
@param $prefixData
@return array | [
"Copy",
"endpoint",
"data",
"for",
"other",
"prefixes",
"used",
"by",
"a",
"given",
"service"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Endpoint/PartitionEndpointProvider.php#L89-L107 | train |
aws/aws-sdk-php | src/Credentials/CredentialProvider.php | CredentialProvider.env | 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) ?: NULL)
);
}
return self::reject('Could not find environment variable '
. 'credentials in ' . self::ENV_KEY . '/' . self::ENV_SECRET);
};
} | php | 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) ?: NULL)
);
}
return self::reject('Could not find environment variable '
. 'credentials in ' . self::ENV_KEY . '/' . self::ENV_SECRET);
};
} | [
"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",
")",
"?",
":",
"NULL",
")",
")",
";",
"}",
"return",
"self",
"::",
"reject",
"(",
"'Could not find environment variable '",
".",
"'credentials in '",
".",
"self",
"::",
"ENV_KEY",
".",
"'/'",
".",
"self",
"::",
"ENV_SECRET",
")",
";",
"}",
";",
"}"
] | Provider that creates credentials from environment variables
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN.
@return callable | [
"Provider",
"that",
"creates",
"credentials",
"from",
"environment",
"variables",
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY",
"and",
"AWS_SESSION_TOKEN",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Credentials/CredentialProvider.php#L222-L237 | train |
aws/aws-sdk-php | src/Credentials/CredentialProvider.php | CredentialProvider.ini | 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 = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
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']
)
);
};
} | php | 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 = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
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']
)
);
};
} | [
"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",
"=",
"\\",
"Aws",
"\\",
"parse_ini_file",
"(",
"$",
"filename",
",",
"true",
",",
"INI_SCANNER_RAW",
")",
";",
"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'",
"]",
")",
")",
";",
"}",
";",
"}"
] | 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 in "~/.aws/credentials".
@param string|null $filename If provided, uses a custom filename rather
than looking in the home directory.
@return callable | [
"Credentials",
"provider",
"that",
"creates",
"credentials",
"using",
"an",
"ini",
"file",
"stored",
"in",
"the",
"current",
"user",
"s",
"home",
"directory",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Credentials/CredentialProvider.php#L291-L329 | train |
aws/aws-sdk-php | src/Credentials/CredentialProvider.php | CredentialProvider.process | public static function process($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 process credentials from $filename");
}
$data = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
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]['credential_process'])
) {
return self::reject("No credential_process present in INI profile "
. "'$profile' ($filename)");
}
$credentialProcess = $data[$profile]['credential_process'];
$json = shell_exec($credentialProcess);
$processData = json_decode($json, true);
// Only support version 1
if (isset($processData['Version'])) {
if ($processData['Version'] !== 1) {
return self::reject("credential_process does not return Version == 1");
}
}
if (!isset($processData['AccessKeyId']) || !isset($processData['SecretAccessKey'])) {
return self::reject("credential_process does not return valid credentials");
}
if (isset($processData['Expiration'])) {
try {
$expiration = new DateTimeResult($processData['Expiration']);
} catch (\Exception $e) {
return self::reject("credential_process returned invalid expiration");
}
$now = new DateTimeResult();
if ($expiration < $now) {
return self::reject("credential_process returned expired credentials");
}
} else {
$processData['Expiration'] = null;
}
if (empty($processData['SessionToken'])) {
$processData['SessionToken'] = null;
}
return Promise\promise_for(
new Credentials(
$processData['AccessKeyId'],
$processData['SecretAccessKey'],
$processData['SessionToken'],
$processData['Expiration']
)
);
};
} | php | public static function process($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 process credentials from $filename");
}
$data = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
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]['credential_process'])
) {
return self::reject("No credential_process present in INI profile "
. "'$profile' ($filename)");
}
$credentialProcess = $data[$profile]['credential_process'];
$json = shell_exec($credentialProcess);
$processData = json_decode($json, true);
// Only support version 1
if (isset($processData['Version'])) {
if ($processData['Version'] !== 1) {
return self::reject("credential_process does not return Version == 1");
}
}
if (!isset($processData['AccessKeyId']) || !isset($processData['SecretAccessKey'])) {
return self::reject("credential_process does not return valid credentials");
}
if (isset($processData['Expiration'])) {
try {
$expiration = new DateTimeResult($processData['Expiration']);
} catch (\Exception $e) {
return self::reject("credential_process returned invalid expiration");
}
$now = new DateTimeResult();
if ($expiration < $now) {
return self::reject("credential_process returned expired credentials");
}
} else {
$processData['Expiration'] = null;
}
if (empty($processData['SessionToken'])) {
$processData['SessionToken'] = null;
}
return Promise\promise_for(
new Credentials(
$processData['AccessKeyId'],
$processData['SecretAccessKey'],
$processData['SessionToken'],
$processData['Expiration']
)
);
};
} | [
"public",
"static",
"function",
"process",
"(",
"$",
"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 process credentials from $filename\"",
")",
";",
"}",
"$",
"data",
"=",
"\\",
"Aws",
"\\",
"parse_ini_file",
"(",
"$",
"filename",
",",
"true",
",",
"INI_SCANNER_RAW",
")",
";",
"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",
"]",
"[",
"'credential_process'",
"]",
")",
")",
"{",
"return",
"self",
"::",
"reject",
"(",
"\"No credential_process present in INI profile \"",
".",
"\"'$profile' ($filename)\"",
")",
";",
"}",
"$",
"credentialProcess",
"=",
"$",
"data",
"[",
"$",
"profile",
"]",
"[",
"'credential_process'",
"]",
";",
"$",
"json",
"=",
"shell_exec",
"(",
"$",
"credentialProcess",
")",
";",
"$",
"processData",
"=",
"json_decode",
"(",
"$",
"json",
",",
"true",
")",
";",
"// Only support version 1",
"if",
"(",
"isset",
"(",
"$",
"processData",
"[",
"'Version'",
"]",
")",
")",
"{",
"if",
"(",
"$",
"processData",
"[",
"'Version'",
"]",
"!==",
"1",
")",
"{",
"return",
"self",
"::",
"reject",
"(",
"\"credential_process does not return Version == 1\"",
")",
";",
"}",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"processData",
"[",
"'AccessKeyId'",
"]",
")",
"||",
"!",
"isset",
"(",
"$",
"processData",
"[",
"'SecretAccessKey'",
"]",
")",
")",
"{",
"return",
"self",
"::",
"reject",
"(",
"\"credential_process does not return valid credentials\"",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"processData",
"[",
"'Expiration'",
"]",
")",
")",
"{",
"try",
"{",
"$",
"expiration",
"=",
"new",
"DateTimeResult",
"(",
"$",
"processData",
"[",
"'Expiration'",
"]",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
"self",
"::",
"reject",
"(",
"\"credential_process returned invalid expiration\"",
")",
";",
"}",
"$",
"now",
"=",
"new",
"DateTimeResult",
"(",
")",
";",
"if",
"(",
"$",
"expiration",
"<",
"$",
"now",
")",
"{",
"return",
"self",
"::",
"reject",
"(",
"\"credential_process returned expired credentials\"",
")",
";",
"}",
"}",
"else",
"{",
"$",
"processData",
"[",
"'Expiration'",
"]",
"=",
"null",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"processData",
"[",
"'SessionToken'",
"]",
")",
")",
"{",
"$",
"processData",
"[",
"'SessionToken'",
"]",
"=",
"null",
";",
"}",
"return",
"Promise",
"\\",
"promise_for",
"(",
"new",
"Credentials",
"(",
"$",
"processData",
"[",
"'AccessKeyId'",
"]",
",",
"$",
"processData",
"[",
"'SecretAccessKey'",
"]",
",",
"$",
"processData",
"[",
"'SessionToken'",
"]",
",",
"$",
"processData",
"[",
"'Expiration'",
"]",
")",
")",
";",
"}",
";",
"}"
] | Credentials provider that creates credentials using a process configured in
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 in "~/.aws/credentials".
@param string|null $filename If provided, uses a custom filename rather
than looking in the home directory.
@return callable | [
"Credentials",
"provider",
"that",
"creates",
"credentials",
"using",
"a",
"process",
"configured",
"in",
"ini",
"file",
"stored",
"in",
"the",
"current",
"user",
"s",
"home",
"directory",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Credentials/CredentialProvider.php#L342-L407 | train |
aws/aws-sdk-php | src/Middleware.php | Middleware.requestBuilder | public static function requestBuilder(callable $serializer)
{
return function (callable $handler) use ($serializer) {
return function (CommandInterface $command) use ($serializer, $handler) {
return $handler($command, $serializer($command));
};
};
} | php | public static function requestBuilder(callable $serializer)
{
return function (callable $handler) use ($serializer) {
return function (CommandInterface $command) use ($serializer, $handler) {
return $handler($command, $serializer($command));
};
};
} | [
"public",
"static",
"function",
"requestBuilder",
"(",
"callable",
"$",
"serializer",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"serializer",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
")",
"use",
"(",
"$",
"serializer",
",",
"$",
"handler",
")",
"{",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"serializer",
"(",
"$",
"command",
")",
")",
";",
"}",
";",
"}",
";",
"}"
] | Builds an HTTP request for a command.
@param callable $serializer Function used to serialize a request for a
command.
@return callable | [
"Builds",
"an",
"HTTP",
"request",
"for",
"a",
"command",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Middleware.php#L92-L99 | train |
aws/aws-sdk-php | src/Middleware.php | Middleware.signer | public static function signer(callable $credProvider, callable $signatureFunction)
{
return function (callable $handler) use ($signatureFunction, $credProvider) {
return function (
CommandInterface $command,
RequestInterface $request
) use ($handler, $signatureFunction, $credProvider) {
$signer = $signatureFunction($command);
return $credProvider()->then(
function (CredentialsInterface $creds)
use ($handler, $command, $signer, $request) {
return $handler(
$command,
$signer->signRequest($request, $creds)
);
}
);
};
};
} | php | public static function signer(callable $credProvider, callable $signatureFunction)
{
return function (callable $handler) use ($signatureFunction, $credProvider) {
return function (
CommandInterface $command,
RequestInterface $request
) use ($handler, $signatureFunction, $credProvider) {
$signer = $signatureFunction($command);
return $credProvider()->then(
function (CredentialsInterface $creds)
use ($handler, $command, $signer, $request) {
return $handler(
$command,
$signer->signRequest($request, $creds)
);
}
);
};
};
} | [
"public",
"static",
"function",
"signer",
"(",
"callable",
"$",
"credProvider",
",",
"callable",
"$",
"signatureFunction",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"signatureFunction",
",",
"$",
"credProvider",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
")",
"use",
"(",
"$",
"handler",
",",
"$",
"signatureFunction",
",",
"$",
"credProvider",
")",
"{",
"$",
"signer",
"=",
"$",
"signatureFunction",
"(",
"$",
"command",
")",
";",
"return",
"$",
"credProvider",
"(",
")",
"->",
"then",
"(",
"function",
"(",
"CredentialsInterface",
"$",
"creds",
")",
"use",
"(",
"$",
"handler",
",",
"$",
"command",
",",
"$",
"signer",
",",
"$",
"request",
")",
"{",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"signer",
"->",
"signRequest",
"(",
"$",
"request",
",",
"$",
"creds",
")",
")",
";",
"}",
")",
";",
"}",
";",
"}",
";",
"}"
] | Creates a middleware that signs requests for a command.
@param callable $credProvider Credentials provider function that
returns a promise that is resolved
with a CredentialsInterface object.
@param callable $signatureFunction Function that accepts a Command
object and returns a
SignatureInterface.
@return callable | [
"Creates",
"a",
"middleware",
"that",
"signs",
"requests",
"for",
"a",
"command",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Middleware.php#L113-L132 | train |
aws/aws-sdk-php | src/Middleware.php | Middleware.tap | public static function tap(callable $fn)
{
return function (callable $handler) use ($fn) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $fn) {
$fn($command, $request);
return $handler($command, $request);
};
};
} | php | public static function tap(callable $fn)
{
return function (callable $handler) use ($fn) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $fn) {
$fn($command, $request);
return $handler($command, $request);
};
};
} | [
"public",
"static",
"function",
"tap",
"(",
"callable",
"$",
"fn",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"fn",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
",",
"$",
"fn",
")",
"{",
"$",
"fn",
"(",
"$",
"command",
",",
"$",
"request",
")",
";",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
")",
";",
"}",
";",
"}",
";",
"}"
] | Creates a middleware that invokes a callback at a given step.
The tap callback accepts a CommandInterface and RequestInterface as
arguments but is not expected to return a new value or proxy to
downstream middleware. It's simply a way to "tap" into the handler chain
to debug or get an intermediate value.
@param callable $fn Tap function
@return callable | [
"Creates",
"a",
"middleware",
"that",
"invokes",
"a",
"callback",
"at",
"a",
"given",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Middleware.php#L146-L157 | train |
aws/aws-sdk-php | src/Middleware.php | Middleware.invocationId | public static function invocationId()
{
return function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request
) use ($handler){
return $handler($command, $request->withHeader(
'aws-sdk-invocation-id',
md5(uniqid(gethostname(), true))
));
};
};
} | php | public static function invocationId()
{
return function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request
) use ($handler){
return $handler($command, $request->withHeader(
'aws-sdk-invocation-id',
md5(uniqid(gethostname(), true))
));
};
};
} | [
"public",
"static",
"function",
"invocationId",
"(",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
")",
"use",
"(",
"$",
"handler",
")",
"{",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
"->",
"withHeader",
"(",
"'aws-sdk-invocation-id'",
",",
"md5",
"(",
"uniqid",
"(",
"gethostname",
"(",
")",
",",
"true",
")",
")",
")",
")",
";",
"}",
";",
"}",
";",
"}"
] | Middleware wrapper function that adds an invocation id header to
requests, which is only applied after the build step.
This is a uniquely generated UUID to identify initial and subsequent
retries as part of a complete request lifecycle.
@return callable | [
"Middleware",
"wrapper",
"function",
"that",
"adds",
"an",
"invocation",
"id",
"header",
"to",
"requests",
"which",
"is",
"only",
"applied",
"after",
"the",
"build",
"step",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Middleware.php#L197-L210 | train |
aws/aws-sdk-php | src/Middleware.php | Middleware.contentType | public static function contentType(array $operations)
{
return function (callable $handler) use ($operations) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $operations) {
if (!$request->hasHeader('Content-Type')
&& in_array($command->getName(), $operations, true)
&& ($uri = $request->getBody()->getMetadata('uri'))
) {
$request = $request->withHeader(
'Content-Type',
Psr7\mimetype_from_filename($uri) ?: 'application/octet-stream'
);
}
return $handler($command, $request);
};
};
} | php | public static function contentType(array $operations)
{
return function (callable $handler) use ($operations) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $operations) {
if (!$request->hasHeader('Content-Type')
&& in_array($command->getName(), $operations, true)
&& ($uri = $request->getBody()->getMetadata('uri'))
) {
$request = $request->withHeader(
'Content-Type',
Psr7\mimetype_from_filename($uri) ?: 'application/octet-stream'
);
}
return $handler($command, $request);
};
};
} | [
"public",
"static",
"function",
"contentType",
"(",
"array",
"$",
"operations",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"operations",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
",",
"$",
"operations",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"hasHeader",
"(",
"'Content-Type'",
")",
"&&",
"in_array",
"(",
"$",
"command",
"->",
"getName",
"(",
")",
",",
"$",
"operations",
",",
"true",
")",
"&&",
"(",
"$",
"uri",
"=",
"$",
"request",
"->",
"getBody",
"(",
")",
"->",
"getMetadata",
"(",
"'uri'",
")",
")",
")",
"{",
"$",
"request",
"=",
"$",
"request",
"->",
"withHeader",
"(",
"'Content-Type'",
",",
"Psr7",
"\\",
"mimetype_from_filename",
"(",
"$",
"uri",
")",
"?",
":",
"'application/octet-stream'",
")",
";",
"}",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
")",
";",
"}",
";",
"}",
";",
"}"
] | Middleware wrapper function that adds a Content-Type header to requests.
This is only done when the Content-Type has not already been set, and the
request body's URI is available. It then checks the file extension of the
URI to determine the mime-type.
@param array $operations Operations that Content-Type should be added to.
@return callable | [
"Middleware",
"wrapper",
"function",
"that",
"adds",
"a",
"Content",
"-",
"Type",
"header",
"to",
"requests",
".",
"This",
"is",
"only",
"done",
"when",
"the",
"Content",
"-",
"Type",
"has",
"not",
"already",
"been",
"set",
"and",
"the",
"request",
"body",
"s",
"URI",
"is",
"available",
".",
"It",
"then",
"checks",
"the",
"file",
"extension",
"of",
"the",
"URI",
"to",
"determine",
"the",
"mime",
"-",
"type",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Middleware.php#L221-L241 | train |
aws/aws-sdk-php | src/Middleware.php | Middleware.history | public static function history(History $history)
{
return function (callable $handler) use ($history) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $history) {
$ticket = $history->start($command, $request);
return $handler($command, $request)
->then(
function ($result) use ($history, $ticket) {
$history->finish($ticket, $result);
return $result;
},
function ($reason) use ($history, $ticket) {
$history->finish($ticket, $reason);
return Promise\rejection_for($reason);
}
);
};
};
} | php | public static function history(History $history)
{
return function (callable $handler) use ($history) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $history) {
$ticket = $history->start($command, $request);
return $handler($command, $request)
->then(
function ($result) use ($history, $ticket) {
$history->finish($ticket, $result);
return $result;
},
function ($reason) use ($history, $ticket) {
$history->finish($ticket, $reason);
return Promise\rejection_for($reason);
}
);
};
};
} | [
"public",
"static",
"function",
"history",
"(",
"History",
"$",
"history",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"history",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
",",
"$",
"history",
")",
"{",
"$",
"ticket",
"=",
"$",
"history",
"->",
"start",
"(",
"$",
"command",
",",
"$",
"request",
")",
";",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
")",
"->",
"then",
"(",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"$",
"history",
",",
"$",
"ticket",
")",
"{",
"$",
"history",
"->",
"finish",
"(",
"$",
"ticket",
",",
"$",
"result",
")",
";",
"return",
"$",
"result",
";",
"}",
",",
"function",
"(",
"$",
"reason",
")",
"use",
"(",
"$",
"history",
",",
"$",
"ticket",
")",
"{",
"$",
"history",
"->",
"finish",
"(",
"$",
"ticket",
",",
"$",
"reason",
")",
";",
"return",
"Promise",
"\\",
"rejection_for",
"(",
"$",
"reason",
")",
";",
"}",
")",
";",
"}",
";",
"}",
";",
"}"
] | Tracks command and request history using a history container.
This is useful for testing.
@param History $history History container to store entries.
@return callable | [
"Tracks",
"command",
"and",
"request",
"history",
"using",
"a",
"history",
"container",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Middleware.php#L252-L273 | train |
aws/aws-sdk-php | src/Middleware.php | Middleware.mapRequest | public static function mapRequest(callable $f)
{
return function (callable $handler) use ($f) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $f) {
return $handler($command, $f($request));
};
};
} | php | public static function mapRequest(callable $f)
{
return function (callable $handler) use ($f) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $f) {
return $handler($command, $f($request));
};
};
} | [
"public",
"static",
"function",
"mapRequest",
"(",
"callable",
"$",
"f",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"f",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
",",
"$",
"f",
")",
"{",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"f",
"(",
"$",
"request",
")",
")",
";",
"}",
";",
"}",
";",
"}"
] | Creates a middleware that applies a map function to requests as they
pass through the middleware.
@param callable $f Map function that accepts a RequestInterface and
returns a RequestInterface.
@return callable | [
"Creates",
"a",
"middleware",
"that",
"applies",
"a",
"map",
"function",
"to",
"requests",
"as",
"they",
"pass",
"through",
"the",
"middleware",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Middleware.php#L284-L294 | train |
aws/aws-sdk-php | src/Middleware.php | Middleware.mapCommand | public static function mapCommand(callable $f)
{
return function (callable $handler) use ($f) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $f) {
return $handler($f($command), $request);
};
};
} | php | public static function mapCommand(callable $f)
{
return function (callable $handler) use ($f) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $f) {
return $handler($f($command), $request);
};
};
} | [
"public",
"static",
"function",
"mapCommand",
"(",
"callable",
"$",
"f",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"f",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
",",
"$",
"f",
")",
"{",
"return",
"$",
"handler",
"(",
"$",
"f",
"(",
"$",
"command",
")",
",",
"$",
"request",
")",
";",
"}",
";",
"}",
";",
"}"
] | Creates a middleware that applies a map function to commands as they
pass through the middleware.
@param callable $f Map function that accepts a command and returns a
command.
@return callable | [
"Creates",
"a",
"middleware",
"that",
"applies",
"a",
"map",
"function",
"to",
"commands",
"as",
"they",
"pass",
"through",
"the",
"middleware",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Middleware.php#L305-L315 | train |
aws/aws-sdk-php | src/Middleware.php | Middleware.mapResult | public static function mapResult(callable $f)
{
return function (callable $handler) use ($f) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $f) {
return $handler($command, $request)->then($f);
};
};
} | php | public static function mapResult(callable $f)
{
return function (callable $handler) use ($f) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $f) {
return $handler($command, $request)->then($f);
};
};
} | [
"public",
"static",
"function",
"mapResult",
"(",
"callable",
"$",
"f",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"f",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
",",
"$",
"f",
")",
"{",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
")",
"->",
"then",
"(",
"$",
"f",
")",
";",
"}",
";",
"}",
";",
"}"
] | Creates a middleware that applies a map function to results.
@param callable $f Map function that accepts an Aws\ResultInterface and
returns an Aws\ResultInterface.
@return callable | [
"Creates",
"a",
"middleware",
"that",
"applies",
"a",
"map",
"function",
"to",
"results",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Middleware.php#L325-L335 | train |
aws/aws-sdk-php | src/Multipart/AbstractUploadManager.php | AbstractUploadManager.determineState | private function determineState()
{
// If the state was provided via config, then just use it.
if ($this->config['state'] instanceof UploadState) {
return $this->config['state'];
}
// Otherwise, construct a new state from the provided identifiers.
$required = $this->info['id'];
$id = [$required['upload_id'] => null];
unset($required['upload_id']);
foreach ($required as $key => $param) {
if (!$this->config[$key]) {
throw new IAE('You must provide a value for "' . $key . '" in '
. 'your config for the MultipartUploader for '
. $this->client->getApi()->getServiceFullName() . '.');
}
$id[$param] = $this->config[$key];
}
$state = new UploadState($id);
$state->setPartSize($this->determinePartSize());
return $state;
} | php | private function determineState()
{
// If the state was provided via config, then just use it.
if ($this->config['state'] instanceof UploadState) {
return $this->config['state'];
}
// Otherwise, construct a new state from the provided identifiers.
$required = $this->info['id'];
$id = [$required['upload_id'] => null];
unset($required['upload_id']);
foreach ($required as $key => $param) {
if (!$this->config[$key]) {
throw new IAE('You must provide a value for "' . $key . '" in '
. 'your config for the MultipartUploader for '
. $this->client->getApi()->getServiceFullName() . '.');
}
$id[$param] = $this->config[$key];
}
$state = new UploadState($id);
$state->setPartSize($this->determinePartSize());
return $state;
} | [
"private",
"function",
"determineState",
"(",
")",
"{",
"// If the state was provided via config, then just use it.",
"if",
"(",
"$",
"this",
"->",
"config",
"[",
"'state'",
"]",
"instanceof",
"UploadState",
")",
"{",
"return",
"$",
"this",
"->",
"config",
"[",
"'state'",
"]",
";",
"}",
"// Otherwise, construct a new state from the provided identifiers.",
"$",
"required",
"=",
"$",
"this",
"->",
"info",
"[",
"'id'",
"]",
";",
"$",
"id",
"=",
"[",
"$",
"required",
"[",
"'upload_id'",
"]",
"=>",
"null",
"]",
";",
"unset",
"(",
"$",
"required",
"[",
"'upload_id'",
"]",
")",
";",
"foreach",
"(",
"$",
"required",
"as",
"$",
"key",
"=>",
"$",
"param",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"config",
"[",
"$",
"key",
"]",
")",
"{",
"throw",
"new",
"IAE",
"(",
"'You must provide a value for \"'",
".",
"$",
"key",
".",
"'\" in '",
".",
"'your config for the MultipartUploader for '",
".",
"$",
"this",
"->",
"client",
"->",
"getApi",
"(",
")",
"->",
"getServiceFullName",
"(",
")",
".",
"'.'",
")",
";",
"}",
"$",
"id",
"[",
"$",
"param",
"]",
"=",
"$",
"this",
"->",
"config",
"[",
"$",
"key",
"]",
";",
"}",
"$",
"state",
"=",
"new",
"UploadState",
"(",
"$",
"id",
")",
";",
"$",
"state",
"->",
"setPartSize",
"(",
"$",
"this",
"->",
"determinePartSize",
"(",
")",
")",
";",
"return",
"$",
"state",
";",
"}"
] | Based on the config and service-specific workflow info, creates a
`Promise` for an `UploadState` object.
@return PromiseInterface A `Promise` that resolves to an `UploadState`. | [
"Based",
"on",
"the",
"config",
"and",
"service",
"-",
"specific",
"workflow",
"info",
"creates",
"a",
"Promise",
"for",
"an",
"UploadState",
"object",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Multipart/AbstractUploadManager.php#L224-L247 | train |
aws/aws-sdk-php | src/S3/S3ClientTrait.php | S3ClientTrait.checkExistenceWithCommand | private function checkExistenceWithCommand(CommandInterface $command)
{
try {
$this->execute($command);
return true;
} catch (S3Exception $e) {
if ($e->getAwsErrorCode() == 'AccessDenied') {
return true;
}
if ($e->getStatusCode() >= 500) {
throw $e;
}
return false;
}
} | php | private function checkExistenceWithCommand(CommandInterface $command)
{
try {
$this->execute($command);
return true;
} catch (S3Exception $e) {
if ($e->getAwsErrorCode() == 'AccessDenied') {
return true;
}
if ($e->getStatusCode() >= 500) {
throw $e;
}
return false;
}
} | [
"private",
"function",
"checkExistenceWithCommand",
"(",
"CommandInterface",
"$",
"command",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"execute",
"(",
"$",
"command",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"S3Exception",
"$",
"e",
")",
"{",
"if",
"(",
"$",
"e",
"->",
"getAwsErrorCode",
"(",
")",
"==",
"'AccessDenied'",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"$",
"e",
"->",
"getStatusCode",
"(",
")",
">=",
"500",
")",
"{",
"throw",
"$",
"e",
";",
"}",
"return",
"false",
";",
"}",
"}"
] | Determines whether or not a resource exists using a command
@param CommandInterface $command Command used to poll for the resource
@return bool
@throws S3Exception|\Exception if there is an unhandled exception | [
"Determines",
"whether",
"or",
"not",
"a",
"resource",
"exists",
"using",
"a",
"command"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/S3ClientTrait.php#L284-L298 | train |
aws/aws-sdk-php | src/Glacier/MultipartUploader.php | MultipartUploader.decorateWithHashes | private function decorateWithHashes(Stream $stream, array &$data)
{
// Make sure that a tree hash is calculated.
$stream = new HashingStream($stream, new TreeHash(),
function ($result) use (&$data) {
$data['checksum'] = bin2hex($result);
}
);
// Make sure that a linear SHA256 hash is calculated.
$stream = new HashingStream($stream, new PhpHash('sha256'),
function ($result) use (&$data) {
$data['ContentSHA256'] = bin2hex($result);
}
);
return $stream;
} | php | private function decorateWithHashes(Stream $stream, array &$data)
{
// Make sure that a tree hash is calculated.
$stream = new HashingStream($stream, new TreeHash(),
function ($result) use (&$data) {
$data['checksum'] = bin2hex($result);
}
);
// Make sure that a linear SHA256 hash is calculated.
$stream = new HashingStream($stream, new PhpHash('sha256'),
function ($result) use (&$data) {
$data['ContentSHA256'] = bin2hex($result);
}
);
return $stream;
} | [
"private",
"function",
"decorateWithHashes",
"(",
"Stream",
"$",
"stream",
",",
"array",
"&",
"$",
"data",
")",
"{",
"// Make sure that a tree hash is calculated.",
"$",
"stream",
"=",
"new",
"HashingStream",
"(",
"$",
"stream",
",",
"new",
"TreeHash",
"(",
")",
",",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"&",
"$",
"data",
")",
"{",
"$",
"data",
"[",
"'checksum'",
"]",
"=",
"bin2hex",
"(",
"$",
"result",
")",
";",
"}",
")",
";",
"// Make sure that a linear SHA256 hash is calculated.",
"$",
"stream",
"=",
"new",
"HashingStream",
"(",
"$",
"stream",
",",
"new",
"PhpHash",
"(",
"'sha256'",
")",
",",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"&",
"$",
"data",
")",
"{",
"$",
"data",
"[",
"'ContentSHA256'",
"]",
"=",
"bin2hex",
"(",
"$",
"result",
")",
";",
"}",
")",
";",
"return",
"$",
"stream",
";",
"}"
] | Decorates a stream with a tree AND linear sha256 hashing stream.
@param Stream $stream Stream to decorate.
@param array $data Data bag that results are injected into.
@return Stream | [
"Decorates",
"a",
"stream",
"with",
"a",
"tree",
"AND",
"linear",
"sha256",
"hashing",
"stream",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Glacier/MultipartUploader.php#L241-L258 | train |
aws/aws-sdk-php | src/Glacier/MultipartUploader.php | MultipartUploader.parseRange | private static function parseRange($range, $partSize)
{
// Strip away the prefix and suffix.
if (strpos($range, 'bytes') !== false) {
$range = substr($range, 6, -2);
}
// Split that range into it's parts.
list($firstByte, $lastByte) = explode('-', $range);
// Calculate and return range index and range size
return [
intval($firstByte / $partSize) + 1,
$lastByte - $firstByte + 1,
];
} | php | private static function parseRange($range, $partSize)
{
// Strip away the prefix and suffix.
if (strpos($range, 'bytes') !== false) {
$range = substr($range, 6, -2);
}
// Split that range into it's parts.
list($firstByte, $lastByte) = explode('-', $range);
// Calculate and return range index and range size
return [
intval($firstByte / $partSize) + 1,
$lastByte - $firstByte + 1,
];
} | [
"private",
"static",
"function",
"parseRange",
"(",
"$",
"range",
",",
"$",
"partSize",
")",
"{",
"// Strip away the prefix and suffix.",
"if",
"(",
"strpos",
"(",
"$",
"range",
",",
"'bytes'",
")",
"!==",
"false",
")",
"{",
"$",
"range",
"=",
"substr",
"(",
"$",
"range",
",",
"6",
",",
"-",
"2",
")",
";",
"}",
"// Split that range into it's parts.",
"list",
"(",
"$",
"firstByte",
",",
"$",
"lastByte",
")",
"=",
"explode",
"(",
"'-'",
",",
"$",
"range",
")",
";",
"// Calculate and return range index and range size",
"return",
"[",
"intval",
"(",
"$",
"firstByte",
"/",
"$",
"partSize",
")",
"+",
"1",
",",
"$",
"lastByte",
"-",
"$",
"firstByte",
"+",
"1",
",",
"]",
";",
"}"
] | Parses a Glacier range string into a size and part number.
@param string $range Glacier range string (e.g., "bytes 5-5000/*")
@param int $partSize The chosen part size
@return array | [
"Parses",
"a",
"Glacier",
"range",
"string",
"into",
"a",
"size",
"and",
"part",
"number",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Glacier/MultipartUploader.php#L268-L283 | train |
aws/aws-sdk-php | src/Api/Serializer/JsonBody.php | JsonBody.build | public function build(Shape $shape, array $args)
{
$result = json_encode($this->format($shape, $args));
return $result == '[]' ? '{}' : $result;
} | php | public function build(Shape $shape, array $args)
{
$result = json_encode($this->format($shape, $args));
return $result == '[]' ? '{}' : $result;
} | [
"public",
"function",
"build",
"(",
"Shape",
"$",
"shape",
",",
"array",
"$",
"args",
")",
"{",
"$",
"result",
"=",
"json_encode",
"(",
"$",
"this",
"->",
"format",
"(",
"$",
"shape",
",",
"$",
"args",
")",
")",
";",
"return",
"$",
"result",
"==",
"'[]'",
"?",
"'{}'",
":",
"$",
"result",
";",
"}"
] | 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 | [
"Builds",
"the",
"JSON",
"body",
"based",
"on",
"an",
"array",
"of",
"arguments",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Serializer/JsonBody.php#L42-L47 | train |
aws/aws-sdk-php | src/PhpHash.php | PhpHash.getContext | private function getContext()
{
if (!$this->context) {
$key = isset($this->options['key']) ? $this->options['key'] : null;
$this->context = hash_init(
$this->algo,
$key ? HASH_HMAC : 0,
$key
);
}
return $this->context;
} | php | private function getContext()
{
if (!$this->context) {
$key = isset($this->options['key']) ? $this->options['key'] : null;
$this->context = hash_init(
$this->algo,
$key ? HASH_HMAC : 0,
$key
);
}
return $this->context;
} | [
"private",
"function",
"getContext",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"context",
")",
"{",
"$",
"key",
"=",
"isset",
"(",
"$",
"this",
"->",
"options",
"[",
"'key'",
"]",
")",
"?",
"$",
"this",
"->",
"options",
"[",
"'key'",
"]",
":",
"null",
";",
"$",
"this",
"->",
"context",
"=",
"hash_init",
"(",
"$",
"this",
"->",
"algo",
",",
"$",
"key",
"?",
"HASH_HMAC",
":",
"0",
",",
"$",
"key",
")",
";",
"}",
"return",
"$",
"this",
"->",
"context",
";",
"}"
] | Get a hash context or create one if needed
@return resource|\HashContext | [
"Get",
"a",
"hash",
"context",
"or",
"create",
"one",
"if",
"needed"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/PhpHash.php#L68-L80 | train |
aws/aws-sdk-php | src/Waiter.php | Waiter.getArgsForAttempt | private function getArgsForAttempt($attempt)
{
$args = $this->args;
// Determine the delay.
$delay = ($attempt === 1)
? $this->config['initDelay']
: $this->config['delay'];
if (is_callable($delay)) {
$delay = $delay($attempt);
}
// Set the delay. (Note: handlers except delay in milliseconds.)
if (!isset($args['@http'])) {
$args['@http'] = [];
}
$args['@http']['delay'] = $delay * 1000;
return $args;
} | php | private function getArgsForAttempt($attempt)
{
$args = $this->args;
// Determine the delay.
$delay = ($attempt === 1)
? $this->config['initDelay']
: $this->config['delay'];
if (is_callable($delay)) {
$delay = $delay($attempt);
}
// Set the delay. (Note: handlers except delay in milliseconds.)
if (!isset($args['@http'])) {
$args['@http'] = [];
}
$args['@http']['delay'] = $delay * 1000;
return $args;
} | [
"private",
"function",
"getArgsForAttempt",
"(",
"$",
"attempt",
")",
"{",
"$",
"args",
"=",
"$",
"this",
"->",
"args",
";",
"// Determine the delay.",
"$",
"delay",
"=",
"(",
"$",
"attempt",
"===",
"1",
")",
"?",
"$",
"this",
"->",
"config",
"[",
"'initDelay'",
"]",
":",
"$",
"this",
"->",
"config",
"[",
"'delay'",
"]",
";",
"if",
"(",
"is_callable",
"(",
"$",
"delay",
")",
")",
"{",
"$",
"delay",
"=",
"$",
"delay",
"(",
"$",
"attempt",
")",
";",
"}",
"// Set the delay. (Note: handlers except delay in milliseconds.)",
"if",
"(",
"!",
"isset",
"(",
"$",
"args",
"[",
"'@http'",
"]",
")",
")",
"{",
"$",
"args",
"[",
"'@http'",
"]",
"=",
"[",
"]",
";",
"}",
"$",
"args",
"[",
"'@http'",
"]",
"[",
"'delay'",
"]",
"=",
"$",
"delay",
"*",
"1000",
";",
"return",
"$",
"args",
";",
"}"
] | Gets the operation arguments for the attempt, including the delay.
@param $attempt Number of the current attempt.
@return mixed integer | [
"Gets",
"the",
"operation",
"arguments",
"for",
"the",
"attempt",
"including",
"the",
"delay",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Waiter.php#L135-L154 | train |
aws/aws-sdk-php | src/Waiter.php | Waiter.determineState | private function determineState($result)
{
foreach ($this->config['acceptors'] as $acceptor) {
$matcher = 'matches' . ucfirst($acceptor['matcher']);
if ($this->{$matcher}($result, $acceptor)) {
return $acceptor['state'];
}
}
return $result instanceof \Exception ? 'failed' : 'retry';
} | php | private function determineState($result)
{
foreach ($this->config['acceptors'] as $acceptor) {
$matcher = 'matches' . ucfirst($acceptor['matcher']);
if ($this->{$matcher}($result, $acceptor)) {
return $acceptor['state'];
}
}
return $result instanceof \Exception ? 'failed' : 'retry';
} | [
"private",
"function",
"determineState",
"(",
"$",
"result",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"config",
"[",
"'acceptors'",
"]",
"as",
"$",
"acceptor",
")",
"{",
"$",
"matcher",
"=",
"'matches'",
".",
"ucfirst",
"(",
"$",
"acceptor",
"[",
"'matcher'",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"{",
"$",
"matcher",
"}",
"(",
"$",
"result",
",",
"$",
"acceptor",
")",
")",
"{",
"return",
"$",
"acceptor",
"[",
"'state'",
"]",
";",
"}",
"}",
"return",
"$",
"result",
"instanceof",
"\\",
"Exception",
"?",
"'failed'",
":",
"'retry'",
";",
"}"
] | Determines the state of the waiter attempt, based on the result of
polling the resource. A waiter can have the state of "success", "failed",
or "retry".
@param mixed $result
@return string Will be "success", "failed", or "retry" | [
"Determines",
"the",
"state",
"of",
"the",
"waiter",
"attempt",
"based",
"on",
"the",
"result",
"of",
"polling",
"the",
"resource",
".",
"A",
"waiter",
"can",
"have",
"the",
"state",
"of",
"success",
"failed",
"or",
"retry",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Waiter.php#L165-L175 | train |
aws/aws-sdk-php | src/S3/Transfer.php | Transfer.promise | public function promise()
{
// If the promise has been created, just return it.
if (!$this->promise) {
// Create an upload/download promise for the transfer.
$this->promise = $this->sourceMetadata['scheme'] === 'file'
? $this->createUploadPromise()
: $this->createDownloadPromise();
}
return $this->promise;
} | php | public function promise()
{
// If the promise has been created, just return it.
if (!$this->promise) {
// Create an upload/download promise for the transfer.
$this->promise = $this->sourceMetadata['scheme'] === 'file'
? $this->createUploadPromise()
: $this->createDownloadPromise();
}
return $this->promise;
} | [
"public",
"function",
"promise",
"(",
")",
"{",
"// If the promise has been created, just return it.",
"if",
"(",
"!",
"$",
"this",
"->",
"promise",
")",
"{",
"// Create an upload/download promise for the transfer.",
"$",
"this",
"->",
"promise",
"=",
"$",
"this",
"->",
"sourceMetadata",
"[",
"'scheme'",
"]",
"===",
"'file'",
"?",
"$",
"this",
"->",
"createUploadPromise",
"(",
")",
":",
"$",
"this",
"->",
"createDownloadPromise",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"promise",
";",
"}"
] | Transfers the files. | [
"Transfers",
"the",
"files",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/Transfer.php#L138-L149 | train |
aws/aws-sdk-php | src/S3/Transfer.php | Transfer.getS3Args | private function getS3Args($path)
{
$parts = explode('/', str_replace('s3://', '', $path), 2);
$args = ['Bucket' => $parts[0]];
if (isset($parts[1])) {
$args['Key'] = $parts[1];
}
return $args;
} | php | private function getS3Args($path)
{
$parts = explode('/', str_replace('s3://', '', $path), 2);
$args = ['Bucket' => $parts[0]];
if (isset($parts[1])) {
$args['Key'] = $parts[1];
}
return $args;
} | [
"private",
"function",
"getS3Args",
"(",
"$",
"path",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'/'",
",",
"str_replace",
"(",
"'s3://'",
",",
"''",
",",
"$",
"path",
")",
",",
"2",
")",
";",
"$",
"args",
"=",
"[",
"'Bucket'",
"=>",
"$",
"parts",
"[",
"0",
"]",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"parts",
"[",
"1",
"]",
")",
")",
"{",
"$",
"args",
"[",
"'Key'",
"]",
"=",
"$",
"parts",
"[",
"1",
"]",
";",
"}",
"return",
"$",
"args",
";",
"}"
] | Creates an array that contains Bucket and Key by parsing the filename.
@param string $path Path to parse.
@return array | [
"Creates",
"an",
"array",
"that",
"contains",
"Bucket",
"and",
"Key",
"by",
"parsing",
"the",
"filename",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/Transfer.php#L180-L189 | train |
aws/aws-sdk-php | src/ClientResolver.php | ClientResolver.resolve | 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.
if (is_callable($a['default'])
&& (
is_array($a['default'])
|| $a['default'] instanceof \Closure
)
) {
$args[$key] = $a['default']($args);
} else {
$args[$key] = $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;
} | php | 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.
if (is_callable($a['default'])
&& (
is_array($a['default'])
|| $a['default'] instanceof \Closure
)
) {
$args[$key] = $a['default']($args);
} else {
$args[$key] = $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;
} | [
"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.",
"if",
"(",
"is_callable",
"(",
"$",
"a",
"[",
"'default'",
"]",
")",
"&&",
"(",
"is_array",
"(",
"$",
"a",
"[",
"'default'",
"]",
")",
"||",
"$",
"a",
"[",
"'default'",
"]",
"instanceof",
"\\",
"Closure",
")",
")",
"{",
"$",
"args",
"[",
"$",
"key",
"]",
"=",
"$",
"a",
"[",
"'default'",
"]",
"(",
"$",
"args",
")",
";",
"}",
"else",
"{",
"$",
"args",
"[",
"$",
"key",
"]",
"=",
"$",
"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",
";",
"}"
] | Resolves client configuration options and attached event listeners.
Check for missing keys in passed arguments
@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. | [
"Resolves",
"client",
"configuration",
"options",
"and",
"attached",
"event",
"listeners",
".",
"Check",
"for",
"missing",
"keys",
"in",
"passed",
"arguments"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientResolver.php#L262-L313 | train |
aws/aws-sdk-php | src/ClientResolver.php | ClientResolver.getArgMessage | 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;
} | php | 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;
} | [
"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",
";",
"}"
] | 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 | [
"Creates",
"a",
"verbose",
"error",
"message",
"for",
"an",
"invalid",
"argument",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientResolver.php#L324-L348 | train |
aws/aws-sdk-php | src/ClientResolver.php | ClientResolver.invalidType | 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);
} | php | 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);
} | [
"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",
")",
";",
"}"
] | Throw when an invalid type is encountered.
@param string $name Name of the value being validated.
@param mixed $provided The provided value.
@throws \InvalidArgumentException | [
"Throw",
"when",
"an",
"invalid",
"type",
"is",
"encountered",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientResolver.php#L357-L365 | train |
aws/aws-sdk-php | src/ClientResolver.php | ClientResolver.throwRequired | private function throwRequired(array $args)
{
$missing = [];
foreach ($this->argDefinitions as $k => $a) {
if (empty($a['required'])
|| isset($a['default'])
|| isset($args[$k])
) {
continue;
}
$missing[] = $this->getArgMessage($k, $args, true);
}
$msg = "Missing required client configuration options: \n\n";
$msg .= implode("\n\n", $missing);
throw new IAE($msg);
} | php | private function throwRequired(array $args)
{
$missing = [];
foreach ($this->argDefinitions as $k => $a) {
if (empty($a['required'])
|| isset($a['default'])
|| isset($args[$k])
) {
continue;
}
$missing[] = $this->getArgMessage($k, $args, true);
}
$msg = "Missing required client configuration options: \n\n";
$msg .= implode("\n\n", $missing);
throw new IAE($msg);
} | [
"private",
"function",
"throwRequired",
"(",
"array",
"$",
"args",
")",
"{",
"$",
"missing",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"argDefinitions",
"as",
"$",
"k",
"=>",
"$",
"a",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"a",
"[",
"'required'",
"]",
")",
"||",
"isset",
"(",
"$",
"a",
"[",
"'default'",
"]",
")",
"||",
"isset",
"(",
"$",
"args",
"[",
"$",
"k",
"]",
")",
")",
"{",
"continue",
";",
"}",
"$",
"missing",
"[",
"]",
"=",
"$",
"this",
"->",
"getArgMessage",
"(",
"$",
"k",
",",
"$",
"args",
",",
"true",
")",
";",
"}",
"$",
"msg",
"=",
"\"Missing required client configuration options: \\n\\n\"",
";",
"$",
"msg",
".=",
"implode",
"(",
"\"\\n\\n\"",
",",
"$",
"missing",
")",
";",
"throw",
"new",
"IAE",
"(",
"$",
"msg",
")",
";",
"}"
] | Throws an exception for missing required arguments.
@param array $args Passed in arguments.
@throws \InvalidArgumentException | [
"Throws",
"an",
"exception",
"for",
"missing",
"required",
"arguments",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientResolver.php#L373-L388 | train |
aws/aws-sdk-php | src/ClientSideMonitoring/AbstractMonitoringMiddleware.php | AbstractMonitoringMiddleware.sendEventData | private function sendEventData(array $eventData)
{
$socket = $this->prepareSocket();
$datagram = json_encode($eventData);
$result = socket_write($socket, $datagram, strlen($datagram));
if ($result === false) {
$this->prepareSocket(true);
}
return $result;
} | php | private function sendEventData(array $eventData)
{
$socket = $this->prepareSocket();
$datagram = json_encode($eventData);
$result = socket_write($socket, $datagram, strlen($datagram));
if ($result === false) {
$this->prepareSocket(true);
}
return $result;
} | [
"private",
"function",
"sendEventData",
"(",
"array",
"$",
"eventData",
")",
"{",
"$",
"socket",
"=",
"$",
"this",
"->",
"prepareSocket",
"(",
")",
";",
"$",
"datagram",
"=",
"json_encode",
"(",
"$",
"eventData",
")",
";",
"$",
"result",
"=",
"socket_write",
"(",
"$",
"socket",
",",
"$",
"datagram",
",",
"strlen",
"(",
"$",
"datagram",
")",
")",
";",
"if",
"(",
"$",
"result",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"prepareSocket",
"(",
"true",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Sends formatted monitoring event data via the UDP socket connection to
the CSM agent endpoint.
@param array $eventData
@return int | [
"Sends",
"formatted",
"monitoring",
"event",
"data",
"via",
"the",
"UDP",
"socket",
"connection",
"to",
"the",
"CSM",
"agent",
"endpoint",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientSideMonitoring/AbstractMonitoringMiddleware.php#L252-L261 | train |
aws/aws-sdk-php | src/ClientSideMonitoring/AbstractMonitoringMiddleware.php | AbstractMonitoringMiddleware.unwrappedOptions | private function unwrappedOptions()
{
if (!($this->options instanceof ConfigurationInterface)) {
$this->options = ConfigurationProvider::unwrap($this->options);
}
return $this->options;
} | php | private function unwrappedOptions()
{
if (!($this->options instanceof ConfigurationInterface)) {
$this->options = ConfigurationProvider::unwrap($this->options);
}
return $this->options;
} | [
"private",
"function",
"unwrappedOptions",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"this",
"->",
"options",
"instanceof",
"ConfigurationInterface",
")",
")",
"{",
"$",
"this",
"->",
"options",
"=",
"ConfigurationProvider",
"::",
"unwrap",
"(",
"$",
"this",
"->",
"options",
")",
";",
"}",
"return",
"$",
"this",
"->",
"options",
";",
"}"
] | Unwraps options, if needed, and returns them.
@return ConfigurationInterface | [
"Unwraps",
"options",
"if",
"needed",
"and",
"returns",
"them",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientSideMonitoring/AbstractMonitoringMiddleware.php#L268-L274 | train |
aws/aws-sdk-php | src/CloudSearchDomain/CloudSearchDomainClient.php | CloudSearchDomainClient.searchByPost | 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));
};
};
} | php | 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));
};
};
} | [
"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",
")",
")",
";",
"}",
";",
"}",
";",
"}"
] | Use POST for search command
Useful when query string is too long | [
"Use",
"POST",
"for",
"search",
"command"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudSearchDomain/CloudSearchDomainClient.php#L47-L60 | train |
aws/aws-sdk-php | src/CloudSearchDomain/CloudSearchDomainClient.php | CloudSearchDomainClient.convertGetToPost | 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;
} | php | 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;
} | [
"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",
";",
"}"
] | 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 | [
"Converts",
"default",
"GET",
"request",
"to",
"a",
"POST",
"request"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudSearchDomain/CloudSearchDomainClient.php#L70-L83 | train |
aws/aws-sdk-php | src/Api/Validator.php | Validator.validate | 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);
}
} | php | 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);
}
} | [
"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",
")",
";",
"}",
"}"
] | 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. | [
"Validates",
"the",
"given",
"input",
"against",
"the",
"schema",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Validator.php#L50-L67 | train |
aws/aws-sdk-php | src/S3/Crypto/S3EncryptionClient.php | S3EncryptionClient.getObjectAsync | public function getObjectAsync(array $args)
{
$provider = $this->getMaterialsProvider($args);
unset($args['@MaterialsProvider']);
$instructionFileSuffix = $this->getInstructionFileSuffix($args);
unset($args['@InstructionFileSuffix']);
$strategy = $this->getMetadataStrategy($args, $instructionFileSuffix);
unset($args['@MetadataStrategy']);
$saveAs = null;
if (!empty($args['SaveAs'])) {
$saveAs = $args['SaveAs'];
}
$promise = $this->client->getObjectAsync($args)
->then(
function ($result) use (
$provider,
$instructionFileSuffix,
$strategy,
$args
) {
if ($strategy === null) {
$strategy = $this->determineGetObjectStrategy(
$result,
$instructionFileSuffix
);
}
$envelope = $strategy->load($args + [
'Metadata' => $result['Metadata']
]);
$provider = $provider->fromDecryptionEnvelope($envelope);
$result['Body'] = $this->decrypt(
$result['Body'],
$provider,
$envelope,
isset($args['@CipherOptions'])
? $args['@CipherOptions']
: []
);
return $result;
}
)->then(
function ($result) use ($saveAs) {
if (!empty($saveAs)) {
file_put_contents(
$saveAs,
(string)$result['Body'],
LOCK_EX
);
}
return $result;
}
);
return $promise;
} | php | public function getObjectAsync(array $args)
{
$provider = $this->getMaterialsProvider($args);
unset($args['@MaterialsProvider']);
$instructionFileSuffix = $this->getInstructionFileSuffix($args);
unset($args['@InstructionFileSuffix']);
$strategy = $this->getMetadataStrategy($args, $instructionFileSuffix);
unset($args['@MetadataStrategy']);
$saveAs = null;
if (!empty($args['SaveAs'])) {
$saveAs = $args['SaveAs'];
}
$promise = $this->client->getObjectAsync($args)
->then(
function ($result) use (
$provider,
$instructionFileSuffix,
$strategy,
$args
) {
if ($strategy === null) {
$strategy = $this->determineGetObjectStrategy(
$result,
$instructionFileSuffix
);
}
$envelope = $strategy->load($args + [
'Metadata' => $result['Metadata']
]);
$provider = $provider->fromDecryptionEnvelope($envelope);
$result['Body'] = $this->decrypt(
$result['Body'],
$provider,
$envelope,
isset($args['@CipherOptions'])
? $args['@CipherOptions']
: []
);
return $result;
}
)->then(
function ($result) use ($saveAs) {
if (!empty($saveAs)) {
file_put_contents(
$saveAs,
(string)$result['Body'],
LOCK_EX
);
}
return $result;
}
);
return $promise;
} | [
"public",
"function",
"getObjectAsync",
"(",
"array",
"$",
"args",
")",
"{",
"$",
"provider",
"=",
"$",
"this",
"->",
"getMaterialsProvider",
"(",
"$",
"args",
")",
";",
"unset",
"(",
"$",
"args",
"[",
"'@MaterialsProvider'",
"]",
")",
";",
"$",
"instructionFileSuffix",
"=",
"$",
"this",
"->",
"getInstructionFileSuffix",
"(",
"$",
"args",
")",
";",
"unset",
"(",
"$",
"args",
"[",
"'@InstructionFileSuffix'",
"]",
")",
";",
"$",
"strategy",
"=",
"$",
"this",
"->",
"getMetadataStrategy",
"(",
"$",
"args",
",",
"$",
"instructionFileSuffix",
")",
";",
"unset",
"(",
"$",
"args",
"[",
"'@MetadataStrategy'",
"]",
")",
";",
"$",
"saveAs",
"=",
"null",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"args",
"[",
"'SaveAs'",
"]",
")",
")",
"{",
"$",
"saveAs",
"=",
"$",
"args",
"[",
"'SaveAs'",
"]",
";",
"}",
"$",
"promise",
"=",
"$",
"this",
"->",
"client",
"->",
"getObjectAsync",
"(",
"$",
"args",
")",
"->",
"then",
"(",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"$",
"provider",
",",
"$",
"instructionFileSuffix",
",",
"$",
"strategy",
",",
"$",
"args",
")",
"{",
"if",
"(",
"$",
"strategy",
"===",
"null",
")",
"{",
"$",
"strategy",
"=",
"$",
"this",
"->",
"determineGetObjectStrategy",
"(",
"$",
"result",
",",
"$",
"instructionFileSuffix",
")",
";",
"}",
"$",
"envelope",
"=",
"$",
"strategy",
"->",
"load",
"(",
"$",
"args",
"+",
"[",
"'Metadata'",
"=>",
"$",
"result",
"[",
"'Metadata'",
"]",
"]",
")",
";",
"$",
"provider",
"=",
"$",
"provider",
"->",
"fromDecryptionEnvelope",
"(",
"$",
"envelope",
")",
";",
"$",
"result",
"[",
"'Body'",
"]",
"=",
"$",
"this",
"->",
"decrypt",
"(",
"$",
"result",
"[",
"'Body'",
"]",
",",
"$",
"provider",
",",
"$",
"envelope",
",",
"isset",
"(",
"$",
"args",
"[",
"'@CipherOptions'",
"]",
")",
"?",
"$",
"args",
"[",
"'@CipherOptions'",
"]",
":",
"[",
"]",
")",
";",
"return",
"$",
"result",
";",
"}",
")",
"->",
"then",
"(",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"$",
"saveAs",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"saveAs",
")",
")",
"{",
"file_put_contents",
"(",
"$",
"saveAs",
",",
"(",
"string",
")",
"$",
"result",
"[",
"'Body'",
"]",
",",
"LOCK_EX",
")",
";",
"}",
"return",
"$",
"result",
";",
"}",
")",
";",
"return",
"$",
"promise",
";",
"}"
] | Promises to retrieve an object from S3 and decrypt the data in the
'Body' field.
@param array $args Arguments for retrieving an object from S3 via
GetObject and decrypting it.
The required configuration argument is as follows:
- @MaterialsProvider: (MaterialsProvider) Provides Cek, Iv, and Cek
encrypting/decrypting for decryption metadata. May have data loaded
from the MetadataEnvelope upon decryption.
The optional configuration arguments are as follows:
- SaveAs: (string) The path to a file on disk to save the decrypted
object data. This will be handled by file_put_contents instead of the
Guzzle sink.
- @MetadataStrategy: (MetadataStrategy|string|null) Strategy for reading
MetadataEnvelope information. Defaults to determining based on object
response headers. Can either be a class implementing MetadataStrategy,
a class name of a predefined strategy, or empty/null to default.
- @InstructionFileSuffix: (string) Suffix used when looking for an
instruction file if an InstructionFileMetadataHandler is being used.
- @CipherOptions: (array) Cipher options for decrypting data. A Cipher
is required. Accepts the following options:
- Aad: (string) Additional authentication data. This option is
passed directly to OpenSSL when using gcm. It is ignored when
using cbc.
@return PromiseInterface
@throws \InvalidArgumentException Thrown when required arguments are not
passed or are passed incorrectly. | [
"Promises",
"to",
"retrieve",
"an",
"object",
"from",
"S3",
"and",
"decrypt",
"the",
"data",
"in",
"the",
"Body",
"field",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/Crypto/S3EncryptionClient.php#L218-L279 | train |
aws/aws-sdk-php | src/AwsClient.php | AwsClient.parseClass | 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"
];
} | php | 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",
"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\"",
"]",
";",
"}"
] | 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 | [
"Parse",
"the",
"class",
"name",
"and",
"setup",
"the",
"custom",
"exception",
"class",
"of",
"the",
"client",
"and",
"return",
"the",
"service",
"name",
"of",
"the",
"client",
"and",
"exception_class",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/AwsClient.php#L269-L283 | train |
aws/aws-sdk-php | src/Api/StructureShape.php | StructureShape.getMember | public function getMember($name)
{
$members = $this->getMembers();
if (!isset($members[$name])) {
throw new \InvalidArgumentException('Unknown member ' . $name);
}
return $members[$name];
} | php | public function getMember($name)
{
$members = $this->getMembers();
if (!isset($members[$name])) {
throw new \InvalidArgumentException('Unknown member ' . $name);
}
return $members[$name];
} | [
"public",
"function",
"getMember",
"(",
"$",
"name",
")",
"{",
"$",
"members",
"=",
"$",
"this",
"->",
"getMembers",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"members",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Unknown member '",
".",
"$",
"name",
")",
";",
"}",
"return",
"$",
"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. | [
"Retrieve",
"a",
"member",
"by",
"name",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/StructureShape.php#L59-L68 | train |
aws/aws-sdk-php | src/IdempotencyTokenMiddleware.php | IdempotencyTokenMiddleware.wrap | public static function wrap(
Service $service,
callable $bytesGenerator = null
) {
return function (callable $handler) use ($service, $bytesGenerator) {
return new self($handler, $service, $bytesGenerator);
};
} | php | public static function wrap(
Service $service,
callable $bytesGenerator = null
) {
return function (callable $handler) use ($service, $bytesGenerator) {
return new self($handler, $service, $bytesGenerator);
};
} | [
"public",
"static",
"function",
"wrap",
"(",
"Service",
"$",
"service",
",",
"callable",
"$",
"bytesGenerator",
"=",
"null",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"service",
",",
"$",
"bytesGenerator",
")",
"{",
"return",
"new",
"self",
"(",
"$",
"handler",
",",
"$",
"service",
",",
"$",
"bytesGenerator",
")",
";",
"}",
";",
"}"
] | Creates a middleware that populates operation parameter
with trait 'idempotencyToken' enabled with a random UUIDv4
One of following functions needs to be available
in order to generate random bytes used for UUID
(SDK will attempt to utilize function in following order):
- random_bytes (requires PHP 7.0 or above)
- openssl_random_pseudo_bytes (requires 'openssl' module enabled)
- mcrypt_create_iv (requires 'mcrypt' module enabled)
You may also supply a custom bytes generator as an optional second
parameter.
@param \Aws\Api\Service $service
@param callable|null $bytesGenerator
@return callable | [
"Creates",
"a",
"middleware",
"that",
"populates",
"operation",
"parameter",
"with",
"trait",
"idempotencyToken",
"enabled",
"with",
"a",
"random",
"UUIDv4"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/IdempotencyTokenMiddleware.php#L38-L45 | train |
aws/aws-sdk-php | src/IdempotencyTokenMiddleware.php | IdempotencyTokenMiddleware.getUuidV4 | private static function getUuidV4($bytes)
{
// set version to 0100
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
// set bits 6-7 to 10
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
} | php | private static function getUuidV4($bytes)
{
// set version to 0100
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
// set bits 6-7 to 10
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
} | [
"private",
"static",
"function",
"getUuidV4",
"(",
"$",
"bytes",
")",
"{",
"// set version to 0100",
"$",
"bytes",
"[",
"6",
"]",
"=",
"chr",
"(",
"ord",
"(",
"$",
"bytes",
"[",
"6",
"]",
")",
"&",
"0x0f",
"|",
"0x40",
")",
";",
"// set bits 6-7 to 10",
"$",
"bytes",
"[",
"8",
"]",
"=",
"chr",
"(",
"ord",
"(",
"$",
"bytes",
"[",
"8",
"]",
")",
"&",
"0x3f",
"|",
"0x80",
")",
";",
"return",
"vsprintf",
"(",
"'%s%s-%s-%s-%s-%s%s%s'",
",",
"str_split",
"(",
"bin2hex",
"(",
"$",
"bytes",
")",
",",
"4",
")",
")",
";",
"}"
] | This function generates a random UUID v4 string,
which is used as auto filled token value.
@param string $bytes 16 bytes of pseudo-random bytes
@return string
More information about UUID v4, see:
https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
https://tools.ietf.org/html/rfc4122#page-14 | [
"This",
"function",
"generates",
"a",
"random",
"UUID",
"v4",
"string",
"which",
"is",
"used",
"as",
"auto",
"filled",
"token",
"value",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/IdempotencyTokenMiddleware.php#L90-L97 | train |
phpstan/phpstan | src/Command/ErrorFormatter/CheckstyleErrorFormatter.php | CheckstyleErrorFormatter.formatErrors | public function formatErrors(
AnalysisResult $analysisResult,
OutputStyle $style
): int
{
$style->writeln('<?xml version="1.0" encoding="UTF-8"?>');
$style->writeln('<checkstyle>');
foreach ($this->groupByFile($analysisResult) as $relativeFilePath => $errors) {
$style->writeln(sprintf(
'<file name="%s">',
$this->escape($relativeFilePath)
));
foreach ($errors as $error) {
$style->writeln(sprintf(
' <error line="%d" column="1" severity="error" message="%s" />',
$this->escape((string) $error->getLine()),
$this->escape((string) $error->getMessage())
));
}
$style->writeln('</file>');
}
$notFileSpecificErrors = $analysisResult->getNotFileSpecificErrors();
if (count($notFileSpecificErrors) > 0) {
$style->writeln('<file>');
foreach ($notFileSpecificErrors as $error) {
$style->writeln(sprintf(' <error severity="error" message="%s" />', $this->escape($error)));
}
$style->writeln('</file>');
}
$style->writeln('</checkstyle>');
return $analysisResult->hasErrors() ? 1 : 0;
} | php | public function formatErrors(
AnalysisResult $analysisResult,
OutputStyle $style
): int
{
$style->writeln('<?xml version="1.0" encoding="UTF-8"?>');
$style->writeln('<checkstyle>');
foreach ($this->groupByFile($analysisResult) as $relativeFilePath => $errors) {
$style->writeln(sprintf(
'<file name="%s">',
$this->escape($relativeFilePath)
));
foreach ($errors as $error) {
$style->writeln(sprintf(
' <error line="%d" column="1" severity="error" message="%s" />',
$this->escape((string) $error->getLine()),
$this->escape((string) $error->getMessage())
));
}
$style->writeln('</file>');
}
$notFileSpecificErrors = $analysisResult->getNotFileSpecificErrors();
if (count($notFileSpecificErrors) > 0) {
$style->writeln('<file>');
foreach ($notFileSpecificErrors as $error) {
$style->writeln(sprintf(' <error severity="error" message="%s" />', $this->escape($error)));
}
$style->writeln('</file>');
}
$style->writeln('</checkstyle>');
return $analysisResult->hasErrors() ? 1 : 0;
} | [
"public",
"function",
"formatErrors",
"(",
"AnalysisResult",
"$",
"analysisResult",
",",
"OutputStyle",
"$",
"style",
")",
":",
"int",
"{",
"$",
"style",
"->",
"writeln",
"(",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'",
")",
";",
"$",
"style",
"->",
"writeln",
"(",
"'<checkstyle>'",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"groupByFile",
"(",
"$",
"analysisResult",
")",
"as",
"$",
"relativeFilePath",
"=>",
"$",
"errors",
")",
"{",
"$",
"style",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<file name=\"%s\">'",
",",
"$",
"this",
"->",
"escape",
"(",
"$",
"relativeFilePath",
")",
")",
")",
";",
"foreach",
"(",
"$",
"errors",
"as",
"$",
"error",
")",
"{",
"$",
"style",
"->",
"writeln",
"(",
"sprintf",
"(",
"' <error line=\"%d\" column=\"1\" severity=\"error\" message=\"%s\" />'",
",",
"$",
"this",
"->",
"escape",
"(",
"(",
"string",
")",
"$",
"error",
"->",
"getLine",
"(",
")",
")",
",",
"$",
"this",
"->",
"escape",
"(",
"(",
"string",
")",
"$",
"error",
"->",
"getMessage",
"(",
")",
")",
")",
")",
";",
"}",
"$",
"style",
"->",
"writeln",
"(",
"'</file>'",
")",
";",
"}",
"$",
"notFileSpecificErrors",
"=",
"$",
"analysisResult",
"->",
"getNotFileSpecificErrors",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"notFileSpecificErrors",
")",
">",
"0",
")",
"{",
"$",
"style",
"->",
"writeln",
"(",
"'<file>'",
")",
";",
"foreach",
"(",
"$",
"notFileSpecificErrors",
"as",
"$",
"error",
")",
"{",
"$",
"style",
"->",
"writeln",
"(",
"sprintf",
"(",
"' <error severity=\"error\" message=\"%s\" />'",
",",
"$",
"this",
"->",
"escape",
"(",
"$",
"error",
")",
")",
")",
";",
"}",
"$",
"style",
"->",
"writeln",
"(",
"'</file>'",
")",
";",
"}",
"$",
"style",
"->",
"writeln",
"(",
"'</checkstyle>'",
")",
";",
"return",
"$",
"analysisResult",
"->",
"hasErrors",
"(",
")",
"?",
"1",
":",
"0",
";",
"}"
] | Formats the errors and outputs them to the console.
@param \PHPStan\Command\AnalysisResult $analysisResult
@param \Symfony\Component\Console\Style\OutputStyle $style
@return int Error code. | [
"Formats",
"the",
"errors",
"and",
"outputs",
"them",
"to",
"the",
"console",
"."
] | 954b7101f5b9b516243a61c6b32b272cd892eb7d | https://github.com/phpstan/phpstan/blob/954b7101f5b9b516243a61c6b32b272cd892eb7d/src/Command/ErrorFormatter/CheckstyleErrorFormatter.php#L27-L66 | train |
phpstan/phpstan | src/Command/ErrorFormatter/CheckstyleErrorFormatter.php | CheckstyleErrorFormatter.groupByFile | private function groupByFile(AnalysisResult $analysisResult): array
{
$files = [];
/** @var \PHPStan\Analyser\Error $fileSpecificError */
foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) {
$relativeFilePath = $this->relativePathHelper->getRelativePath(
$fileSpecificError->getFile()
);
$files[$relativeFilePath][] = $fileSpecificError;
}
return $files;
} | php | private function groupByFile(AnalysisResult $analysisResult): array
{
$files = [];
/** @var \PHPStan\Analyser\Error $fileSpecificError */
foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) {
$relativeFilePath = $this->relativePathHelper->getRelativePath(
$fileSpecificError->getFile()
);
$files[$relativeFilePath][] = $fileSpecificError;
}
return $files;
} | [
"private",
"function",
"groupByFile",
"(",
"AnalysisResult",
"$",
"analysisResult",
")",
":",
"array",
"{",
"$",
"files",
"=",
"[",
"]",
";",
"/** @var \\PHPStan\\Analyser\\Error $fileSpecificError */",
"foreach",
"(",
"$",
"analysisResult",
"->",
"getFileSpecificErrors",
"(",
")",
"as",
"$",
"fileSpecificError",
")",
"{",
"$",
"relativeFilePath",
"=",
"$",
"this",
"->",
"relativePathHelper",
"->",
"getRelativePath",
"(",
"$",
"fileSpecificError",
"->",
"getFile",
"(",
")",
")",
";",
"$",
"files",
"[",
"$",
"relativeFilePath",
"]",
"[",
"]",
"=",
"$",
"fileSpecificError",
";",
"}",
"return",
"$",
"files",
";",
"}"
] | Group errors by file
@param AnalysisResult $analysisResult
@return array<string, array> Array that have as key the relative path of file
and as value an array with occured errors. | [
"Group",
"errors",
"by",
"file"
] | 954b7101f5b9b516243a61c6b32b272cd892eb7d | https://github.com/phpstan/phpstan/blob/954b7101f5b9b516243a61c6b32b272cd892eb7d/src/Command/ErrorFormatter/CheckstyleErrorFormatter.php#L86-L100 | train |
yansongda/pay | src/Pay.php | Pay.registerLogService | protected function registerLogService()
{
$logger = Log::createLogger(
$this->config->get('log.file'),
'yansongda.pay',
$this->config->get('log.level', 'warning'),
$this->config->get('log.type', 'daily'),
$this->config->get('log.max_file', 30)
);
Log::setLogger($logger);
} | php | protected function registerLogService()
{
$logger = Log::createLogger(
$this->config->get('log.file'),
'yansongda.pay',
$this->config->get('log.level', 'warning'),
$this->config->get('log.type', 'daily'),
$this->config->get('log.max_file', 30)
);
Log::setLogger($logger);
} | [
"protected",
"function",
"registerLogService",
"(",
")",
"{",
"$",
"logger",
"=",
"Log",
"::",
"createLogger",
"(",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'log.file'",
")",
",",
"'yansongda.pay'",
",",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'log.level'",
",",
"'warning'",
")",
",",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'log.type'",
",",
"'daily'",
")",
",",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'log.max_file'",
",",
"30",
")",
")",
";",
"Log",
"::",
"setLogger",
"(",
"$",
"logger",
")",
";",
"}"
] | Register log service.
@author yansongda <me@yansongda.cn>
@throws Exception | [
"Register",
"log",
"service",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Pay.php#L116-L127 | train |
yansongda/pay | src/Gateways/Wechat.php | Wechat.refund | public function refund($order): Collection
{
$this->payload = Support::filterPayload($this->payload, $order, true);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'Refund', $this->gateway, $this->payload));
return Support::requestApi(
'secapi/pay/refund',
$this->payload,
true
);
} | php | public function refund($order): Collection
{
$this->payload = Support::filterPayload($this->payload, $order, true);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'Refund', $this->gateway, $this->payload));
return Support::requestApi(
'secapi/pay/refund',
$this->payload,
true
);
} | [
"public",
"function",
"refund",
"(",
"$",
"order",
")",
":",
"Collection",
"{",
"$",
"this",
"->",
"payload",
"=",
"Support",
"::",
"filterPayload",
"(",
"$",
"this",
"->",
"payload",
",",
"$",
"order",
",",
"true",
")",
";",
"Events",
"::",
"dispatch",
"(",
"Events",
"::",
"METHOD_CALLED",
",",
"new",
"Events",
"\\",
"MethodCalled",
"(",
"'Wechat'",
",",
"'Refund'",
",",
"$",
"this",
"->",
"gateway",
",",
"$",
"this",
"->",
"payload",
")",
")",
";",
"return",
"Support",
"::",
"requestApi",
"(",
"'secapi/pay/refund'",
",",
"$",
"this",
"->",
"payload",
",",
"true",
")",
";",
"}"
] | Refund an order.
@author yansongda <me@yansongda.cn>
@param array $order
@throws GatewayException
@throws InvalidSignException
@throws InvalidArgumentException
@return Collection | [
"Refund",
"an",
"order",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Wechat.php#L238-L249 | train |
yansongda/pay | src/Gateways/Wechat.php | Wechat.download | public function download(array $params): string
{
unset($this->payload['spbill_create_ip']);
$this->payload = Support::filterPayload($this->payload, $params, true);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'Download', $this->gateway, $this->payload));
$result = Support::getInstance()->post(
'pay/downloadbill',
Support::getInstance()->toXml($this->payload)
);
if (is_array($result)) {
throw new GatewayException('Get Wechat API Error: '.$result['return_msg'], $result);
}
return $result;
} | php | public function download(array $params): string
{
unset($this->payload['spbill_create_ip']);
$this->payload = Support::filterPayload($this->payload, $params, true);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'Download', $this->gateway, $this->payload));
$result = Support::getInstance()->post(
'pay/downloadbill',
Support::getInstance()->toXml($this->payload)
);
if (is_array($result)) {
throw new GatewayException('Get Wechat API Error: '.$result['return_msg'], $result);
}
return $result;
} | [
"public",
"function",
"download",
"(",
"array",
"$",
"params",
")",
":",
"string",
"{",
"unset",
"(",
"$",
"this",
"->",
"payload",
"[",
"'spbill_create_ip'",
"]",
")",
";",
"$",
"this",
"->",
"payload",
"=",
"Support",
"::",
"filterPayload",
"(",
"$",
"this",
"->",
"payload",
",",
"$",
"params",
",",
"true",
")",
";",
"Events",
"::",
"dispatch",
"(",
"Events",
"::",
"METHOD_CALLED",
",",
"new",
"Events",
"\\",
"MethodCalled",
"(",
"'Wechat'",
",",
"'Download'",
",",
"$",
"this",
"->",
"gateway",
",",
"$",
"this",
"->",
"payload",
")",
")",
";",
"$",
"result",
"=",
"Support",
"::",
"getInstance",
"(",
")",
"->",
"post",
"(",
"'pay/downloadbill'",
",",
"Support",
"::",
"getInstance",
"(",
")",
"->",
"toXml",
"(",
"$",
"this",
"->",
"payload",
")",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"result",
")",
")",
"{",
"throw",
"new",
"GatewayException",
"(",
"'Get Wechat API Error: '",
".",
"$",
"result",
"[",
"'return_msg'",
"]",
",",
"$",
"result",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Download the bill.
@author yansongda <me@yansongda.cn>
@param array $params
@throws GatewayException
@throws InvalidArgumentException
@return string | [
"Download",
"the",
"bill",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Wechat.php#L335-L353 | train |
yansongda/pay | src/Gateways/Wechat/Support.php | Support.getSignContent | public static function getSignContent($data): string
{
$buff = '';
foreach ($data as $k => $v) {
$buff .= ($k != 'sign' && $v != '' && !is_array($v)) ? $k.'='.$v.'&' : '';
}
Log::debug('Wechat Generate Sign Content Before Trim', [$data, $buff]);
return trim($buff, '&');
} | php | public static function getSignContent($data): string
{
$buff = '';
foreach ($data as $k => $v) {
$buff .= ($k != 'sign' && $v != '' && !is_array($v)) ? $k.'='.$v.'&' : '';
}
Log::debug('Wechat Generate Sign Content Before Trim', [$data, $buff]);
return trim($buff, '&');
} | [
"public",
"static",
"function",
"getSignContent",
"(",
"$",
"data",
")",
":",
"string",
"{",
"$",
"buff",
"=",
"''",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"$",
"buff",
".=",
"(",
"$",
"k",
"!=",
"'sign'",
"&&",
"$",
"v",
"!=",
"''",
"&&",
"!",
"is_array",
"(",
"$",
"v",
")",
")",
"?",
"$",
"k",
".",
"'='",
".",
"$",
"v",
".",
"'&'",
":",
"''",
";",
"}",
"Log",
"::",
"debug",
"(",
"'Wechat Generate Sign Content Before Trim'",
",",
"[",
"$",
"data",
",",
"$",
"buff",
"]",
")",
";",
"return",
"trim",
"(",
"$",
"buff",
",",
"'&'",
")",
";",
"}"
] | Generate sign content.
@author yansongda <me@yansongda.cn>
@param array $data
@return string | [
"Generate",
"sign",
"content",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Wechat/Support.php#L253-L264 | train |
yansongda/pay | src/Gateways/Wechat/Support.php | Support.decryptRefundContents | public static function decryptRefundContents($contents): string
{
return openssl_decrypt(
base64_decode($contents),
'AES-256-ECB',
md5(self::$instance->key),
OPENSSL_RAW_DATA
);
} | php | public static function decryptRefundContents($contents): string
{
return openssl_decrypt(
base64_decode($contents),
'AES-256-ECB',
md5(self::$instance->key),
OPENSSL_RAW_DATA
);
} | [
"public",
"static",
"function",
"decryptRefundContents",
"(",
"$",
"contents",
")",
":",
"string",
"{",
"return",
"openssl_decrypt",
"(",
"base64_decode",
"(",
"$",
"contents",
")",
",",
"'AES-256-ECB'",
",",
"md5",
"(",
"self",
"::",
"$",
"instance",
"->",
"key",
")",
",",
"OPENSSL_RAW_DATA",
")",
";",
"}"
] | Decrypt refund contents.
@author yansongda <me@yansongda.cn>
@param string $contents
@return string | [
"Decrypt",
"refund",
"contents",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Wechat/Support.php#L275-L283 | train |
yansongda/pay | src/Gateways/Wechat/Support.php | Support.toXml | public static function toXml($data): string
{
if (!is_array($data) || count($data) <= 0) {
throw new InvalidArgumentException('Convert To Xml Error! Invalid Array!');
}
$xml = '<xml>';
foreach ($data as $key => $val) {
$xml .= is_numeric($val) ? '<'.$key.'>'.$val.'</'.$key.'>' :
'<'.$key.'><![CDATA['.$val.']]></'.$key.'>';
}
$xml .= '</xml>';
return $xml;
} | php | public static function toXml($data): string
{
if (!is_array($data) || count($data) <= 0) {
throw new InvalidArgumentException('Convert To Xml Error! Invalid Array!');
}
$xml = '<xml>';
foreach ($data as $key => $val) {
$xml .= is_numeric($val) ? '<'.$key.'>'.$val.'</'.$key.'>' :
'<'.$key.'><![CDATA['.$val.']]></'.$key.'>';
}
$xml .= '</xml>';
return $xml;
} | [
"public",
"static",
"function",
"toXml",
"(",
"$",
"data",
")",
":",
"string",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"data",
")",
"||",
"count",
"(",
"$",
"data",
")",
"<=",
"0",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Convert To Xml Error! Invalid Array!'",
")",
";",
"}",
"$",
"xml",
"=",
"'<xml>'",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"val",
")",
"{",
"$",
"xml",
".=",
"is_numeric",
"(",
"$",
"val",
")",
"?",
"'<'",
".",
"$",
"key",
".",
"'>'",
".",
"$",
"val",
".",
"'</'",
".",
"$",
"key",
".",
"'>'",
":",
"'<'",
".",
"$",
"key",
".",
"'><![CDATA['",
".",
"$",
"val",
".",
"']]></'",
".",
"$",
"key",
".",
"'>'",
";",
"}",
"$",
"xml",
".=",
"'</xml>'",
";",
"return",
"$",
"xml",
";",
"}"
] | Convert array to xml.
@author yansongda <me@yansongda.cn>
@param array $data
@throws InvalidArgumentException
@return string | [
"Convert",
"array",
"to",
"xml",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Wechat/Support.php#L296-L310 | train |
yansongda/pay | src/Gateways/Wechat/Support.php | Support.fromXml | public static function fromXml($xml): array
{
if (!$xml) {
throw new InvalidArgumentException('Convert To Array Error! Invalid Xml!');
}
libxml_disable_entity_loader(true);
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA), JSON_UNESCAPED_UNICODE), true);
} | php | public static function fromXml($xml): array
{
if (!$xml) {
throw new InvalidArgumentException('Convert To Array Error! Invalid Xml!');
}
libxml_disable_entity_loader(true);
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA), JSON_UNESCAPED_UNICODE), true);
} | [
"public",
"static",
"function",
"fromXml",
"(",
"$",
"xml",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"xml",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Convert To Array Error! Invalid Xml!'",
")",
";",
"}",
"libxml_disable_entity_loader",
"(",
"true",
")",
";",
"return",
"json_decode",
"(",
"json_encode",
"(",
"simplexml_load_string",
"(",
"$",
"xml",
",",
"'SimpleXMLElement'",
",",
"LIBXML_NOCDATA",
")",
",",
"JSON_UNESCAPED_UNICODE",
")",
",",
"true",
")",
";",
"}"
] | Convert xml to array.
@author yansongda <me@yansongda.cn>
@param string $xml
@throws InvalidArgumentException
@return array | [
"Convert",
"xml",
"to",
"array",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Wechat/Support.php#L323-L332 | train |
yansongda/pay | src/Gateways/Wechat/Support.php | Support.getConfig | public function getConfig($key = null, $default = null)
{
if (is_null($key)) {
return $this->config->all();
}
if ($this->config->has($key)) {
return $this->config[$key];
}
return $default;
} | php | public function getConfig($key = null, $default = null)
{
if (is_null($key)) {
return $this->config->all();
}
if ($this->config->has($key)) {
return $this->config[$key];
}
return $default;
} | [
"public",
"function",
"getConfig",
"(",
"$",
"key",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"this",
"->",
"config",
"->",
"all",
"(",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"config",
"->",
"has",
"(",
"$",
"key",
")",
")",
"{",
"return",
"$",
"this",
"->",
"config",
"[",
"$",
"key",
"]",
";",
"}",
"return",
"$",
"default",
";",
"}"
] | Get service config.
@author yansongda <me@yansongda.cn>
@param null|string $key
@param null|mixed $default
@return mixed|null | [
"Get",
"service",
"config",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Wechat/Support.php#L344-L355 | train |
yansongda/pay | src/Gateways/Alipay.php | Alipay.cancel | public function cancel($order): Collection
{
$this->payload['method'] = 'alipay.trade.cancel';
$this->payload['biz_content'] = json_encode(is_array($order) ? $order : ['out_trade_no' => $order]);
$this->payload['sign'] = Support::generateSign($this->payload);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Alipay', 'Cancel', $this->gateway, $this->payload));
return Support::requestApi($this->payload);
} | php | public function cancel($order): Collection
{
$this->payload['method'] = 'alipay.trade.cancel';
$this->payload['biz_content'] = json_encode(is_array($order) ? $order : ['out_trade_no' => $order]);
$this->payload['sign'] = Support::generateSign($this->payload);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Alipay', 'Cancel', $this->gateway, $this->payload));
return Support::requestApi($this->payload);
} | [
"public",
"function",
"cancel",
"(",
"$",
"order",
")",
":",
"Collection",
"{",
"$",
"this",
"->",
"payload",
"[",
"'method'",
"]",
"=",
"'alipay.trade.cancel'",
";",
"$",
"this",
"->",
"payload",
"[",
"'biz_content'",
"]",
"=",
"json_encode",
"(",
"is_array",
"(",
"$",
"order",
")",
"?",
"$",
"order",
":",
"[",
"'out_trade_no'",
"=>",
"$",
"order",
"]",
")",
";",
"$",
"this",
"->",
"payload",
"[",
"'sign'",
"]",
"=",
"Support",
"::",
"generateSign",
"(",
"$",
"this",
"->",
"payload",
")",
";",
"Events",
"::",
"dispatch",
"(",
"Events",
"::",
"METHOD_CALLED",
",",
"new",
"Events",
"\\",
"MethodCalled",
"(",
"'Alipay'",
",",
"'Cancel'",
",",
"$",
"this",
"->",
"gateway",
",",
"$",
"this",
"->",
"payload",
")",
")",
";",
"return",
"Support",
"::",
"requestApi",
"(",
"$",
"this",
"->",
"payload",
")",
";",
"}"
] | Cancel an order.
@author yansongda <me@yansongda.cn>
@param array $order
@throws GatewayException
@throws InvalidConfigException
@throws InvalidSignException
@return Collection | [
"Cancel",
"an",
"order",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Alipay.php#L260-L269 | train |
yansongda/pay | src/Gateways/Alipay.php | Alipay.success | public function success(): Response
{
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Alipay', 'Success', $this->gateway));
return Response::create('success');
} | php | public function success(): Response
{
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Alipay', 'Success', $this->gateway));
return Response::create('success');
} | [
"public",
"function",
"success",
"(",
")",
":",
"Response",
"{",
"Events",
"::",
"dispatch",
"(",
"Events",
"::",
"METHOD_CALLED",
",",
"new",
"Events",
"\\",
"MethodCalled",
"(",
"'Alipay'",
",",
"'Success'",
",",
"$",
"this",
"->",
"gateway",
")",
")",
";",
"return",
"Response",
"::",
"create",
"(",
"'success'",
")",
";",
"}"
] | Reply success to alipay.
@author yansongda <me@yansongda.cn>
@return Response | [
"Reply",
"success",
"to",
"alipay",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Alipay.php#L328-L333 | train |
yansongda/pay | src/Gateways/Alipay/Support.php | Support.getSignContent | public static function getSignContent(array $data, $verify = false): string
{
$data = self::encoding($data, $data['charset'] ?? 'gb2312', 'utf-8');
ksort($data);
$stringToBeSigned = '';
foreach ($data as $k => $v) {
if ($verify && $k != 'sign' && $k != 'sign_type') {
$stringToBeSigned .= $k.'='.$v.'&';
}
if (!$verify && $v !== '' && !is_null($v) && $k != 'sign' && '@' != substr($v, 0, 1)) {
$stringToBeSigned .= $k.'='.$v.'&';
}
}
Log::debug('Alipay Generate Sign Content Before Trim', [$data, $stringToBeSigned]);
return trim($stringToBeSigned, '&');
} | php | public static function getSignContent(array $data, $verify = false): string
{
$data = self::encoding($data, $data['charset'] ?? 'gb2312', 'utf-8');
ksort($data);
$stringToBeSigned = '';
foreach ($data as $k => $v) {
if ($verify && $k != 'sign' && $k != 'sign_type') {
$stringToBeSigned .= $k.'='.$v.'&';
}
if (!$verify && $v !== '' && !is_null($v) && $k != 'sign' && '@' != substr($v, 0, 1)) {
$stringToBeSigned .= $k.'='.$v.'&';
}
}
Log::debug('Alipay Generate Sign Content Before Trim', [$data, $stringToBeSigned]);
return trim($stringToBeSigned, '&');
} | [
"public",
"static",
"function",
"getSignContent",
"(",
"array",
"$",
"data",
",",
"$",
"verify",
"=",
"false",
")",
":",
"string",
"{",
"$",
"data",
"=",
"self",
"::",
"encoding",
"(",
"$",
"data",
",",
"$",
"data",
"[",
"'charset'",
"]",
"??",
"'gb2312'",
",",
"'utf-8'",
")",
";",
"ksort",
"(",
"$",
"data",
")",
";",
"$",
"stringToBeSigned",
"=",
"''",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"$",
"verify",
"&&",
"$",
"k",
"!=",
"'sign'",
"&&",
"$",
"k",
"!=",
"'sign_type'",
")",
"{",
"$",
"stringToBeSigned",
".=",
"$",
"k",
".",
"'='",
".",
"$",
"v",
".",
"'&'",
";",
"}",
"if",
"(",
"!",
"$",
"verify",
"&&",
"$",
"v",
"!==",
"''",
"&&",
"!",
"is_null",
"(",
"$",
"v",
")",
"&&",
"$",
"k",
"!=",
"'sign'",
"&&",
"'@'",
"!=",
"substr",
"(",
"$",
"v",
",",
"0",
",",
"1",
")",
")",
"{",
"$",
"stringToBeSigned",
".=",
"$",
"k",
".",
"'='",
".",
"$",
"v",
".",
"'&'",
";",
"}",
"}",
"Log",
"::",
"debug",
"(",
"'Alipay Generate Sign Content Before Trim'",
",",
"[",
"$",
"data",
",",
"$",
"stringToBeSigned",
"]",
")",
";",
"return",
"trim",
"(",
"$",
"stringToBeSigned",
",",
"'&'",
")",
";",
"}"
] | Get signContent that is to be signed.
@author yansongda <me@yansongda.cn>
@param array $data
@param bool $verify
@return string | [
"Get",
"signContent",
"that",
"is",
"to",
"be",
"signed",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Alipay/Support.php#L224-L243 | train |
yansongda/pay | src/Gateways/Alipay/Support.php | Support.setHttpOptions | protected function setHttpOptions(): self
{
if ($this->config->has('http') && is_array($this->config->get('http'))) {
$this->config->forget('http.base_uri');
$this->httpOptions = $this->config->get('http');
}
return $this;
} | php | protected function setHttpOptions(): self
{
if ($this->config->has('http') && is_array($this->config->get('http'))) {
$this->config->forget('http.base_uri');
$this->httpOptions = $this->config->get('http');
}
return $this;
} | [
"protected",
"function",
"setHttpOptions",
"(",
")",
":",
"self",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"->",
"has",
"(",
"'http'",
")",
"&&",
"is_array",
"(",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'http'",
")",
")",
")",
"{",
"$",
"this",
"->",
"config",
"->",
"forget",
"(",
"'http.base_uri'",
")",
";",
"$",
"this",
"->",
"httpOptions",
"=",
"$",
"this",
"->",
"config",
"->",
"get",
"(",
"'http'",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Set Http options.
@author yansongda <me@yansongda.cn>
@return self | [
"Set",
"Http",
"options",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Alipay/Support.php#L338-L346 | train |
yansongda/pay | src/Gateways/Wechat/Gateway.php | Gateway.preOrder | protected function preOrder($payload): Collection
{
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'PreOrder', '', $payload));
return Support::requestApi('pay/unifiedorder', $payload);
} | php | protected function preOrder($payload): Collection
{
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'PreOrder', '', $payload));
return Support::requestApi('pay/unifiedorder', $payload);
} | [
"protected",
"function",
"preOrder",
"(",
"$",
"payload",
")",
":",
"Collection",
"{",
"$",
"payload",
"[",
"'sign'",
"]",
"=",
"Support",
"::",
"generateSign",
"(",
"$",
"payload",
")",
";",
"Events",
"::",
"dispatch",
"(",
"Events",
"::",
"METHOD_CALLED",
",",
"new",
"Events",
"\\",
"MethodCalled",
"(",
"'Wechat'",
",",
"'PreOrder'",
",",
"''",
",",
"$",
"payload",
")",
")",
";",
"return",
"Support",
"::",
"requestApi",
"(",
"'pay/unifiedorder'",
",",
"$",
"payload",
")",
";",
"}"
] | Schedule an order.
@author yansongda <me@yansongda.cn>
@param array $payload
@throws GatewayException
@throws InvalidArgumentException
@throws InvalidSignException
@return Collection | [
"Schedule",
"an",
"order",
"."
] | b423068179b1e2d88d1325b5597b1431eb21cd64 | https://github.com/yansongda/pay/blob/b423068179b1e2d88d1325b5597b1431eb21cd64/src/Gateways/Wechat/Gateway.php#L67-L74 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/Migrations/SchemaParser.php | SchemaParser.render | public function render()
{
$results = '';
foreach ($this->toArray() as $column => $attributes) {
$results .= $this->createField($column, $attributes);
}
return $results;
} | php | public function render()
{
$results = '';
foreach ($this->toArray() as $column => $attributes) {
$results .= $this->createField($column, $attributes);
}
return $results;
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"results",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"toArray",
"(",
")",
"as",
"$",
"column",
"=>",
"$",
"attributes",
")",
"{",
"$",
"results",
".=",
"$",
"this",
"->",
"createField",
"(",
"$",
"column",
",",
"$",
"attributes",
")",
";",
"}",
"return",
"$",
"results",
";",
"}"
] | Render the migration to formatted script.
@return string | [
"Render",
"the",
"migration",
"to",
"formatted",
"script",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/Migrations/SchemaParser.php#L54-L62 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/Migrations/SchemaParser.php | SchemaParser.parse | public function parse($schema)
{
$this->schema = $schema;
$parsed = [];
foreach ($this->getSchemas() as $schemaArray) {
$column = $this->getColumn($schemaArray);
$attributes = $this->getAttributes($column, $schemaArray);
$parsed[$column] = $attributes;
}
return $parsed;
} | php | public function parse($schema)
{
$this->schema = $schema;
$parsed = [];
foreach ($this->getSchemas() as $schemaArray) {
$column = $this->getColumn($schemaArray);
$attributes = $this->getAttributes($column, $schemaArray);
$parsed[$column] = $attributes;
}
return $parsed;
} | [
"public",
"function",
"parse",
"(",
"$",
"schema",
")",
"{",
"$",
"this",
"->",
"schema",
"=",
"$",
"schema",
";",
"$",
"parsed",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getSchemas",
"(",
")",
"as",
"$",
"schemaArray",
")",
"{",
"$",
"column",
"=",
"$",
"this",
"->",
"getColumn",
"(",
"$",
"schemaArray",
")",
";",
"$",
"attributes",
"=",
"$",
"this",
"->",
"getAttributes",
"(",
"$",
"column",
",",
"$",
"schemaArray",
")",
";",
"$",
"parsed",
"[",
"$",
"column",
"]",
"=",
"$",
"attributes",
";",
"}",
"return",
"$",
"parsed",
";",
"}"
] | Parse a string to array of formatted schema.
@param string $schema
@return array | [
"Parse",
"a",
"string",
"to",
"array",
"of",
"formatted",
"schema",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/Migrations/SchemaParser.php#L81-L92 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/Migrations/SchemaParser.php | SchemaParser.getAttributes | public function getAttributes($column, $schema)
{
$fields = str_replace($column . ':', '', $schema);
return $this->hasCustomAttribute($column) ? $this->getCustomAttribute($column) : explode(':', $fields);
} | php | public function getAttributes($column, $schema)
{
$fields = str_replace($column . ':', '', $schema);
return $this->hasCustomAttribute($column) ? $this->getCustomAttribute($column) : explode(':', $fields);
} | [
"public",
"function",
"getAttributes",
"(",
"$",
"column",
",",
"$",
"schema",
")",
"{",
"$",
"fields",
"=",
"str_replace",
"(",
"$",
"column",
".",
"':'",
",",
"''",
",",
"$",
"schema",
")",
";",
"return",
"$",
"this",
"->",
"hasCustomAttribute",
"(",
"$",
"column",
")",
"?",
"$",
"this",
"->",
"getCustomAttribute",
"(",
"$",
"column",
")",
":",
"explode",
"(",
"':'",
",",
"$",
"fields",
")",
";",
"}"
] | Get column attributes.
@param string $column
@param string $schema
@return array | [
"Get",
"column",
"attributes",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/Migrations/SchemaParser.php#L130-L135 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/Migrations/SchemaParser.php | SchemaParser.down | public function down()
{
$results = '';
foreach ($this->toArray() as $column => $attributes) {
$results .= $this->createField($column, $attributes, 'remove');
}
return $results;
} | php | public function down()
{
$results = '';
foreach ($this->toArray() as $column => $attributes) {
$results .= $this->createField($column, $attributes, 'remove');
}
return $results;
} | [
"public",
"function",
"down",
"(",
")",
"{",
"$",
"results",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"toArray",
"(",
")",
"as",
"$",
"column",
"=>",
"$",
"attributes",
")",
"{",
"$",
"results",
".=",
"$",
"this",
"->",
"createField",
"(",
"$",
"column",
",",
"$",
"attributes",
",",
"'remove'",
")",
";",
"}",
"return",
"$",
"results",
";",
"}"
] | Render down migration fields.
@return string | [
"Render",
"down",
"migration",
"fields",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/Migrations/SchemaParser.php#L184-L192 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/Migrations/RulesParser.php | RulesParser.parse | public function parse($rules)
{
$this->rules = $rules;
$parsed = [];
foreach ($this->getRules() as $rulesArray) {
$column = $this->getColumn($rulesArray);
$attributes = $this->getAttributes($column, $rulesArray);
$parsed[$column] = $attributes;
}
return $parsed;
} | php | public function parse($rules)
{
$this->rules = $rules;
$parsed = [];
foreach ($this->getRules() as $rulesArray) {
$column = $this->getColumn($rulesArray);
$attributes = $this->getAttributes($column, $rulesArray);
$parsed[$column] = $attributes;
}
return $parsed;
} | [
"public",
"function",
"parse",
"(",
"$",
"rules",
")",
"{",
"$",
"this",
"->",
"rules",
"=",
"$",
"rules",
";",
"$",
"parsed",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getRules",
"(",
")",
"as",
"$",
"rulesArray",
")",
"{",
"$",
"column",
"=",
"$",
"this",
"->",
"getColumn",
"(",
"$",
"rulesArray",
")",
";",
"$",
"attributes",
"=",
"$",
"this",
"->",
"getAttributes",
"(",
"$",
"column",
",",
"$",
"rulesArray",
")",
";",
"$",
"parsed",
"[",
"$",
"column",
"]",
"=",
"$",
"attributes",
";",
"}",
"return",
"$",
"parsed",
";",
"}"
] | Parse a string to array of formatted rules.
@param string $rules
@return array | [
"Parse",
"a",
"string",
"to",
"array",
"of",
"formatted",
"rules",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/Migrations/RulesParser.php#L49-L60 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/RepositoryEloquentGenerator.php | RepositoryEloquentGenerator.getFillable | public function getFillable()
{
if (!$this->fillable) {
return '[]';
}
$results = '[' . PHP_EOL;
foreach ($this->getSchemaParser()->toArray() as $column => $value) {
$results .= "\t\t'{$column}'," . PHP_EOL;
}
return $results . "\t" . ']';
} | php | public function getFillable()
{
if (!$this->fillable) {
return '[]';
}
$results = '[' . PHP_EOL;
foreach ($this->getSchemaParser()->toArray() as $column => $value) {
$results .= "\t\t'{$column}'," . PHP_EOL;
}
return $results . "\t" . ']';
} | [
"public",
"function",
"getFillable",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"fillable",
")",
"{",
"return",
"'[]'",
";",
"}",
"$",
"results",
"=",
"'['",
".",
"PHP_EOL",
";",
"foreach",
"(",
"$",
"this",
"->",
"getSchemaParser",
"(",
")",
"->",
"toArray",
"(",
")",
"as",
"$",
"column",
"=>",
"$",
"value",
")",
"{",
"$",
"results",
".=",
"\"\\t\\t'{$column}',\"",
".",
"PHP_EOL",
";",
"}",
"return",
"$",
"results",
".",
"\"\\t\"",
".",
"']'",
";",
"}"
] | Get the fillable attributes.
@return string | [
"Get",
"the",
"fillable",
"attributes",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/RepositoryEloquentGenerator.php#L88-L100 | train |
andersao/l5-repository | src/Prettus/Repository/Traits/CacheableRepository.php | CacheableRepository.getCacheRepository | public function getCacheRepository()
{
if (is_null($this->cacheRepository)) {
$this->cacheRepository = app(config('repository.cache.repository', 'cache'));
}
return $this->cacheRepository;
} | php | public function getCacheRepository()
{
if (is_null($this->cacheRepository)) {
$this->cacheRepository = app(config('repository.cache.repository', 'cache'));
}
return $this->cacheRepository;
} | [
"public",
"function",
"getCacheRepository",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"cacheRepository",
")",
")",
"{",
"$",
"this",
"->",
"cacheRepository",
"=",
"app",
"(",
"config",
"(",
"'repository.cache.repository'",
",",
"'cache'",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"cacheRepository",
";",
"}"
] | Return instance of Cache Repository
@return CacheRepository | [
"Return",
"instance",
"of",
"Cache",
"Repository"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Traits/CacheableRepository.php#L43-L50 | train |
andersao/l5-repository | src/Prettus/Repository/Traits/CacheableRepository.php | CacheableRepository.serializeCriteria | protected function serializeCriteria()
{
try {
return serialize($this->getCriteria());
} catch (Exception $e) {
return serialize($this->getCriteria()->map(function ($criterion) {
return $this->serializeCriterion($criterion);
}));
}
} | php | protected function serializeCriteria()
{
try {
return serialize($this->getCriteria());
} catch (Exception $e) {
return serialize($this->getCriteria()->map(function ($criterion) {
return $this->serializeCriterion($criterion);
}));
}
} | [
"protected",
"function",
"serializeCriteria",
"(",
")",
"{",
"try",
"{",
"return",
"serialize",
"(",
"$",
"this",
"->",
"getCriteria",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"serialize",
"(",
"$",
"this",
"->",
"getCriteria",
"(",
")",
"->",
"map",
"(",
"function",
"(",
"$",
"criterion",
")",
"{",
"return",
"$",
"this",
"->",
"serializeCriterion",
"(",
"$",
"criterion",
")",
";",
"}",
")",
")",
";",
"}",
"}"
] | Serialize the criteria making sure the Closures are taken care of.
@return string | [
"Serialize",
"the",
"criteria",
"making",
"sure",
"the",
"Closures",
"are",
"taken",
"care",
"of",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Traits/CacheableRepository.php#L140-L149 | train |
andersao/l5-repository | src/Prettus/Repository/Traits/CacheableRepository.php | CacheableRepository.serializeCriterion | protected function serializeCriterion($criterion)
{
try {
serialize($criterion);
return $criterion;
} catch (Exception $e) {
// We want to take care of the closure serialization errors,
// other than that we will simply re-throw the exception.
if ($e->getMessage() !== "Serialization of 'Closure' is not allowed") {
throw $e;
}
$r = new ReflectionObject($criterion);
return [
'hash' => md5((string) $r),
'properties' => $r->getProperties(),
];
}
} | php | protected function serializeCriterion($criterion)
{
try {
serialize($criterion);
return $criterion;
} catch (Exception $e) {
// We want to take care of the closure serialization errors,
// other than that we will simply re-throw the exception.
if ($e->getMessage() !== "Serialization of 'Closure' is not allowed") {
throw $e;
}
$r = new ReflectionObject($criterion);
return [
'hash' => md5((string) $r),
'properties' => $r->getProperties(),
];
}
} | [
"protected",
"function",
"serializeCriterion",
"(",
"$",
"criterion",
")",
"{",
"try",
"{",
"serialize",
"(",
"$",
"criterion",
")",
";",
"return",
"$",
"criterion",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"// We want to take care of the closure serialization errors,",
"// other than that we will simply re-throw the exception.",
"if",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
"!==",
"\"Serialization of 'Closure' is not allowed\"",
")",
"{",
"throw",
"$",
"e",
";",
"}",
"$",
"r",
"=",
"new",
"ReflectionObject",
"(",
"$",
"criterion",
")",
";",
"return",
"[",
"'hash'",
"=>",
"md5",
"(",
"(",
"string",
")",
"$",
"r",
")",
",",
"'properties'",
"=>",
"$",
"r",
"->",
"getProperties",
"(",
")",
",",
"]",
";",
"}",
"}"
] | Serialize single criterion with customized serialization of Closures.
@param \Prettus\Repository\Contracts\CriteriaInterface $criterion
@return \Prettus\Repository\Contracts\CriteriaInterface|array
@throws \Exception | [
"Serialize",
"single",
"criterion",
"with",
"customized",
"serialization",
"of",
"Closures",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Traits/CacheableRepository.php#L159-L179 | train |
andersao/l5-repository | src/Prettus/Repository/Traits/ComparesVersionsTrait.php | ComparesVersionsTrait.versionCompare | public function versionCompare($frameworkVersion, $compareVersion, $operator = null)
{
// Lumen (5.5.2) (Laravel Components 5.5.*)
$lumenPattern = '/Lumen \((\d\.\d\.[\d|\*])\)( \(Laravel Components (\d\.\d\.[\d|\*])\))?/';
if (preg_match($lumenPattern, $frameworkVersion, $matches)) {
$frameworkVersion = isset($matches[3]) ? $matches[3] : $matches[1]; // Prefer Laravel Components version.
}
return version_compare($frameworkVersion, $compareVersion, $operator);
} | php | public function versionCompare($frameworkVersion, $compareVersion, $operator = null)
{
// Lumen (5.5.2) (Laravel Components 5.5.*)
$lumenPattern = '/Lumen \((\d\.\d\.[\d|\*])\)( \(Laravel Components (\d\.\d\.[\d|\*])\))?/';
if (preg_match($lumenPattern, $frameworkVersion, $matches)) {
$frameworkVersion = isset($matches[3]) ? $matches[3] : $matches[1]; // Prefer Laravel Components version.
}
return version_compare($frameworkVersion, $compareVersion, $operator);
} | [
"public",
"function",
"versionCompare",
"(",
"$",
"frameworkVersion",
",",
"$",
"compareVersion",
",",
"$",
"operator",
"=",
"null",
")",
"{",
"// Lumen (5.5.2) (Laravel Components 5.5.*)",
"$",
"lumenPattern",
"=",
"'/Lumen \\((\\d\\.\\d\\.[\\d|\\*])\\)( \\(Laravel Components (\\d\\.\\d\\.[\\d|\\*])\\))?/'",
";",
"if",
"(",
"preg_match",
"(",
"$",
"lumenPattern",
",",
"$",
"frameworkVersion",
",",
"$",
"matches",
")",
")",
"{",
"$",
"frameworkVersion",
"=",
"isset",
"(",
"$",
"matches",
"[",
"3",
"]",
")",
"?",
"$",
"matches",
"[",
"3",
"]",
":",
"$",
"matches",
"[",
"1",
"]",
";",
"// Prefer Laravel Components version.",
"}",
"return",
"version_compare",
"(",
"$",
"frameworkVersion",
",",
"$",
"compareVersion",
",",
"$",
"operator",
")",
";",
"}"
] | Version compare function that can compare both Laravel and Lumen versions.
@param string $frameworkVersion
@param string $compareVersion
@param string|null $operator
@return mixed | [
"Version",
"compare",
"function",
"that",
"can",
"compare",
"both",
"Laravel",
"and",
"Lumen",
"versions",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Traits/ComparesVersionsTrait.php#L19-L29 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/ValidatorGenerator.php | ValidatorGenerator.getRules | public function getRules()
{
if (!$this->rules) {
return '[]';
}
$results = '[' . PHP_EOL;
foreach ($this->getSchemaParser()->toArray() as $column => $value) {
$results .= "\t\t'{$column}'\t=>'\t{$value}'," . PHP_EOL;
}
return $results . "\t" . ']';
} | php | public function getRules()
{
if (!$this->rules) {
return '[]';
}
$results = '[' . PHP_EOL;
foreach ($this->getSchemaParser()->toArray() as $column => $value) {
$results .= "\t\t'{$column}'\t=>'\t{$value}'," . PHP_EOL;
}
return $results . "\t" . ']';
} | [
"public",
"function",
"getRules",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"rules",
")",
"{",
"return",
"'[]'",
";",
"}",
"$",
"results",
"=",
"'['",
".",
"PHP_EOL",
";",
"foreach",
"(",
"$",
"this",
"->",
"getSchemaParser",
"(",
")",
"->",
"toArray",
"(",
")",
"as",
"$",
"column",
"=>",
"$",
"value",
")",
"{",
"$",
"results",
".=",
"\"\\t\\t'{$column}'\\t=>'\\t{$value}',\"",
".",
"PHP_EOL",
";",
"}",
"return",
"$",
"results",
".",
"\"\\t\"",
".",
"']'",
";",
"}"
] | Get the rules.
@return string | [
"Get",
"the",
"rules",
"."
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/ValidatorGenerator.php#L80-L92 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/ControllerGenerator.php | ControllerGenerator.getValidator | public function getValidator()
{
$validatorGenerator = new ValidatorGenerator([
'name' => $this->name,
]);
$validator = $validatorGenerator->getRootNamespace() . '\\' . $validatorGenerator->getName();
return 'use ' . str_replace([
"\\",
'/'
], '\\', $validator) . 'Validator;';
} | php | public function getValidator()
{
$validatorGenerator = new ValidatorGenerator([
'name' => $this->name,
]);
$validator = $validatorGenerator->getRootNamespace() . '\\' . $validatorGenerator->getName();
return 'use ' . str_replace([
"\\",
'/'
], '\\', $validator) . 'Validator;';
} | [
"public",
"function",
"getValidator",
"(",
")",
"{",
"$",
"validatorGenerator",
"=",
"new",
"ValidatorGenerator",
"(",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"name",
",",
"]",
")",
";",
"$",
"validator",
"=",
"$",
"validatorGenerator",
"->",
"getRootNamespace",
"(",
")",
".",
"'\\\\'",
".",
"$",
"validatorGenerator",
"->",
"getName",
"(",
")",
";",
"return",
"'use '",
".",
"str_replace",
"(",
"[",
"\"\\\\\"",
",",
"'/'",
"]",
",",
"'\\\\'",
",",
"$",
"validator",
")",
".",
"'Validator;'",
";",
"}"
] | Gets validator full class name
@return string | [
"Gets",
"validator",
"full",
"class",
"name"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/ControllerGenerator.php#L114-L126 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/ControllerGenerator.php | ControllerGenerator.getRepository | public function getRepository()
{
$repositoryGenerator = new RepositoryInterfaceGenerator([
'name' => $this->name,
]);
$repository = $repositoryGenerator->getRootNamespace() . '\\' . $repositoryGenerator->getName();
return 'use ' . str_replace([
"\\",
'/'
], '\\', $repository) . 'Repository;';
} | php | public function getRepository()
{
$repositoryGenerator = new RepositoryInterfaceGenerator([
'name' => $this->name,
]);
$repository = $repositoryGenerator->getRootNamespace() . '\\' . $repositoryGenerator->getName();
return 'use ' . str_replace([
"\\",
'/'
], '\\', $repository) . 'Repository;';
} | [
"public",
"function",
"getRepository",
"(",
")",
"{",
"$",
"repositoryGenerator",
"=",
"new",
"RepositoryInterfaceGenerator",
"(",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"name",
",",
"]",
")",
";",
"$",
"repository",
"=",
"$",
"repositoryGenerator",
"->",
"getRootNamespace",
"(",
")",
".",
"'\\\\'",
".",
"$",
"repositoryGenerator",
"->",
"getName",
"(",
")",
";",
"return",
"'use '",
".",
"str_replace",
"(",
"[",
"\"\\\\\"",
",",
"'/'",
"]",
",",
"'\\\\'",
",",
"$",
"repository",
")",
".",
"'Repository;'",
";",
"}"
] | Gets repository full class name
@return string | [
"Gets",
"repository",
"full",
"class",
"name"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/ControllerGenerator.php#L134-L146 | train |
andersao/l5-repository | src/Prettus/Repository/Generators/BindingsGenerator.php | BindingsGenerator.getEloquentRepository | public function getEloquentRepository()
{
$repositoryGenerator = new RepositoryEloquentGenerator([
'name' => $this->name,
]);
$repository = $repositoryGenerator->getRootNamespace() . '\\' . $repositoryGenerator->getName();
return str_replace([
"\\",
'/'
], '\\', $repository) . 'RepositoryEloquent';
} | php | public function getEloquentRepository()
{
$repositoryGenerator = new RepositoryEloquentGenerator([
'name' => $this->name,
]);
$repository = $repositoryGenerator->getRootNamespace() . '\\' . $repositoryGenerator->getName();
return str_replace([
"\\",
'/'
], '\\', $repository) . 'RepositoryEloquent';
} | [
"public",
"function",
"getEloquentRepository",
"(",
")",
"{",
"$",
"repositoryGenerator",
"=",
"new",
"RepositoryEloquentGenerator",
"(",
"[",
"'name'",
"=>",
"$",
"this",
"->",
"name",
",",
"]",
")",
";",
"$",
"repository",
"=",
"$",
"repositoryGenerator",
"->",
"getRootNamespace",
"(",
")",
".",
"'\\\\'",
".",
"$",
"repositoryGenerator",
"->",
"getName",
"(",
")",
";",
"return",
"str_replace",
"(",
"[",
"\"\\\\\"",
",",
"'/'",
"]",
",",
"'\\\\'",
",",
"$",
"repository",
")",
".",
"'RepositoryEloquent'",
";",
"}"
] | Gets eloquent repository full class name
@return string | [
"Gets",
"eloquent",
"repository",
"full",
"class",
"name"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Generators/BindingsGenerator.php#L90-L102 | train |
andersao/l5-repository | src/Prettus/Repository/Eloquent/BaseRepository.php | BaseRepository.validator | public function validator()
{
if (isset($this->rules) && !is_null($this->rules) && is_array($this->rules) && !empty($this->rules)) {
if (class_exists('Prettus\Validator\LaravelValidator')) {
$validator = app('Prettus\Validator\LaravelValidator');
if ($validator instanceof ValidatorInterface) {
$validator->setRules($this->rules);
return $validator;
}
} else {
throw new Exception(trans('repository::packages.prettus_laravel_validation_required'));
}
}
return null;
} | php | public function validator()
{
if (isset($this->rules) && !is_null($this->rules) && is_array($this->rules) && !empty($this->rules)) {
if (class_exists('Prettus\Validator\LaravelValidator')) {
$validator = app('Prettus\Validator\LaravelValidator');
if ($validator instanceof ValidatorInterface) {
$validator->setRules($this->rules);
return $validator;
}
} else {
throw new Exception(trans('repository::packages.prettus_laravel_validation_required'));
}
}
return null;
} | [
"public",
"function",
"validator",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"rules",
")",
"&&",
"!",
"is_null",
"(",
"$",
"this",
"->",
"rules",
")",
"&&",
"is_array",
"(",
"$",
"this",
"->",
"rules",
")",
"&&",
"!",
"empty",
"(",
"$",
"this",
"->",
"rules",
")",
")",
"{",
"if",
"(",
"class_exists",
"(",
"'Prettus\\Validator\\LaravelValidator'",
")",
")",
"{",
"$",
"validator",
"=",
"app",
"(",
"'Prettus\\Validator\\LaravelValidator'",
")",
";",
"if",
"(",
"$",
"validator",
"instanceof",
"ValidatorInterface",
")",
"{",
"$",
"validator",
"->",
"setRules",
"(",
"$",
"this",
"->",
"rules",
")",
";",
"return",
"$",
"validator",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Exception",
"(",
"trans",
"(",
"'repository::packages.prettus_laravel_validation_required'",
")",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Specify Validator class name of Prettus\Validator\Contracts\ValidatorInterface
@return null
@throws Exception | [
"Specify",
"Validator",
"class",
"name",
"of",
"Prettus",
"\\",
"Validator",
"\\",
"Contracts",
"\\",
"ValidatorInterface"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Eloquent/BaseRepository.php#L139-L156 | train |
andersao/l5-repository | src/Prettus/Repository/Eloquent/BaseRepository.php | BaseRepository.first | public function first($columns = ['*'])
{
$this->applyCriteria();
$this->applyScope();
$results = $this->model->first($columns);
$this->resetModel();
return $this->parserResult($results);
} | php | public function first($columns = ['*'])
{
$this->applyCriteria();
$this->applyScope();
$results = $this->model->first($columns);
$this->resetModel();
return $this->parserResult($results);
} | [
"public",
"function",
"first",
"(",
"$",
"columns",
"=",
"[",
"'*'",
"]",
")",
"{",
"$",
"this",
"->",
"applyCriteria",
"(",
")",
";",
"$",
"this",
"->",
"applyScope",
"(",
")",
";",
"$",
"results",
"=",
"$",
"this",
"->",
"model",
"->",
"first",
"(",
"$",
"columns",
")",
";",
"$",
"this",
"->",
"resetModel",
"(",
")",
";",
"return",
"$",
"this",
"->",
"parserResult",
"(",
"$",
"results",
")",
";",
"}"
] | Retrieve first data of repository
@param array $columns
@return mixed | [
"Retrieve",
"first",
"data",
"of",
"repository"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Eloquent/BaseRepository.php#L358-L368 | train |
andersao/l5-repository | src/Prettus/Repository/Eloquent/BaseRepository.php | BaseRepository.find | public function find($id, $columns = ['*'])
{
$this->applyCriteria();
$this->applyScope();
$model = $this->model->findOrFail($id, $columns);
$this->resetModel();
return $this->parserResult($model);
} | php | public function find($id, $columns = ['*'])
{
$this->applyCriteria();
$this->applyScope();
$model = $this->model->findOrFail($id, $columns);
$this->resetModel();
return $this->parserResult($model);
} | [
"public",
"function",
"find",
"(",
"$",
"id",
",",
"$",
"columns",
"=",
"[",
"'*'",
"]",
")",
"{",
"$",
"this",
"->",
"applyCriteria",
"(",
")",
";",
"$",
"this",
"->",
"applyScope",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"model",
"->",
"findOrFail",
"(",
"$",
"id",
",",
"$",
"columns",
")",
";",
"$",
"this",
"->",
"resetModel",
"(",
")",
";",
"return",
"$",
"this",
"->",
"parserResult",
"(",
"$",
"model",
")",
";",
"}"
] | Find data by id
@param $id
@param array $columns
@return mixed | [
"Find",
"data",
"by",
"id"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Eloquent/BaseRepository.php#L458-L466 | train |
andersao/l5-repository | src/Prettus/Repository/Eloquent/BaseRepository.php | BaseRepository.findWhereIn | public function findWhereIn($field, array $values, $columns = ['*'])
{
$this->applyCriteria();
$this->applyScope();
$model = $this->model->whereIn($field, $values)->get($columns);
$this->resetModel();
return $this->parserResult($model);
} | php | public function findWhereIn($field, array $values, $columns = ['*'])
{
$this->applyCriteria();
$this->applyScope();
$model = $this->model->whereIn($field, $values)->get($columns);
$this->resetModel();
return $this->parserResult($model);
} | [
"public",
"function",
"findWhereIn",
"(",
"$",
"field",
",",
"array",
"$",
"values",
",",
"$",
"columns",
"=",
"[",
"'*'",
"]",
")",
"{",
"$",
"this",
"->",
"applyCriteria",
"(",
")",
";",
"$",
"this",
"->",
"applyScope",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"model",
"->",
"whereIn",
"(",
"$",
"field",
",",
"$",
"values",
")",
"->",
"get",
"(",
"$",
"columns",
")",
";",
"$",
"this",
"->",
"resetModel",
"(",
")",
";",
"return",
"$",
"this",
"->",
"parserResult",
"(",
"$",
"model",
")",
";",
"}"
] | Find data by multiple values in one field
@param $field
@param array $values
@param array $columns
@return mixed | [
"Find",
"data",
"by",
"multiple",
"values",
"in",
"one",
"field"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Eloquent/BaseRepository.php#L517-L525 | train |
andersao/l5-repository | src/Prettus/Repository/Eloquent/BaseRepository.php | BaseRepository.findWhereNotIn | public function findWhereNotIn($field, array $values, $columns = ['*'])
{
$this->applyCriteria();
$this->applyScope();
$model = $this->model->whereNotIn($field, $values)->get($columns);
$this->resetModel();
return $this->parserResult($model);
} | php | public function findWhereNotIn($field, array $values, $columns = ['*'])
{
$this->applyCriteria();
$this->applyScope();
$model = $this->model->whereNotIn($field, $values)->get($columns);
$this->resetModel();
return $this->parserResult($model);
} | [
"public",
"function",
"findWhereNotIn",
"(",
"$",
"field",
",",
"array",
"$",
"values",
",",
"$",
"columns",
"=",
"[",
"'*'",
"]",
")",
"{",
"$",
"this",
"->",
"applyCriteria",
"(",
")",
";",
"$",
"this",
"->",
"applyScope",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"model",
"->",
"whereNotIn",
"(",
"$",
"field",
",",
"$",
"values",
")",
"->",
"get",
"(",
"$",
"columns",
")",
";",
"$",
"this",
"->",
"resetModel",
"(",
")",
";",
"return",
"$",
"this",
"->",
"parserResult",
"(",
"$",
"model",
")",
";",
"}"
] | Find data by excluding multiple values in one field
@param $field
@param array $values
@param array $columns
@return mixed | [
"Find",
"data",
"by",
"excluding",
"multiple",
"values",
"in",
"one",
"field"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Eloquent/BaseRepository.php#L536-L544 | train |
andersao/l5-repository | src/Prettus/Repository/Eloquent/BaseRepository.php | BaseRepository.whereHas | public function whereHas($relation, $closure)
{
$this->model = $this->model->whereHas($relation, $closure);
return $this;
} | php | public function whereHas($relation, $closure)
{
$this->model = $this->model->whereHas($relation, $closure);
return $this;
} | [
"public",
"function",
"whereHas",
"(",
"$",
"relation",
",",
"$",
"closure",
")",
"{",
"$",
"this",
"->",
"model",
"=",
"$",
"this",
"->",
"model",
"->",
"whereHas",
"(",
"$",
"relation",
",",
"$",
"closure",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Load relation with closure
@param string $relation
@param closure $closure
@return $this | [
"Load",
"relation",
"with",
"closure"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Eloquent/BaseRepository.php#L759-L764 | train |
andersao/l5-repository | src/Prettus/Repository/Eloquent/BaseRepository.php | BaseRepository.pushCriteria | public function pushCriteria($criteria)
{
if (is_string($criteria)) {
$criteria = new $criteria;
}
if (!$criteria instanceof CriteriaInterface) {
throw new RepositoryException("Class " . get_class($criteria) . " must be an instance of Prettus\\Repository\\Contracts\\CriteriaInterface");
}
$this->criteria->push($criteria);
return $this;
} | php | public function pushCriteria($criteria)
{
if (is_string($criteria)) {
$criteria = new $criteria;
}
if (!$criteria instanceof CriteriaInterface) {
throw new RepositoryException("Class " . get_class($criteria) . " must be an instance of Prettus\\Repository\\Contracts\\CriteriaInterface");
}
$this->criteria->push($criteria);
return $this;
} | [
"public",
"function",
"pushCriteria",
"(",
"$",
"criteria",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"criteria",
")",
")",
"{",
"$",
"criteria",
"=",
"new",
"$",
"criteria",
";",
"}",
"if",
"(",
"!",
"$",
"criteria",
"instanceof",
"CriteriaInterface",
")",
"{",
"throw",
"new",
"RepositoryException",
"(",
"\"Class \"",
".",
"get_class",
"(",
"$",
"criteria",
")",
".",
"\" must be an instance of Prettus\\\\Repository\\\\Contracts\\\\CriteriaInterface\"",
")",
";",
"}",
"$",
"this",
"->",
"criteria",
"->",
"push",
"(",
"$",
"criteria",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Push Criteria for filter the query
@param $criteria
@return $this
@throws \Prettus\Repository\Exceptions\RepositoryException | [
"Push",
"Criteria",
"for",
"filter",
"the",
"query"
] | f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4 | https://github.com/andersao/l5-repository/blob/f2008d8ff8af50036d2d155c0b5dbb07cbcd0ee4/src/Prettus/Repository/Eloquent/BaseRepository.php#L809-L820 | train |