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 |
---|---|---|---|---|---|---|---|---|---|---|---|
Sylius/Sylius | src/Sylius/Bundle/CoreBundle/EventListener/ChannelDeletionListener.php | ChannelDeletionListener.onChannelPreDelete | public function onChannelPreDelete(ResourceControllerEvent $event): void
{
$channel = $event->getSubject();
if (!$channel instanceof ChannelInterface) {
throw new UnexpectedTypeException(
$channel,
ChannelInterface::class
);
}
$results = $this->channelRepository->findBy(['enabled' => true]);
if (!$results || (count($results) === 1 && current($results) === $channel)) {
$event->stop('sylius.channel.delete_error');
}
} | php | public function onChannelPreDelete(ResourceControllerEvent $event): void
{
$channel = $event->getSubject();
if (!$channel instanceof ChannelInterface) {
throw new UnexpectedTypeException(
$channel,
ChannelInterface::class
);
}
$results = $this->channelRepository->findBy(['enabled' => true]);
if (!$results || (count($results) === 1 && current($results) === $channel)) {
$event->stop('sylius.channel.delete_error');
}
} | [
"public",
"function",
"onChannelPreDelete",
"(",
"ResourceControllerEvent",
"$",
"event",
")",
":",
"void",
"{",
"$",
"channel",
"=",
"$",
"event",
"->",
"getSubject",
"(",
")",
";",
"if",
"(",
"!",
"$",
"channel",
"instanceof",
"ChannelInterface",
")",
"{",
"throw",
"new",
"UnexpectedTypeException",
"(",
"$",
"channel",
",",
"ChannelInterface",
"::",
"class",
")",
";",
"}",
"$",
"results",
"=",
"$",
"this",
"->",
"channelRepository",
"->",
"findBy",
"(",
"[",
"'enabled'",
"=>",
"true",
"]",
")",
";",
"if",
"(",
"!",
"$",
"results",
"||",
"(",
"count",
"(",
"$",
"results",
")",
"===",
"1",
"&&",
"current",
"(",
"$",
"results",
")",
"===",
"$",
"channel",
")",
")",
"{",
"$",
"event",
"->",
"stop",
"(",
"'sylius.channel.delete_error'",
")",
";",
"}",
"}"
] | Prevent channel deletion if no more channels enabled. | [
"Prevent",
"channel",
"deletion",
"if",
"no",
"more",
"channels",
"enabled",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Bundle/CoreBundle/EventListener/ChannelDeletionListener.php#L34-L50 | train |
Sylius/Sylius | src/Sylius/Component/Core/Model/OrderItem.php | OrderItem.getTaxTotal | public function getTaxTotal(): int
{
$taxTotal = 0;
foreach ($this->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT) as $taxAdjustment) {
$taxTotal += $taxAdjustment->getAmount();
}
foreach ($this->units as $unit) {
$taxTotal += $unit->getTaxTotal();
}
return $taxTotal;
} | php | public function getTaxTotal(): int
{
$taxTotal = 0;
foreach ($this->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT) as $taxAdjustment) {
$taxTotal += $taxAdjustment->getAmount();
}
foreach ($this->units as $unit) {
$taxTotal += $unit->getTaxTotal();
}
return $taxTotal;
} | [
"public",
"function",
"getTaxTotal",
"(",
")",
":",
"int",
"{",
"$",
"taxTotal",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"getAdjustments",
"(",
"AdjustmentInterface",
"::",
"TAX_ADJUSTMENT",
")",
"as",
"$",
"taxAdjustment",
")",
"{",
"$",
"taxTotal",
"+=",
"$",
"taxAdjustment",
"->",
"getAmount",
"(",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"units",
"as",
"$",
"unit",
")",
"{",
"$",
"taxTotal",
"+=",
"$",
"unit",
"->",
"getTaxTotal",
"(",
")",
";",
"}",
"return",
"$",
"taxTotal",
";",
"}"
] | Returns sum of neutral and non neutral tax adjustments on order item and total tax of units.
{@inheritdoc} | [
"Returns",
"sum",
"of",
"neutral",
"and",
"non",
"neutral",
"tax",
"adjustments",
"on",
"order",
"item",
"and",
"total",
"tax",
"of",
"units",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Component/Core/Model/OrderItem.php#L96-L109 | train |
Sylius/Sylius | src/Sylius/Bundle/CoreBundle/Validator/Constraints/HasEnabledEntityValidator.php | HasEnabledEntityValidator.isLastEnabledEntity | private function isLastEnabledEntity($result, $entity): bool
{
return !$result || 0 === count($result)
|| (1 === count($result) && $entity === ($result instanceof \Iterator ? $result->current() : current($result)));
} | php | private function isLastEnabledEntity($result, $entity): bool
{
return !$result || 0 === count($result)
|| (1 === count($result) && $entity === ($result instanceof \Iterator ? $result->current() : current($result)));
} | [
"private",
"function",
"isLastEnabledEntity",
"(",
"$",
"result",
",",
"$",
"entity",
")",
":",
"bool",
"{",
"return",
"!",
"$",
"result",
"||",
"0",
"===",
"count",
"(",
"$",
"result",
")",
"||",
"(",
"1",
"===",
"count",
"(",
"$",
"result",
")",
"&&",
"$",
"entity",
"===",
"(",
"$",
"result",
"instanceof",
"\\",
"Iterator",
"?",
"$",
"result",
"->",
"current",
"(",
")",
":",
"current",
"(",
"$",
"result",
")",
")",
")",
";",
"}"
] | If no entity matched the query criteria or a single entity matched, which is the same as the entity being
validated, the entity is the last enabled entity available.
@param array|\Iterator $result
@param object $entity | [
"If",
"no",
"entity",
"matched",
"the",
"query",
"criteria",
"or",
"a",
"single",
"entity",
"matched",
"which",
"is",
"the",
"same",
"as",
"the",
"entity",
"being",
"validated",
"the",
"entity",
"is",
"the",
"last",
"enabled",
"entity",
"available",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Bundle/CoreBundle/Validator/Constraints/HasEnabledEntityValidator.php#L90-L94 | train |
Sylius/Sylius | src/Sylius/Component/Order/Model/Order.php | Order.recalculateTotal | protected function recalculateTotal(): void
{
$this->total = $this->itemsTotal + $this->adjustmentsTotal;
if ($this->total < 0) {
$this->total = 0;
}
} | php | protected function recalculateTotal(): void
{
$this->total = $this->itemsTotal + $this->adjustmentsTotal;
if ($this->total < 0) {
$this->total = 0;
}
} | [
"protected",
"function",
"recalculateTotal",
"(",
")",
":",
"void",
"{",
"$",
"this",
"->",
"total",
"=",
"$",
"this",
"->",
"itemsTotal",
"+",
"$",
"this",
"->",
"adjustmentsTotal",
";",
"if",
"(",
"$",
"this",
"->",
"total",
"<",
"0",
")",
"{",
"$",
"this",
"->",
"total",
"=",
"0",
";",
"}",
"}"
] | Items total + Adjustments total. | [
"Items",
"total",
"+",
"Adjustments",
"total",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Component/Order/Model/Order.php#L406-L413 | train |
Sylius/Sylius | src/Sylius/Bundle/UserBundle/Controller/SecurityController.php | SecurityController.loginAction | public function loginAction(Request $request): Response
{
$authenticationUtils = $this->get('security.authentication_utils');
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
$options = $request->attributes->get('_sylius');
$template = $options['template'] ?? null;
Assert::notNull($template, 'Template is not configured.');
$formType = $options['form'] ?? UserLoginType::class;
$form = $this->get('form.factory')->createNamed('', $formType);
return $this->render($template, [
'form' => $form->createView(),
'last_username' => $lastUsername,
'error' => $error,
]);
} | php | public function loginAction(Request $request): Response
{
$authenticationUtils = $this->get('security.authentication_utils');
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
$options = $request->attributes->get('_sylius');
$template = $options['template'] ?? null;
Assert::notNull($template, 'Template is not configured.');
$formType = $options['form'] ?? UserLoginType::class;
$form = $this->get('form.factory')->createNamed('', $formType);
return $this->render($template, [
'form' => $form->createView(),
'last_username' => $lastUsername,
'error' => $error,
]);
} | [
"public",
"function",
"loginAction",
"(",
"Request",
"$",
"request",
")",
":",
"Response",
"{",
"$",
"authenticationUtils",
"=",
"$",
"this",
"->",
"get",
"(",
"'security.authentication_utils'",
")",
";",
"$",
"error",
"=",
"$",
"authenticationUtils",
"->",
"getLastAuthenticationError",
"(",
")",
";",
"$",
"lastUsername",
"=",
"$",
"authenticationUtils",
"->",
"getLastUsername",
"(",
")",
";",
"$",
"options",
"=",
"$",
"request",
"->",
"attributes",
"->",
"get",
"(",
"'_sylius'",
")",
";",
"$",
"template",
"=",
"$",
"options",
"[",
"'template'",
"]",
"??",
"null",
";",
"Assert",
"::",
"notNull",
"(",
"$",
"template",
",",
"'Template is not configured.'",
")",
";",
"$",
"formType",
"=",
"$",
"options",
"[",
"'form'",
"]",
"??",
"UserLoginType",
"::",
"class",
";",
"$",
"form",
"=",
"$",
"this",
"->",
"get",
"(",
"'form.factory'",
")",
"->",
"createNamed",
"(",
"''",
",",
"$",
"formType",
")",
";",
"return",
"$",
"this",
"->",
"render",
"(",
"$",
"template",
",",
"[",
"'form'",
"=>",
"$",
"form",
"->",
"createView",
"(",
")",
",",
"'last_username'",
"=>",
"$",
"lastUsername",
",",
"'error'",
"=>",
"$",
"error",
",",
"]",
")",
";",
"}"
] | Login form action. | [
"Login",
"form",
"action",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Bundle/UserBundle/Controller/SecurityController.php#L27-L46 | train |
Sylius/Sylius | src/Sylius/Component/Core/Model/Order.php | Order.getTaxTotal | public function getTaxTotal(): int
{
$taxTotal = 0;
foreach ($this->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT) as $taxAdjustment) {
$taxTotal += $taxAdjustment->getAmount();
}
foreach ($this->items as $item) {
$taxTotal += $item->getTaxTotal();
}
return $taxTotal;
} | php | public function getTaxTotal(): int
{
$taxTotal = 0;
foreach ($this->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT) as $taxAdjustment) {
$taxTotal += $taxAdjustment->getAmount();
}
foreach ($this->items as $item) {
$taxTotal += $item->getTaxTotal();
}
return $taxTotal;
} | [
"public",
"function",
"getTaxTotal",
"(",
")",
":",
"int",
"{",
"$",
"taxTotal",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"getAdjustments",
"(",
"AdjustmentInterface",
"::",
"TAX_ADJUSTMENT",
")",
"as",
"$",
"taxAdjustment",
")",
"{",
"$",
"taxTotal",
"+=",
"$",
"taxAdjustment",
"->",
"getAmount",
"(",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"items",
"as",
"$",
"item",
")",
"{",
"$",
"taxTotal",
"+=",
"$",
"item",
"->",
"getTaxTotal",
"(",
")",
";",
"}",
"return",
"$",
"taxTotal",
";",
"}"
] | Returns sum of neutral and non neutral tax adjustments on order and total tax of order items.
{@inheritdoc} | [
"Returns",
"sum",
"of",
"neutral",
"and",
"non",
"neutral",
"tax",
"adjustments",
"on",
"order",
"and",
"total",
"tax",
"of",
"order",
"items",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Component/Core/Model/Order.php#L476-L488 | train |
Sylius/Sylius | src/Sylius/Component/Core/Model/Order.php | Order.getShippingTotal | public function getShippingTotal(): int
{
$shippingTotal = $this->getAdjustmentsTotal(AdjustmentInterface::SHIPPING_ADJUSTMENT);
$shippingTotal += $this->getAdjustmentsTotal(AdjustmentInterface::ORDER_SHIPPING_PROMOTION_ADJUSTMENT);
$shippingTotal += $this->getAdjustmentsTotal(AdjustmentInterface::TAX_ADJUSTMENT);
return $shippingTotal;
} | php | public function getShippingTotal(): int
{
$shippingTotal = $this->getAdjustmentsTotal(AdjustmentInterface::SHIPPING_ADJUSTMENT);
$shippingTotal += $this->getAdjustmentsTotal(AdjustmentInterface::ORDER_SHIPPING_PROMOTION_ADJUSTMENT);
$shippingTotal += $this->getAdjustmentsTotal(AdjustmentInterface::TAX_ADJUSTMENT);
return $shippingTotal;
} | [
"public",
"function",
"getShippingTotal",
"(",
")",
":",
"int",
"{",
"$",
"shippingTotal",
"=",
"$",
"this",
"->",
"getAdjustmentsTotal",
"(",
"AdjustmentInterface",
"::",
"SHIPPING_ADJUSTMENT",
")",
";",
"$",
"shippingTotal",
"+=",
"$",
"this",
"->",
"getAdjustmentsTotal",
"(",
"AdjustmentInterface",
"::",
"ORDER_SHIPPING_PROMOTION_ADJUSTMENT",
")",
";",
"$",
"shippingTotal",
"+=",
"$",
"this",
"->",
"getAdjustmentsTotal",
"(",
"AdjustmentInterface",
"::",
"TAX_ADJUSTMENT",
")",
";",
"return",
"$",
"shippingTotal",
";",
"}"
] | Returns shipping fee together with taxes decreased by shipping discount.
{@inheritdoc} | [
"Returns",
"shipping",
"fee",
"together",
"with",
"taxes",
"decreased",
"by",
"shipping",
"discount",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Component/Core/Model/Order.php#L495-L502 | train |
Sylius/Sylius | src/Sylius/Component/Core/Model/Order.php | Order.getOrderPromotionTotal | public function getOrderPromotionTotal(): int
{
$orderPromotionTotal = 0;
foreach ($this->items as $item) {
$orderPromotionTotal += $item->getAdjustmentsTotalRecursively(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
}
return $orderPromotionTotal;
} | php | public function getOrderPromotionTotal(): int
{
$orderPromotionTotal = 0;
foreach ($this->items as $item) {
$orderPromotionTotal += $item->getAdjustmentsTotalRecursively(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
}
return $orderPromotionTotal;
} | [
"public",
"function",
"getOrderPromotionTotal",
"(",
")",
":",
"int",
"{",
"$",
"orderPromotionTotal",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"items",
"as",
"$",
"item",
")",
"{",
"$",
"orderPromotionTotal",
"+=",
"$",
"item",
"->",
"getAdjustmentsTotalRecursively",
"(",
"AdjustmentInterface",
"::",
"ORDER_PROMOTION_ADJUSTMENT",
")",
";",
"}",
"return",
"$",
"orderPromotionTotal",
";",
"}"
] | Returns amount of order discount. Does not include order item and shipping discounts.
{@inheritdoc} | [
"Returns",
"amount",
"of",
"order",
"discount",
".",
"Does",
"not",
"include",
"order",
"item",
"and",
"shipping",
"discounts",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Component/Core/Model/Order.php#L509-L518 | train |
Sylius/Sylius | src/Sylius/Component/Order/Model/OrderItem.php | OrderItem.recalculateTotal | protected function recalculateTotal(): void
{
$this->total = $this->unitsTotal + $this->adjustmentsTotal;
if ($this->total < 0) {
$this->total = 0;
}
if (null !== $this->order) {
$this->order->recalculateItemsTotal();
}
} | php | protected function recalculateTotal(): void
{
$this->total = $this->unitsTotal + $this->adjustmentsTotal;
if ($this->total < 0) {
$this->total = 0;
}
if (null !== $this->order) {
$this->order->recalculateItemsTotal();
}
} | [
"protected",
"function",
"recalculateTotal",
"(",
")",
":",
"void",
"{",
"$",
"this",
"->",
"total",
"=",
"$",
"this",
"->",
"unitsTotal",
"+",
"$",
"this",
"->",
"adjustmentsTotal",
";",
"if",
"(",
"$",
"this",
"->",
"total",
"<",
"0",
")",
"{",
"$",
"this",
"->",
"total",
"=",
"0",
";",
"}",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"order",
")",
"{",
"$",
"this",
"->",
"order",
"->",
"recalculateItemsTotal",
"(",
")",
";",
"}",
"}"
] | Recalculates total after units total or adjustments total change. | [
"Recalculates",
"total",
"after",
"units",
"total",
"or",
"adjustments",
"total",
"change",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Component/Order/Model/OrderItem.php#L356-L367 | train |
Sylius/Sylius | src/Sylius/Bundle/CoreBundle/OAuth/UserProvider.php | UserProvider.updateUserByOAuthUserResponse | private function updateUserByOAuthUserResponse(UserInterface $user, UserResponseInterface $response): SyliusUserInterface
{
/** @var SyliusUserInterface $user */
Assert::isInstanceOf($user, SyliusUserInterface::class);
/** @var UserOAuthInterface $oauth */
$oauth = $this->oauthFactory->createNew();
$oauth->setIdentifier($response->getUsername());
$oauth->setProvider($response->getResourceOwner()->getName());
$oauth->setAccessToken($response->getAccessToken());
$oauth->setRefreshToken($response->getRefreshToken());
$user->addOAuthAccount($oauth);
$this->userManager->persist($user);
$this->userManager->flush();
return $user;
} | php | private function updateUserByOAuthUserResponse(UserInterface $user, UserResponseInterface $response): SyliusUserInterface
{
/** @var SyliusUserInterface $user */
Assert::isInstanceOf($user, SyliusUserInterface::class);
/** @var UserOAuthInterface $oauth */
$oauth = $this->oauthFactory->createNew();
$oauth->setIdentifier($response->getUsername());
$oauth->setProvider($response->getResourceOwner()->getName());
$oauth->setAccessToken($response->getAccessToken());
$oauth->setRefreshToken($response->getRefreshToken());
$user->addOAuthAccount($oauth);
$this->userManager->persist($user);
$this->userManager->flush();
return $user;
} | [
"private",
"function",
"updateUserByOAuthUserResponse",
"(",
"UserInterface",
"$",
"user",
",",
"UserResponseInterface",
"$",
"response",
")",
":",
"SyliusUserInterface",
"{",
"/** @var SyliusUserInterface $user */",
"Assert",
"::",
"isInstanceOf",
"(",
"$",
"user",
",",
"SyliusUserInterface",
"::",
"class",
")",
";",
"/** @var UserOAuthInterface $oauth */",
"$",
"oauth",
"=",
"$",
"this",
"->",
"oauthFactory",
"->",
"createNew",
"(",
")",
";",
"$",
"oauth",
"->",
"setIdentifier",
"(",
"$",
"response",
"->",
"getUsername",
"(",
")",
")",
";",
"$",
"oauth",
"->",
"setProvider",
"(",
"$",
"response",
"->",
"getResourceOwner",
"(",
")",
"->",
"getName",
"(",
")",
")",
";",
"$",
"oauth",
"->",
"setAccessToken",
"(",
"$",
"response",
"->",
"getAccessToken",
"(",
")",
")",
";",
"$",
"oauth",
"->",
"setRefreshToken",
"(",
"$",
"response",
"->",
"getRefreshToken",
"(",
")",
")",
";",
"$",
"user",
"->",
"addOAuthAccount",
"(",
"$",
"oauth",
")",
";",
"$",
"this",
"->",
"userManager",
"->",
"persist",
"(",
"$",
"user",
")",
";",
"$",
"this",
"->",
"userManager",
"->",
"flush",
"(",
")",
";",
"return",
"$",
"user",
";",
"}"
] | Attach OAuth sign-in provider account to existing user. | [
"Attach",
"OAuth",
"sign",
"-",
"in",
"provider",
"account",
"to",
"existing",
"user",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Bundle/CoreBundle/OAuth/UserProvider.php#L161-L179 | train |
Sylius/Sylius | src/Sylius/Component/User/Model/User.php | User.serialize | public function serialize(): string
{
return serialize([
$this->password,
$this->salt,
$this->usernameCanonical,
$this->username,
$this->locked,
$this->enabled,
$this->id,
$this->encoderName,
]);
} | php | public function serialize(): string
{
return serialize([
$this->password,
$this->salt,
$this->usernameCanonical,
$this->username,
$this->locked,
$this->enabled,
$this->id,
$this->encoderName,
]);
} | [
"public",
"function",
"serialize",
"(",
")",
":",
"string",
"{",
"return",
"serialize",
"(",
"[",
"$",
"this",
"->",
"password",
",",
"$",
"this",
"->",
"salt",
",",
"$",
"this",
"->",
"usernameCanonical",
",",
"$",
"this",
"->",
"username",
",",
"$",
"this",
"->",
"locked",
",",
"$",
"this",
"->",
"enabled",
",",
"$",
"this",
"->",
"id",
",",
"$",
"this",
"->",
"encoderName",
",",
"]",
")",
";",
"}"
] | The serialized data have to contain the fields used by the equals method and the username. | [
"The",
"serialized",
"data",
"have",
"to",
"contain",
"the",
"fields",
"used",
"by",
"the",
"equals",
"method",
"and",
"the",
"username",
"."
] | 8b26d4188fa81bb488612f59d2418b9472be1c79 | https://github.com/Sylius/Sylius/blob/8b26d4188fa81bb488612f59d2418b9472be1c79/src/Sylius/Component/User/Model/User.php#L508-L520 | train |
aws/aws-sdk-php | src/ClientSideMonitoring/ApiCallMonitoringMiddleware.php | ApiCallMonitoringMiddleware.wrap | public static function wrap(
callable $credentialProvider,
$options,
$region,
$service
) {
return function (callable $handler) use (
$credentialProvider,
$options,
$region,
$service
) {
return new static(
$handler,
$credentialProvider,
$options,
$region,
$service
);
};
} | php | public static function wrap(
callable $credentialProvider,
$options,
$region,
$service
) {
return function (callable $handler) use (
$credentialProvider,
$options,
$region,
$service
) {
return new static(
$handler,
$credentialProvider,
$options,
$region,
$service
);
};
} | [
"public",
"static",
"function",
"wrap",
"(",
"callable",
"$",
"credentialProvider",
",",
"$",
"options",
",",
"$",
"region",
",",
"$",
"service",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"credentialProvider",
",",
"$",
"options",
",",
"$",
"region",
",",
"$",
"service",
")",
"{",
"return",
"new",
"static",
"(",
"$",
"handler",
",",
"$",
"credentialProvider",
",",
"$",
"options",
",",
"$",
"region",
",",
"$",
"service",
")",
";",
"}",
";",
"}"
] | Standard middleware wrapper function with CSM options passed in.
@param callable $credentialProvider
@param mixed $options
@param string $region
@param string $service
@return callable | [
"Standard",
"middleware",
"wrapper",
"function",
"with",
"CSM",
"options",
"passed",
"in",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientSideMonitoring/ApiCallMonitoringMiddleware.php#L39-L59 | train |
aws/aws-sdk-php | src/Api/DocModel.php | DocModel.getOperationDocs | public function getOperationDocs($operation)
{
return isset($this->docs['operations'][$operation])
? $this->docs['operations'][$operation]
: null;
} | php | public function getOperationDocs($operation)
{
return isset($this->docs['operations'][$operation])
? $this->docs['operations'][$operation]
: null;
} | [
"public",
"function",
"getOperationDocs",
"(",
"$",
"operation",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"docs",
"[",
"'operations'",
"]",
"[",
"$",
"operation",
"]",
")",
"?",
"$",
"this",
"->",
"docs",
"[",
"'operations'",
"]",
"[",
"$",
"operation",
"]",
":",
"null",
";",
"}"
] | Retrieves documentation about an operation.
@param string $operation Name of the operation
@return null|string | [
"Retrieves",
"documentation",
"about",
"an",
"operation",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/DocModel.php#L55-L60 | train |
aws/aws-sdk-php | src/Api/DocModel.php | DocModel.getErrorDocs | public function getErrorDocs($error)
{
return isset($this->docs['shapes'][$error]['base'])
? $this->docs['shapes'][$error]['base']
: null;
} | php | public function getErrorDocs($error)
{
return isset($this->docs['shapes'][$error]['base'])
? $this->docs['shapes'][$error]['base']
: null;
} | [
"public",
"function",
"getErrorDocs",
"(",
"$",
"error",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"docs",
"[",
"'shapes'",
"]",
"[",
"$",
"error",
"]",
"[",
"'base'",
"]",
")",
"?",
"$",
"this",
"->",
"docs",
"[",
"'shapes'",
"]",
"[",
"$",
"error",
"]",
"[",
"'base'",
"]",
":",
"null",
";",
"}"
] | Retrieves documentation about an error.
@param string $error Name of the error
@return null|string | [
"Retrieves",
"documentation",
"about",
"an",
"error",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/DocModel.php#L69-L74 | train |
aws/aws-sdk-php | src/Api/DocModel.php | DocModel.getShapeDocs | public function getShapeDocs($shapeName, $parentName, $ref)
{
if (!isset($this->docs['shapes'][$shapeName])) {
return '';
}
$result = '';
$d = $this->docs['shapes'][$shapeName];
if (isset($d['refs']["{$parentName}\$${ref}"])) {
$result = $d['refs']["{$parentName}\$${ref}"];
} elseif (isset($d['base'])) {
$result = $d['base'];
}
if (isset($d['append'])) {
$result .= $d['append'];
}
return $this->clean($result);
} | php | public function getShapeDocs($shapeName, $parentName, $ref)
{
if (!isset($this->docs['shapes'][$shapeName])) {
return '';
}
$result = '';
$d = $this->docs['shapes'][$shapeName];
if (isset($d['refs']["{$parentName}\$${ref}"])) {
$result = $d['refs']["{$parentName}\$${ref}"];
} elseif (isset($d['base'])) {
$result = $d['base'];
}
if (isset($d['append'])) {
$result .= $d['append'];
}
return $this->clean($result);
} | [
"public",
"function",
"getShapeDocs",
"(",
"$",
"shapeName",
",",
"$",
"parentName",
",",
"$",
"ref",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"docs",
"[",
"'shapes'",
"]",
"[",
"$",
"shapeName",
"]",
")",
")",
"{",
"return",
"''",
";",
"}",
"$",
"result",
"=",
"''",
";",
"$",
"d",
"=",
"$",
"this",
"->",
"docs",
"[",
"'shapes'",
"]",
"[",
"$",
"shapeName",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"d",
"[",
"'refs'",
"]",
"[",
"\"{$parentName}\\$${ref}\"",
"]",
")",
")",
"{",
"$",
"result",
"=",
"$",
"d",
"[",
"'refs'",
"]",
"[",
"\"{$parentName}\\$${ref}\"",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"d",
"[",
"'base'",
"]",
")",
")",
"{",
"$",
"result",
"=",
"$",
"d",
"[",
"'base'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"d",
"[",
"'append'",
"]",
")",
")",
"{",
"$",
"result",
".=",
"$",
"d",
"[",
"'append'",
"]",
";",
"}",
"return",
"$",
"this",
"->",
"clean",
"(",
"$",
"result",
")",
";",
"}"
] | Retrieves documentation about a shape, specific to the context.
@param string $shapeName Name of the shape.
@param string $parentName Name of the parent/context shape.
@param string $ref Name used by the context to reference the shape.
@return null|string | [
"Retrieves",
"documentation",
"about",
"a",
"shape",
"specific",
"to",
"the",
"context",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/DocModel.php#L85-L104 | train |
aws/aws-sdk-php | src/Rds/AuthTokenGenerator.php | AuthTokenGenerator.createToken | public function createToken($endpoint, $region, $username)
{
$uri = new Uri($endpoint);
$uri = $uri->withPath('/');
$uri = $uri->withQuery('Action=connect&DBUser=' . $username);
$request = new Request('GET', $uri);
$signer = new SignatureV4('rds-db', $region);
$provider = $this->credentialProvider;
$url = (string) $signer->presign(
$request,
$provider()->wait(),
'+15 minutes'
)->getUri();
// Remove 2 extra slash from the presigned url result
return substr($url, 2);
} | php | public function createToken($endpoint, $region, $username)
{
$uri = new Uri($endpoint);
$uri = $uri->withPath('/');
$uri = $uri->withQuery('Action=connect&DBUser=' . $username);
$request = new Request('GET', $uri);
$signer = new SignatureV4('rds-db', $region);
$provider = $this->credentialProvider;
$url = (string) $signer->presign(
$request,
$provider()->wait(),
'+15 minutes'
)->getUri();
// Remove 2 extra slash from the presigned url result
return substr($url, 2);
} | [
"public",
"function",
"createToken",
"(",
"$",
"endpoint",
",",
"$",
"region",
",",
"$",
"username",
")",
"{",
"$",
"uri",
"=",
"new",
"Uri",
"(",
"$",
"endpoint",
")",
";",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withPath",
"(",
"'/'",
")",
";",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withQuery",
"(",
"'Action=connect&DBUser='",
".",
"$",
"username",
")",
";",
"$",
"request",
"=",
"new",
"Request",
"(",
"'GET'",
",",
"$",
"uri",
")",
";",
"$",
"signer",
"=",
"new",
"SignatureV4",
"(",
"'rds-db'",
",",
"$",
"region",
")",
";",
"$",
"provider",
"=",
"$",
"this",
"->",
"credentialProvider",
";",
"$",
"url",
"=",
"(",
"string",
")",
"$",
"signer",
"->",
"presign",
"(",
"$",
"request",
",",
"$",
"provider",
"(",
")",
"->",
"wait",
"(",
")",
",",
"'+15 minutes'",
")",
"->",
"getUri",
"(",
")",
";",
"// Remove 2 extra slash from the presigned url result",
"return",
"substr",
"(",
"$",
"url",
",",
"2",
")",
";",
"}"
] | Create the token for database login
@param string $endpoint The database hostname with port number specified
(e.g., host:port)
@param string $region The region where the database is located
@param string $username The username to login as
@return string Token generated | [
"Create",
"the",
"token",
"for",
"database",
"login"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Rds/AuthTokenGenerator.php#L45-L63 | train |
aws/aws-sdk-php | src/Endpoint/EndpointProvider.php | EndpointProvider.resolve | public static function resolve(callable $provider, array $args = [])
{
$result = $provider($args);
if (is_array($result)) {
return $result;
}
throw new UnresolvedEndpointException(
'Unable to resolve an endpoint using the provider arguments: '
. json_encode($args) . '. Note: you can provide an "endpoint" '
. 'option to a client constructor to bypass invoking an endpoint '
. 'provider.');
} | php | public static function resolve(callable $provider, array $args = [])
{
$result = $provider($args);
if (is_array($result)) {
return $result;
}
throw new UnresolvedEndpointException(
'Unable to resolve an endpoint using the provider arguments: '
. json_encode($args) . '. Note: you can provide an "endpoint" '
. 'option to a client constructor to bypass invoking an endpoint '
. 'provider.');
} | [
"public",
"static",
"function",
"resolve",
"(",
"callable",
"$",
"provider",
",",
"array",
"$",
"args",
"=",
"[",
"]",
")",
"{",
"$",
"result",
"=",
"$",
"provider",
"(",
"$",
"args",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"result",
")",
")",
"{",
"return",
"$",
"result",
";",
"}",
"throw",
"new",
"UnresolvedEndpointException",
"(",
"'Unable to resolve an endpoint using the provider arguments: '",
".",
"json_encode",
"(",
"$",
"args",
")",
".",
"'. Note: you can provide an \"endpoint\" '",
".",
"'option to a client constructor to bypass invoking an endpoint '",
".",
"'provider.'",
")",
";",
"}"
] | Resolves and endpoint provider and ensures a non-null return value.
@param callable $provider Provider function to invoke.
@param array $args Endpoint arguments to pass to the provider.
@return array
@throws UnresolvedEndpointException | [
"Resolves",
"and",
"endpoint",
"provider",
"and",
"ensures",
"a",
"non",
"-",
"null",
"return",
"value",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Endpoint/EndpointProvider.php#L58-L70 | train |
aws/aws-sdk-php | src/S3Control/S3ControlEndpointMiddleware.php | S3ControlEndpointMiddleware.wrap | public static function wrap($region, array $options)
{
return function (callable $handler) use ($region, $options) {
return new self($handler, $region, $options);
};
} | php | public static function wrap($region, array $options)
{
return function (callable $handler) use ($region, $options) {
return new self($handler, $region, $options);
};
} | [
"public",
"static",
"function",
"wrap",
"(",
"$",
"region",
",",
"array",
"$",
"options",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"region",
",",
"$",
"options",
")",
"{",
"return",
"new",
"self",
"(",
"$",
"handler",
",",
"$",
"region",
",",
"$",
"options",
")",
";",
"}",
";",
"}"
] | Create a middleware wrapper function
@param string $region
@param array $options
@return callable | [
"Create",
"a",
"middleware",
"wrapper",
"function"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3Control/S3ControlEndpointMiddleware.php#L36-L41 | train |
aws/aws-sdk-php | src/S3/Crypto/InstructionFileMetadataStrategy.php | InstructionFileMetadataStrategy.save | public function save(MetadataEnvelope $envelope, array $args)
{
$this->client->putObject([
'Bucket' => $args['Bucket'],
'Key' => $args['Key'] . $this->suffix,
'Body' => json_encode($envelope)
]);
return $args;
} | php | public function save(MetadataEnvelope $envelope, array $args)
{
$this->client->putObject([
'Bucket' => $args['Bucket'],
'Key' => $args['Key'] . $this->suffix,
'Body' => json_encode($envelope)
]);
return $args;
} | [
"public",
"function",
"save",
"(",
"MetadataEnvelope",
"$",
"envelope",
",",
"array",
"$",
"args",
")",
"{",
"$",
"this",
"->",
"client",
"->",
"putObject",
"(",
"[",
"'Bucket'",
"=>",
"$",
"args",
"[",
"'Bucket'",
"]",
",",
"'Key'",
"=>",
"$",
"args",
"[",
"'Key'",
"]",
".",
"$",
"this",
"->",
"suffix",
",",
"'Body'",
"=>",
"json_encode",
"(",
"$",
"envelope",
")",
"]",
")",
";",
"return",
"$",
"args",
";",
"}"
] | Places the information in the MetadataEnvelope to a location on S3.
@param MetadataEnvelope $envelope Encryption data to save according to
the strategy.
@param array $args Starting arguments for PutObject, used for saving
extra the instruction file.
@return array Updated arguments for PutObject. | [
"Places",
"the",
"information",
"in",
"the",
"MetadataEnvelope",
"to",
"a",
"location",
"on",
"S3",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/Crypto/InstructionFileMetadataStrategy.php#L50-L59 | train |
aws/aws-sdk-php | src/S3/Crypto/InstructionFileMetadataStrategy.php | InstructionFileMetadataStrategy.load | public function load(array $args)
{
$result = $this->client->getObject([
'Bucket' => $args['Bucket'],
'Key' => $args['Key'] . $this->suffix
]);
$metadataHeaders = json_decode($result['Body'], true);
$envelope = new MetadataEnvelope();
$constantValues = MetadataEnvelope::getConstantValues();
foreach ($constantValues as $constant) {
if (!empty($metadataHeaders[$constant])) {
$envelope[$constant] = $metadataHeaders[$constant];
}
}
return $envelope;
} | php | public function load(array $args)
{
$result = $this->client->getObject([
'Bucket' => $args['Bucket'],
'Key' => $args['Key'] . $this->suffix
]);
$metadataHeaders = json_decode($result['Body'], true);
$envelope = new MetadataEnvelope();
$constantValues = MetadataEnvelope::getConstantValues();
foreach ($constantValues as $constant) {
if (!empty($metadataHeaders[$constant])) {
$envelope[$constant] = $metadataHeaders[$constant];
}
}
return $envelope;
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"args",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"client",
"->",
"getObject",
"(",
"[",
"'Bucket'",
"=>",
"$",
"args",
"[",
"'Bucket'",
"]",
",",
"'Key'",
"=>",
"$",
"args",
"[",
"'Key'",
"]",
".",
"$",
"this",
"->",
"suffix",
"]",
")",
";",
"$",
"metadataHeaders",
"=",
"json_decode",
"(",
"$",
"result",
"[",
"'Body'",
"]",
",",
"true",
")",
";",
"$",
"envelope",
"=",
"new",
"MetadataEnvelope",
"(",
")",
";",
"$",
"constantValues",
"=",
"MetadataEnvelope",
"::",
"getConstantValues",
"(",
")",
";",
"foreach",
"(",
"$",
"constantValues",
"as",
"$",
"constant",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"metadataHeaders",
"[",
"$",
"constant",
"]",
")",
")",
"{",
"$",
"envelope",
"[",
"$",
"constant",
"]",
"=",
"$",
"metadataHeaders",
"[",
"$",
"constant",
"]",
";",
"}",
"}",
"return",
"$",
"envelope",
";",
"}"
] | Uses the strategy's client to retrieve the instruction file from S3 and generates
a MetadataEnvelope from its contents.
@param array $args Arguments from Command and Result that contains
S3 Object information, relevant headers, and command
configuration.
@return MetadataEnvelope | [
"Uses",
"the",
"strategy",
"s",
"client",
"to",
"retrieve",
"the",
"instruction",
"file",
"from",
"S3",
"and",
"generates",
"a",
"MetadataEnvelope",
"from",
"its",
"contents",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/Crypto/InstructionFileMetadataStrategy.php#L71-L89 | train |
aws/aws-sdk-php | src/Api/Service.php | Service.createSerializer | public static function createSerializer(Service $api, $endpoint)
{
static $mapping = [
'json' => 'Aws\Api\Serializer\JsonRpcSerializer',
'query' => 'Aws\Api\Serializer\QuerySerializer',
'rest-json' => 'Aws\Api\Serializer\RestJsonSerializer',
'rest-xml' => 'Aws\Api\Serializer\RestXmlSerializer'
];
$proto = $api->getProtocol();
if (isset($mapping[$proto])) {
return new $mapping[$proto]($api, $endpoint);
}
if ($proto == 'ec2') {
return new QuerySerializer($api, $endpoint, new Ec2ParamBuilder());
}
throw new \UnexpectedValueException(
'Unknown protocol: ' . $api->getProtocol()
);
} | php | public static function createSerializer(Service $api, $endpoint)
{
static $mapping = [
'json' => 'Aws\Api\Serializer\JsonRpcSerializer',
'query' => 'Aws\Api\Serializer\QuerySerializer',
'rest-json' => 'Aws\Api\Serializer\RestJsonSerializer',
'rest-xml' => 'Aws\Api\Serializer\RestXmlSerializer'
];
$proto = $api->getProtocol();
if (isset($mapping[$proto])) {
return new $mapping[$proto]($api, $endpoint);
}
if ($proto == 'ec2') {
return new QuerySerializer($api, $endpoint, new Ec2ParamBuilder());
}
throw new \UnexpectedValueException(
'Unknown protocol: ' . $api->getProtocol()
);
} | [
"public",
"static",
"function",
"createSerializer",
"(",
"Service",
"$",
"api",
",",
"$",
"endpoint",
")",
"{",
"static",
"$",
"mapping",
"=",
"[",
"'json'",
"=>",
"'Aws\\Api\\Serializer\\JsonRpcSerializer'",
",",
"'query'",
"=>",
"'Aws\\Api\\Serializer\\QuerySerializer'",
",",
"'rest-json'",
"=>",
"'Aws\\Api\\Serializer\\RestJsonSerializer'",
",",
"'rest-xml'",
"=>",
"'Aws\\Api\\Serializer\\RestXmlSerializer'",
"]",
";",
"$",
"proto",
"=",
"$",
"api",
"->",
"getProtocol",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"mapping",
"[",
"$",
"proto",
"]",
")",
")",
"{",
"return",
"new",
"$",
"mapping",
"[",
"$",
"proto",
"]",
"(",
"$",
"api",
",",
"$",
"endpoint",
")",
";",
"}",
"if",
"(",
"$",
"proto",
"==",
"'ec2'",
")",
"{",
"return",
"new",
"QuerySerializer",
"(",
"$",
"api",
",",
"$",
"endpoint",
",",
"new",
"Ec2ParamBuilder",
"(",
")",
")",
";",
"}",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'Unknown protocol: '",
".",
"$",
"api",
"->",
"getProtocol",
"(",
")",
")",
";",
"}"
] | Creates a request serializer for the provided API object.
@param Service $api API that contains a protocol.
@param string $endpoint Endpoint to send requests to.
@return callable
@throws \UnexpectedValueException | [
"Creates",
"a",
"request",
"serializer",
"for",
"the",
"provided",
"API",
"object",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Service.php#L78-L100 | train |
aws/aws-sdk-php | src/Api/Service.php | Service.getOperation | public function getOperation($name)
{
if (!isset($this->operations[$name])) {
if (!isset($this->definition['operations'][$name])) {
throw new \InvalidArgumentException("Unknown operation: $name");
}
$this->operations[$name] = new Operation(
$this->definition['operations'][$name],
$this->shapeMap
);
}
return $this->operations[$name];
} | php | public function getOperation($name)
{
if (!isset($this->operations[$name])) {
if (!isset($this->definition['operations'][$name])) {
throw new \InvalidArgumentException("Unknown operation: $name");
}
$this->operations[$name] = new Operation(
$this->definition['operations'][$name],
$this->shapeMap
);
}
return $this->operations[$name];
} | [
"public",
"function",
"getOperation",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"operations",
"[",
"$",
"name",
"]",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"definition",
"[",
"'operations'",
"]",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Unknown operation: $name\"",
")",
";",
"}",
"$",
"this",
"->",
"operations",
"[",
"$",
"name",
"]",
"=",
"new",
"Operation",
"(",
"$",
"this",
"->",
"definition",
"[",
"'operations'",
"]",
"[",
"$",
"name",
"]",
",",
"$",
"this",
"->",
"shapeMap",
")",
";",
"}",
"return",
"$",
"this",
"->",
"operations",
"[",
"$",
"name",
"]",
";",
"}"
] | Get an operation by name.
@param string $name Operation to retrieve by name
@return Operation
@throws \InvalidArgumentException If the operation is not found | [
"Get",
"an",
"operation",
"by",
"name",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Service.php#L270-L283 | train |
aws/aws-sdk-php | src/Api/Service.php | Service.getOperations | public function getOperations()
{
$result = [];
foreach ($this->definition['operations'] as $name => $definition) {
$result[$name] = $this->getOperation($name);
}
return $result;
} | php | public function getOperations()
{
$result = [];
foreach ($this->definition['operations'] as $name => $definition) {
$result[$name] = $this->getOperation($name);
}
return $result;
} | [
"public",
"function",
"getOperations",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"definition",
"[",
"'operations'",
"]",
"as",
"$",
"name",
"=>",
"$",
"definition",
")",
"{",
"$",
"result",
"[",
"$",
"name",
"]",
"=",
"$",
"this",
"->",
"getOperation",
"(",
"$",
"name",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Get all of the operations of the description.
@return Operation[] | [
"Get",
"all",
"of",
"the",
"operations",
"of",
"the",
"description",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Service.php#L290-L298 | train |
aws/aws-sdk-php | src/Api/Service.php | Service.getMetadata | public function getMetadata($key = null)
{
if (!$key) {
return $this['metadata'];
}
if (isset($this->definition['metadata'][$key])) {
return $this->definition['metadata'][$key];
}
return null;
} | php | public function getMetadata($key = null)
{
if (!$key) {
return $this['metadata'];
}
if (isset($this->definition['metadata'][$key])) {
return $this->definition['metadata'][$key];
}
return null;
} | [
"public",
"function",
"getMetadata",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"key",
")",
"{",
"return",
"$",
"this",
"[",
"'metadata'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"definition",
"[",
"'metadata'",
"]",
"[",
"$",
"key",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"definition",
"[",
"'metadata'",
"]",
"[",
"$",
"key",
"]",
";",
"}",
"return",
"null",
";",
"}"
] | Get all of the service metadata or a specific metadata key value.
@param string|null $key Key to retrieve or null to retrieve all metadata
@return mixed Returns the result or null if the key is not found | [
"Get",
"all",
"of",
"the",
"service",
"metadata",
"or",
"a",
"specific",
"metadata",
"key",
"value",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Service.php#L307-L318 | train |
aws/aws-sdk-php | src/Api/Service.php | Service.getPaginators | public function getPaginators()
{
if (!isset($this->paginators)) {
$res = call_user_func(
$this->apiProvider,
'paginator',
$this->serviceName,
$this->apiVersion
);
$this->paginators = isset($res['pagination'])
? $res['pagination']
: [];
}
return $this->paginators;
} | php | public function getPaginators()
{
if (!isset($this->paginators)) {
$res = call_user_func(
$this->apiProvider,
'paginator',
$this->serviceName,
$this->apiVersion
);
$this->paginators = isset($res['pagination'])
? $res['pagination']
: [];
}
return $this->paginators;
} | [
"public",
"function",
"getPaginators",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"paginators",
")",
")",
"{",
"$",
"res",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"apiProvider",
",",
"'paginator'",
",",
"$",
"this",
"->",
"serviceName",
",",
"$",
"this",
"->",
"apiVersion",
")",
";",
"$",
"this",
"->",
"paginators",
"=",
"isset",
"(",
"$",
"res",
"[",
"'pagination'",
"]",
")",
"?",
"$",
"res",
"[",
"'pagination'",
"]",
":",
"[",
"]",
";",
"}",
"return",
"$",
"this",
"->",
"paginators",
";",
"}"
] | Gets an associative array of available paginator configurations where
the key is the name of the paginator, and the value is the paginator
configuration.
@return array
@unstable The configuration format of paginators may change in the future | [
"Gets",
"an",
"associative",
"array",
"of",
"available",
"paginator",
"configurations",
"where",
"the",
"key",
"is",
"the",
"name",
"of",
"the",
"paginator",
"and",
"the",
"value",
"is",
"the",
"paginator",
"configuration",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Service.php#L328-L343 | train |
aws/aws-sdk-php | src/Api/Service.php | Service.getPaginatorConfig | public function getPaginatorConfig($name)
{
static $defaults = [
'input_token' => null,
'output_token' => null,
'limit_key' => null,
'result_key' => null,
'more_results' => null,
];
if ($this->hasPaginator($name)) {
return $this->paginators[$name] + $defaults;
}
throw new \UnexpectedValueException("There is no {$name} "
. "paginator defined for the {$this->serviceName} service.");
} | php | public function getPaginatorConfig($name)
{
static $defaults = [
'input_token' => null,
'output_token' => null,
'limit_key' => null,
'result_key' => null,
'more_results' => null,
];
if ($this->hasPaginator($name)) {
return $this->paginators[$name] + $defaults;
}
throw new \UnexpectedValueException("There is no {$name} "
. "paginator defined for the {$this->serviceName} service.");
} | [
"public",
"function",
"getPaginatorConfig",
"(",
"$",
"name",
")",
"{",
"static",
"$",
"defaults",
"=",
"[",
"'input_token'",
"=>",
"null",
",",
"'output_token'",
"=>",
"null",
",",
"'limit_key'",
"=>",
"null",
",",
"'result_key'",
"=>",
"null",
",",
"'more_results'",
"=>",
"null",
",",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"hasPaginator",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"this",
"->",
"paginators",
"[",
"$",
"name",
"]",
"+",
"$",
"defaults",
";",
"}",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"\"There is no {$name} \"",
".",
"\"paginator defined for the {$this->serviceName} service.\"",
")",
";",
"}"
] | Retrieve a paginator by name.
@param string $name Paginator to retrieve by name. This argument is
typically the operation name.
@return array
@throws \UnexpectedValueException if the paginator does not exist.
@unstable The configuration format of paginators may change in the future | [
"Retrieve",
"a",
"paginator",
"by",
"name",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Service.php#L366-L382 | train |
aws/aws-sdk-php | src/Api/Service.php | Service.getWaiters | public function getWaiters()
{
if (!isset($this->waiters)) {
$res = call_user_func(
$this->apiProvider,
'waiter',
$this->serviceName,
$this->apiVersion
);
$this->waiters = isset($res['waiters'])
? $res['waiters']
: [];
}
return $this->waiters;
} | php | public function getWaiters()
{
if (!isset($this->waiters)) {
$res = call_user_func(
$this->apiProvider,
'waiter',
$this->serviceName,
$this->apiVersion
);
$this->waiters = isset($res['waiters'])
? $res['waiters']
: [];
}
return $this->waiters;
} | [
"public",
"function",
"getWaiters",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"waiters",
")",
")",
"{",
"$",
"res",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"apiProvider",
",",
"'waiter'",
",",
"$",
"this",
"->",
"serviceName",
",",
"$",
"this",
"->",
"apiVersion",
")",
";",
"$",
"this",
"->",
"waiters",
"=",
"isset",
"(",
"$",
"res",
"[",
"'waiters'",
"]",
")",
"?",
"$",
"res",
"[",
"'waiters'",
"]",
":",
"[",
"]",
";",
"}",
"return",
"$",
"this",
"->",
"waiters",
";",
"}"
] | Gets an associative array of available waiter configurations where the
key is the name of the waiter, and the value is the waiter
configuration.
@return array | [
"Gets",
"an",
"associative",
"array",
"of",
"available",
"waiter",
"configurations",
"where",
"the",
"key",
"is",
"the",
"name",
"of",
"the",
"waiter",
"and",
"the",
"value",
"is",
"the",
"waiter",
"configuration",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Service.php#L391-L406 | train |
aws/aws-sdk-php | src/Glacier/TreeHash.php | TreeHash.addChecksum | public function addChecksum($checksum, $inBinaryForm = false)
{
// Error if hash is already calculated
if ($this->hash) {
throw new \LogicException('You may not add more checksums to a '
. 'complete tree hash.');
}
// Convert the checksum to binary form if necessary
$this->checksums[] = $inBinaryForm ? $checksum : hex2bin($checksum);
return $this;
} | php | public function addChecksum($checksum, $inBinaryForm = false)
{
// Error if hash is already calculated
if ($this->hash) {
throw new \LogicException('You may not add more checksums to a '
. 'complete tree hash.');
}
// Convert the checksum to binary form if necessary
$this->checksums[] = $inBinaryForm ? $checksum : hex2bin($checksum);
return $this;
} | [
"public",
"function",
"addChecksum",
"(",
"$",
"checksum",
",",
"$",
"inBinaryForm",
"=",
"false",
")",
"{",
"// Error if hash is already calculated",
"if",
"(",
"$",
"this",
"->",
"hash",
")",
"{",
"throw",
"new",
"\\",
"LogicException",
"(",
"'You may not add more checksums to a '",
".",
"'complete tree hash.'",
")",
";",
"}",
"// Convert the checksum to binary form if necessary",
"$",
"this",
"->",
"checksums",
"[",
"]",
"=",
"$",
"inBinaryForm",
"?",
"$",
"checksum",
":",
"hex2bin",
"(",
"$",
"checksum",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Add a checksum to the tree hash directly
@param string $checksum The checksum to add
@param bool $inBinaryForm TRUE if checksum is in binary form
@return self
@throws \LogicException if the root tree hash is already calculated | [
"Add",
"a",
"checksum",
"to",
"the",
"tree",
"hash",
"directly"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Glacier/TreeHash.php#L66-L78 | train |
aws/aws-sdk-php | src/Glacier/GlacierClient.php | GlacierClient.getChecksumsMiddleware | private function getChecksumsMiddleware()
{
return function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
// Accept "ContentSHA256" with a lowercase "c" to match other Glacier params.
if (!$command['ContentSHA256'] && $command['contentSHA256']) {
$command['ContentSHA256'] = $command['contentSHA256'];
unset($command['contentSHA256']);
}
// If uploading, then make sure checksums are added.
$name = $command->getName();
if (($name === 'UploadArchive' || $name === 'UploadMultipartPart')
&& (!$command['checksum'] || !$command['ContentSHA256'])
) {
$body = $request->getBody();
if (!$body->isSeekable()) {
throw new CouldNotCreateChecksumException('sha256');
}
// Add a tree hash if not provided.
if (!$command['checksum']) {
$body = new HashingStream(
$body, new TreeHash(),
function ($result) use ($command, &$request) {
$request = $request->withHeader(
'x-amz-sha256-tree-hash',
bin2hex($result)
);
}
);
}
// Add a linear content hash if not provided.
if (!$command['ContentSHA256']) {
$body = new HashingStream(
$body, new PhpHash('sha256'),
function ($result) use ($command) {
$command['ContentSHA256'] = bin2hex($result);
}
);
}
// Read the stream in order to calculate the hashes.
while (!$body->eof()) {
$body->read(1048576);
}
$body->seek(0);
}
// Set the content hash header if a value is in the command.
if ($command['ContentSHA256']) {
$request = $request->withHeader(
'x-amz-content-sha256',
$command['ContentSHA256']
);
}
return $handler($command, $request);
};
};
} | php | private function getChecksumsMiddleware()
{
return function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
// Accept "ContentSHA256" with a lowercase "c" to match other Glacier params.
if (!$command['ContentSHA256'] && $command['contentSHA256']) {
$command['ContentSHA256'] = $command['contentSHA256'];
unset($command['contentSHA256']);
}
// If uploading, then make sure checksums are added.
$name = $command->getName();
if (($name === 'UploadArchive' || $name === 'UploadMultipartPart')
&& (!$command['checksum'] || !$command['ContentSHA256'])
) {
$body = $request->getBody();
if (!$body->isSeekable()) {
throw new CouldNotCreateChecksumException('sha256');
}
// Add a tree hash if not provided.
if (!$command['checksum']) {
$body = new HashingStream(
$body, new TreeHash(),
function ($result) use ($command, &$request) {
$request = $request->withHeader(
'x-amz-sha256-tree-hash',
bin2hex($result)
);
}
);
}
// Add a linear content hash if not provided.
if (!$command['ContentSHA256']) {
$body = new HashingStream(
$body, new PhpHash('sha256'),
function ($result) use ($command) {
$command['ContentSHA256'] = bin2hex($result);
}
);
}
// Read the stream in order to calculate the hashes.
while (!$body->eof()) {
$body->read(1048576);
}
$body->seek(0);
}
// Set the content hash header if a value is in the command.
if ($command['ContentSHA256']) {
$request = $request->withHeader(
'x-amz-content-sha256',
$command['ContentSHA256']
);
}
return $handler($command, $request);
};
};
} | [
"private",
"function",
"getChecksumsMiddleware",
"(",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
")",
"{",
"// Accept \"ContentSHA256\" with a lowercase \"c\" to match other Glacier params.",
"if",
"(",
"!",
"$",
"command",
"[",
"'ContentSHA256'",
"]",
"&&",
"$",
"command",
"[",
"'contentSHA256'",
"]",
")",
"{",
"$",
"command",
"[",
"'ContentSHA256'",
"]",
"=",
"$",
"command",
"[",
"'contentSHA256'",
"]",
";",
"unset",
"(",
"$",
"command",
"[",
"'contentSHA256'",
"]",
")",
";",
"}",
"// If uploading, then make sure checksums are added.",
"$",
"name",
"=",
"$",
"command",
"->",
"getName",
"(",
")",
";",
"if",
"(",
"(",
"$",
"name",
"===",
"'UploadArchive'",
"||",
"$",
"name",
"===",
"'UploadMultipartPart'",
")",
"&&",
"(",
"!",
"$",
"command",
"[",
"'checksum'",
"]",
"||",
"!",
"$",
"command",
"[",
"'ContentSHA256'",
"]",
")",
")",
"{",
"$",
"body",
"=",
"$",
"request",
"->",
"getBody",
"(",
")",
";",
"if",
"(",
"!",
"$",
"body",
"->",
"isSeekable",
"(",
")",
")",
"{",
"throw",
"new",
"CouldNotCreateChecksumException",
"(",
"'sha256'",
")",
";",
"}",
"// Add a tree hash if not provided.",
"if",
"(",
"!",
"$",
"command",
"[",
"'checksum'",
"]",
")",
"{",
"$",
"body",
"=",
"new",
"HashingStream",
"(",
"$",
"body",
",",
"new",
"TreeHash",
"(",
")",
",",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"$",
"command",
",",
"&",
"$",
"request",
")",
"{",
"$",
"request",
"=",
"$",
"request",
"->",
"withHeader",
"(",
"'x-amz-sha256-tree-hash'",
",",
"bin2hex",
"(",
"$",
"result",
")",
")",
";",
"}",
")",
";",
"}",
"// Add a linear content hash if not provided.",
"if",
"(",
"!",
"$",
"command",
"[",
"'ContentSHA256'",
"]",
")",
"{",
"$",
"body",
"=",
"new",
"HashingStream",
"(",
"$",
"body",
",",
"new",
"PhpHash",
"(",
"'sha256'",
")",
",",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"$",
"command",
")",
"{",
"$",
"command",
"[",
"'ContentSHA256'",
"]",
"=",
"bin2hex",
"(",
"$",
"result",
")",
";",
"}",
")",
";",
"}",
"// Read the stream in order to calculate the hashes.",
"while",
"(",
"!",
"$",
"body",
"->",
"eof",
"(",
")",
")",
"{",
"$",
"body",
"->",
"read",
"(",
"1048576",
")",
";",
"}",
"$",
"body",
"->",
"seek",
"(",
"0",
")",
";",
"}",
"// Set the content hash header if a value is in the command.",
"if",
"(",
"$",
"command",
"[",
"'ContentSHA256'",
"]",
")",
"{",
"$",
"request",
"=",
"$",
"request",
"->",
"withHeader",
"(",
"'x-amz-content-sha256'",
",",
"$",
"command",
"[",
"'ContentSHA256'",
"]",
")",
";",
"}",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
")",
";",
"}",
";",
"}",
";",
"}"
] | Creates a middleware that updates a command with the content and tree
hash headers for upload operations.
@return callable
@throws CouldNotCreateChecksumException if the body is not seekable. | [
"Creates",
"a",
"middleware",
"that",
"updates",
"a",
"command",
"with",
"the",
"content",
"and",
"tree",
"hash",
"headers",
"for",
"upload",
"operations",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Glacier/GlacierClient.php#L122-L186 | train |
aws/aws-sdk-php | src/Glacier/GlacierClient.php | GlacierClient.getApiVersionMiddleware | private function getApiVersionMiddleware()
{
return function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
return $handler($command, $request->withHeader(
'x-amz-glacier-version',
$this->getApi()->getMetadata('apiVersion')
));
};
};
} | php | private function getApiVersionMiddleware()
{
return function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
return $handler($command, $request->withHeader(
'x-amz-glacier-version',
$this->getApi()->getMetadata('apiVersion')
));
};
};
} | [
"private",
"function",
"getApiVersionMiddleware",
"(",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"command",
",",
"RequestInterface",
"$",
"request",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
")",
"{",
"return",
"$",
"handler",
"(",
"$",
"command",
",",
"$",
"request",
"->",
"withHeader",
"(",
"'x-amz-glacier-version'",
",",
"$",
"this",
"->",
"getApi",
"(",
")",
"->",
"getMetadata",
"(",
"'apiVersion'",
")",
")",
")",
";",
"}",
";",
"}",
";",
"}"
] | Creates a middleware that adds the API version header for all requests.
@return callable | [
"Creates",
"a",
"middleware",
"that",
"adds",
"the",
"API",
"version",
"header",
"for",
"all",
"requests",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Glacier/GlacierClient.php#L193-L206 | train |
aws/aws-sdk-php | src/Lambda/LambdaClient.php | LambdaClient.getDefaultCurlOptionsMiddleware | public function getDefaultCurlOptionsMiddleware()
{
return Middleware::mapCommand(function (CommandInterface $cmd) {
$defaultCurlOptions = [
CURLOPT_TCP_KEEPALIVE => 1,
];
if (!isset($cmd['@http']['curl'])) {
$cmd['@http']['curl'] = $defaultCurlOptions;
} else {
$cmd['@http']['curl'] += $defaultCurlOptions;
}
return $cmd;
});
} | php | public function getDefaultCurlOptionsMiddleware()
{
return Middleware::mapCommand(function (CommandInterface $cmd) {
$defaultCurlOptions = [
CURLOPT_TCP_KEEPALIVE => 1,
];
if (!isset($cmd['@http']['curl'])) {
$cmd['@http']['curl'] = $defaultCurlOptions;
} else {
$cmd['@http']['curl'] += $defaultCurlOptions;
}
return $cmd;
});
} | [
"public",
"function",
"getDefaultCurlOptionsMiddleware",
"(",
")",
"{",
"return",
"Middleware",
"::",
"mapCommand",
"(",
"function",
"(",
"CommandInterface",
"$",
"cmd",
")",
"{",
"$",
"defaultCurlOptions",
"=",
"[",
"CURLOPT_TCP_KEEPALIVE",
"=>",
"1",
",",
"]",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"cmd",
"[",
"'@http'",
"]",
"[",
"'curl'",
"]",
")",
")",
"{",
"$",
"cmd",
"[",
"'@http'",
"]",
"[",
"'curl'",
"]",
"=",
"$",
"defaultCurlOptions",
";",
"}",
"else",
"{",
"$",
"cmd",
"[",
"'@http'",
"]",
"[",
"'curl'",
"]",
"+=",
"$",
"defaultCurlOptions",
";",
"}",
"return",
"$",
"cmd",
";",
"}",
")",
";",
"}"
] | Provides a middleware that sets default Curl options for the command
@return callable | [
"Provides",
"a",
"middleware",
"that",
"sets",
"default",
"Curl",
"options",
"for",
"the",
"command"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Lambda/LambdaClient.php#L109-L122 | train |
aws/aws-sdk-php | src/ClientSideMonitoring/ConfigurationProvider.php | ConfigurationProvider.chain | public static function chain()
{
$links = func_get_args();
if (empty($links)) {
throw new \InvalidArgumentException('No providers in chain');
}
return function () use ($links) {
/** @var callable $parent */
$parent = array_shift($links);
$promise = $parent();
while ($next = array_shift($links)) {
$promise = $promise->otherwise($next);
}
return $promise;
};
} | php | public static function chain()
{
$links = func_get_args();
if (empty($links)) {
throw new \InvalidArgumentException('No providers in chain');
}
return function () use ($links) {
/** @var callable $parent */
$parent = array_shift($links);
$promise = $parent();
while ($next = array_shift($links)) {
$promise = $promise->otherwise($next);
}
return $promise;
};
} | [
"public",
"static",
"function",
"chain",
"(",
")",
"{",
"$",
"links",
"=",
"func_get_args",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"links",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'No providers in chain'",
")",
";",
"}",
"return",
"function",
"(",
")",
"use",
"(",
"$",
"links",
")",
"{",
"/** @var callable $parent */",
"$",
"parent",
"=",
"array_shift",
"(",
"$",
"links",
")",
";",
"$",
"promise",
"=",
"$",
"parent",
"(",
")",
";",
"while",
"(",
"$",
"next",
"=",
"array_shift",
"(",
"$",
"links",
")",
")",
"{",
"$",
"promise",
"=",
"$",
"promise",
"->",
"otherwise",
"(",
"$",
"next",
")",
";",
"}",
"return",
"$",
"promise",
";",
"}",
";",
"}"
] | Creates an aggregate credentials provider that invokes the provided
variadic providers one after the other until a provider returns
credentials.
@return callable | [
"Creates",
"an",
"aggregate",
"credentials",
"provider",
"that",
"invokes",
"the",
"provided",
"variadic",
"providers",
"one",
"after",
"the",
"other",
"until",
"a",
"provider",
"returns",
"credentials",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientSideMonitoring/ConfigurationProvider.php#L101-L117 | train |
aws/aws-sdk-php | src/ClientSideMonitoring/ConfigurationProvider.php | ConfigurationProvider.env | public static function env()
{
return function () {
// Use credentials from environment variables, if available
$enabled = getenv(self::ENV_ENABLED);
if ($enabled !== false) {
return Promise\promise_for(
new Configuration(
$enabled,
getenv(self::ENV_PORT) ?: self::DEFAULT_PORT,
getenv(self:: ENV_CLIENT_ID) ?: self::DEFAULT_CLIENT_ID
)
);
}
return self::reject('Could not find environment variable CSM config'
. ' in ' . self::ENV_ENABLED. '/' . self::ENV_PORT . '/'
. self::ENV_CLIENT_ID);
};
} | php | public static function env()
{
return function () {
// Use credentials from environment variables, if available
$enabled = getenv(self::ENV_ENABLED);
if ($enabled !== false) {
return Promise\promise_for(
new Configuration(
$enabled,
getenv(self::ENV_PORT) ?: self::DEFAULT_PORT,
getenv(self:: ENV_CLIENT_ID) ?: self::DEFAULT_CLIENT_ID
)
);
}
return self::reject('Could not find environment variable CSM config'
. ' in ' . self::ENV_ENABLED. '/' . self::ENV_PORT . '/'
. self::ENV_CLIENT_ID);
};
} | [
"public",
"static",
"function",
"env",
"(",
")",
"{",
"return",
"function",
"(",
")",
"{",
"// Use credentials from environment variables, if available",
"$",
"enabled",
"=",
"getenv",
"(",
"self",
"::",
"ENV_ENABLED",
")",
";",
"if",
"(",
"$",
"enabled",
"!==",
"false",
")",
"{",
"return",
"Promise",
"\\",
"promise_for",
"(",
"new",
"Configuration",
"(",
"$",
"enabled",
",",
"getenv",
"(",
"self",
"::",
"ENV_PORT",
")",
"?",
":",
"self",
"::",
"DEFAULT_PORT",
",",
"getenv",
"(",
"self",
"::",
"ENV_CLIENT_ID",
")",
"?",
":",
"self",
"::",
"DEFAULT_CLIENT_ID",
")",
")",
";",
"}",
"return",
"self",
"::",
"reject",
"(",
"'Could not find environment variable CSM config'",
".",
"' in '",
".",
"self",
"::",
"ENV_ENABLED",
".",
"'/'",
".",
"self",
"::",
"ENV_PORT",
".",
"'/'",
".",
"self",
"::",
"ENV_CLIENT_ID",
")",
";",
"}",
";",
"}"
] | Provider that creates CSM config from environment variables.
@return callable | [
"Provider",
"that",
"creates",
"CSM",
"config",
"from",
"environment",
"variables",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientSideMonitoring/ConfigurationProvider.php#L157-L176 | train |
aws/aws-sdk-php | src/ClientSideMonitoring/ConfigurationProvider.php | ConfigurationProvider.fallback | public static function fallback()
{
return function() {
return Promise\promise_for(
new Configuration(
self::DEFAULT_ENABLED,
self::DEFAULT_PORT,
self::DEFAULT_CLIENT_ID
)
);
};
} | php | public static function fallback()
{
return function() {
return Promise\promise_for(
new Configuration(
self::DEFAULT_ENABLED,
self::DEFAULT_PORT,
self::DEFAULT_CLIENT_ID
)
);
};
} | [
"public",
"static",
"function",
"fallback",
"(",
")",
"{",
"return",
"function",
"(",
")",
"{",
"return",
"Promise",
"\\",
"promise_for",
"(",
"new",
"Configuration",
"(",
"self",
"::",
"DEFAULT_ENABLED",
",",
"self",
"::",
"DEFAULT_PORT",
",",
"self",
"::",
"DEFAULT_CLIENT_ID",
")",
")",
";",
"}",
";",
"}"
] | Fallback config options when other sources are not set.
@return callable | [
"Fallback",
"config",
"options",
"when",
"other",
"sources",
"are",
"not",
"set",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientSideMonitoring/ConfigurationProvider.php#L183-L194 | train |
aws/aws-sdk-php | src/ClientSideMonitoring/ConfigurationProvider.php | ConfigurationProvider.memoize | public static function memoize(callable $provider)
{
return function () use ($provider) {
static $result;
static $isConstant;
// Constant config will be returned constantly.
if ($isConstant) {
return $result;
}
// Create the initial promise that will be used as the cached value
// until it expires.
if (null === $result) {
$result = $provider();
}
// Return config and set flag that provider is already set
return $result
->then(function (ConfigurationInterface $config) use (&$isConstant) {
$isConstant = true;
return $config;
});
};
} | php | public static function memoize(callable $provider)
{
return function () use ($provider) {
static $result;
static $isConstant;
// Constant config will be returned constantly.
if ($isConstant) {
return $result;
}
// Create the initial promise that will be used as the cached value
// until it expires.
if (null === $result) {
$result = $provider();
}
// Return config and set flag that provider is already set
return $result
->then(function (ConfigurationInterface $config) use (&$isConstant) {
$isConstant = true;
return $config;
});
};
} | [
"public",
"static",
"function",
"memoize",
"(",
"callable",
"$",
"provider",
")",
"{",
"return",
"function",
"(",
")",
"use",
"(",
"$",
"provider",
")",
"{",
"static",
"$",
"result",
";",
"static",
"$",
"isConstant",
";",
"// Constant config will be returned constantly.",
"if",
"(",
"$",
"isConstant",
")",
"{",
"return",
"$",
"result",
";",
"}",
"// Create the initial promise that will be used as the cached value",
"// until it expires.",
"if",
"(",
"null",
"===",
"$",
"result",
")",
"{",
"$",
"result",
"=",
"$",
"provider",
"(",
")",
";",
"}",
"// Return config and set flag that provider is already set",
"return",
"$",
"result",
"->",
"then",
"(",
"function",
"(",
"ConfigurationInterface",
"$",
"config",
")",
"use",
"(",
"&",
"$",
"isConstant",
")",
"{",
"$",
"isConstant",
"=",
"true",
";",
"return",
"$",
"config",
";",
"}",
")",
";",
"}",
";",
"}"
] | Wraps a CSM config provider and caches previously provided configuration.
Ensures that cached configuration is refreshed when it expires.
@param callable $provider CSM config provider function to wrap.
@return callable | [
"Wraps",
"a",
"CSM",
"config",
"provider",
"and",
"caches",
"previously",
"provided",
"configuration",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/ClientSideMonitoring/ConfigurationProvider.php#L276-L300 | train |
aws/aws-sdk-php | src/CloudFront/CloudFrontClient.php | CloudFrontClient.getSignedCookie | public function getSignedCookie(array $options)
{
foreach (['key_pair_id', 'private_key'] as $required) {
if (!isset($options[$required])) {
throw new \InvalidArgumentException("$required is required");
}
}
$cookieSigner = new CookieSigner(
$options['key_pair_id'],
$options['private_key']
);
return $cookieSigner->getSignedCookie(
isset($options['url']) ? $options['url'] : null,
isset($options['expires']) ? $options['expires'] : null,
isset($options['policy']) ? $options['policy'] : null
);
} | php | public function getSignedCookie(array $options)
{
foreach (['key_pair_id', 'private_key'] as $required) {
if (!isset($options[$required])) {
throw new \InvalidArgumentException("$required is required");
}
}
$cookieSigner = new CookieSigner(
$options['key_pair_id'],
$options['private_key']
);
return $cookieSigner->getSignedCookie(
isset($options['url']) ? $options['url'] : null,
isset($options['expires']) ? $options['expires'] : null,
isset($options['policy']) ? $options['policy'] : null
);
} | [
"public",
"function",
"getSignedCookie",
"(",
"array",
"$",
"options",
")",
"{",
"foreach",
"(",
"[",
"'key_pair_id'",
",",
"'private_key'",
"]",
"as",
"$",
"required",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"options",
"[",
"$",
"required",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"$required is required\"",
")",
";",
"}",
"}",
"$",
"cookieSigner",
"=",
"new",
"CookieSigner",
"(",
"$",
"options",
"[",
"'key_pair_id'",
"]",
",",
"$",
"options",
"[",
"'private_key'",
"]",
")",
";",
"return",
"$",
"cookieSigner",
"->",
"getSignedCookie",
"(",
"isset",
"(",
"$",
"options",
"[",
"'url'",
"]",
")",
"?",
"$",
"options",
"[",
"'url'",
"]",
":",
"null",
",",
"isset",
"(",
"$",
"options",
"[",
"'expires'",
"]",
")",
"?",
"$",
"options",
"[",
"'expires'",
"]",
":",
"null",
",",
"isset",
"(",
"$",
"options",
"[",
"'policy'",
"]",
")",
"?",
"$",
"options",
"[",
"'policy'",
"]",
":",
"null",
")",
";",
"}"
] | Create a signed Amazon CloudFront cookie.
This method accepts an array of configuration options:
- url: (string) URL of the resource being signed (can include query
string and wildcards). For example: http://d111111abcdef8.cloudfront.net/images/horizon.jpg?size=large&license=yes
- policy: (string) JSON policy. Use this option when creating a signed
URL for a custom policy.
- expires: (int) UTC Unix timestamp used when signing with a canned
policy. Not required when passing a custom 'policy' option.
- key_pair_id: (string) The ID of the key pair used to sign CloudFront
URLs for private distributions.
- private_key: (string) The filepath ot the private key used to sign
CloudFront URLs for private distributions.
@param array $options Array of configuration options used when signing
@return array Key => value pairs of signed cookies to set
@throws \InvalidArgumentException if url, key_pair_id, or private_key
were not specified.
@link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/WorkingWithStreamingDistributions.html | [
"Create",
"a",
"signed",
"Amazon",
"CloudFront",
"cookie",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudFront/CloudFrontClient.php#L171-L189 | train |
aws/aws-sdk-php | src/S3/StreamWrapper.php | StreamWrapper.url_stat | public function url_stat($path, $flags)
{
$this->initProtocol($path);
// Some paths come through as S3:// for some reason.
$split = explode('://', $path);
$path = strtolower($split[0]) . '://' . $split[1];
// Check if this path is in the url_stat cache
if ($value = $this->getCacheStorage()->get($path)) {
return $value;
}
$stat = $this->createStat($path, $flags);
if (is_array($stat)) {
$this->getCacheStorage()->set($path, $stat);
}
return $stat;
} | php | public function url_stat($path, $flags)
{
$this->initProtocol($path);
// Some paths come through as S3:// for some reason.
$split = explode('://', $path);
$path = strtolower($split[0]) . '://' . $split[1];
// Check if this path is in the url_stat cache
if ($value = $this->getCacheStorage()->get($path)) {
return $value;
}
$stat = $this->createStat($path, $flags);
if (is_array($stat)) {
$this->getCacheStorage()->set($path, $stat);
}
return $stat;
} | [
"public",
"function",
"url_stat",
"(",
"$",
"path",
",",
"$",
"flags",
")",
"{",
"$",
"this",
"->",
"initProtocol",
"(",
"$",
"path",
")",
";",
"// Some paths come through as S3:// for some reason.",
"$",
"split",
"=",
"explode",
"(",
"'://'",
",",
"$",
"path",
")",
";",
"$",
"path",
"=",
"strtolower",
"(",
"$",
"split",
"[",
"0",
"]",
")",
".",
"'://'",
".",
"$",
"split",
"[",
"1",
"]",
";",
"// Check if this path is in the url_stat cache",
"if",
"(",
"$",
"value",
"=",
"$",
"this",
"->",
"getCacheStorage",
"(",
")",
"->",
"get",
"(",
"$",
"path",
")",
")",
"{",
"return",
"$",
"value",
";",
"}",
"$",
"stat",
"=",
"$",
"this",
"->",
"createStat",
"(",
"$",
"path",
",",
"$",
"flags",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"stat",
")",
")",
"{",
"$",
"this",
"->",
"getCacheStorage",
"(",
")",
"->",
"set",
"(",
"$",
"path",
",",
"$",
"stat",
")",
";",
"}",
"return",
"$",
"stat",
";",
"}"
] | Provides information for is_dir, is_file, filesize, etc. Works on
buckets, keys, and prefixes.
@link http://www.php.net/manual/en/streamwrapper.url-stat.php | [
"Provides",
"information",
"for",
"is_dir",
"is_file",
"filesize",
"etc",
".",
"Works",
"on",
"buckets",
"keys",
"and",
"prefixes",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/StreamWrapper.php#L241-L261 | train |
aws/aws-sdk-php | src/S3/StreamWrapper.php | StreamWrapper.validate | private function validate($path, $mode)
{
$errors = [];
if (!$this->getOption('Key')) {
$errors[] = 'Cannot open a bucket. You must specify a path in the '
. 'form of s3://bucket/key';
}
if (!in_array($mode, ['r', 'w', 'a', 'x'])) {
$errors[] = "Mode not supported: {$mode}. "
. "Use one 'r', 'w', 'a', or 'x'.";
}
// When using mode "x" validate if the file exists before attempting
// to read
if ($mode == 'x' &&
$this->getClient()->doesObjectExist(
$this->getOption('Bucket'),
$this->getOption('Key'),
$this->getOptions(true)
)
) {
$errors[] = "{$path} already exists on Amazon S3";
}
return $errors;
} | php | private function validate($path, $mode)
{
$errors = [];
if (!$this->getOption('Key')) {
$errors[] = 'Cannot open a bucket. You must specify a path in the '
. 'form of s3://bucket/key';
}
if (!in_array($mode, ['r', 'w', 'a', 'x'])) {
$errors[] = "Mode not supported: {$mode}. "
. "Use one 'r', 'w', 'a', or 'x'.";
}
// When using mode "x" validate if the file exists before attempting
// to read
if ($mode == 'x' &&
$this->getClient()->doesObjectExist(
$this->getOption('Bucket'),
$this->getOption('Key'),
$this->getOptions(true)
)
) {
$errors[] = "{$path} already exists on Amazon S3";
}
return $errors;
} | [
"private",
"function",
"validate",
"(",
"$",
"path",
",",
"$",
"mode",
")",
"{",
"$",
"errors",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"getOption",
"(",
"'Key'",
")",
")",
"{",
"$",
"errors",
"[",
"]",
"=",
"'Cannot open a bucket. You must specify a path in the '",
".",
"'form of s3://bucket/key'",
";",
"}",
"if",
"(",
"!",
"in_array",
"(",
"$",
"mode",
",",
"[",
"'r'",
",",
"'w'",
",",
"'a'",
",",
"'x'",
"]",
")",
")",
"{",
"$",
"errors",
"[",
"]",
"=",
"\"Mode not supported: {$mode}. \"",
".",
"\"Use one 'r', 'w', 'a', or 'x'.\"",
";",
"}",
"// When using mode \"x\" validate if the file exists before attempting",
"// to read",
"if",
"(",
"$",
"mode",
"==",
"'x'",
"&&",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"doesObjectExist",
"(",
"$",
"this",
"->",
"getOption",
"(",
"'Bucket'",
")",
",",
"$",
"this",
"->",
"getOption",
"(",
"'Key'",
")",
",",
"$",
"this",
"->",
"getOptions",
"(",
"true",
")",
")",
")",
"{",
"$",
"errors",
"[",
"]",
"=",
"\"{$path} already exists on Amazon S3\"",
";",
"}",
"return",
"$",
"errors",
";",
"}"
] | Validates the provided stream arguments for fopen and returns an array
of errors. | [
"Validates",
"the",
"provided",
"stream",
"arguments",
"for",
"fopen",
"and",
"returns",
"an",
"array",
"of",
"errors",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/StreamWrapper.php#L570-L597 | train |
aws/aws-sdk-php | src/S3/StreamWrapper.php | StreamWrapper.getOptions | private function getOptions($removeContextData = false)
{
// Context is not set when doing things like stat
if ($this->context === null) {
$options = [];
} else {
$options = stream_context_get_options($this->context);
$options = isset($options[$this->protocol])
? $options[$this->protocol]
: [];
}
$default = stream_context_get_options(stream_context_get_default());
$default = isset($default[$this->protocol])
? $default[$this->protocol]
: [];
$result = $this->params + $options + $default;
if ($removeContextData) {
unset($result['client'], $result['seekable'], $result['cache']);
}
return $result;
} | php | private function getOptions($removeContextData = false)
{
// Context is not set when doing things like stat
if ($this->context === null) {
$options = [];
} else {
$options = stream_context_get_options($this->context);
$options = isset($options[$this->protocol])
? $options[$this->protocol]
: [];
}
$default = stream_context_get_options(stream_context_get_default());
$default = isset($default[$this->protocol])
? $default[$this->protocol]
: [];
$result = $this->params + $options + $default;
if ($removeContextData) {
unset($result['client'], $result['seekable'], $result['cache']);
}
return $result;
} | [
"private",
"function",
"getOptions",
"(",
"$",
"removeContextData",
"=",
"false",
")",
"{",
"// Context is not set when doing things like stat",
"if",
"(",
"$",
"this",
"->",
"context",
"===",
"null",
")",
"{",
"$",
"options",
"=",
"[",
"]",
";",
"}",
"else",
"{",
"$",
"options",
"=",
"stream_context_get_options",
"(",
"$",
"this",
"->",
"context",
")",
";",
"$",
"options",
"=",
"isset",
"(",
"$",
"options",
"[",
"$",
"this",
"->",
"protocol",
"]",
")",
"?",
"$",
"options",
"[",
"$",
"this",
"->",
"protocol",
"]",
":",
"[",
"]",
";",
"}",
"$",
"default",
"=",
"stream_context_get_options",
"(",
"stream_context_get_default",
"(",
")",
")",
";",
"$",
"default",
"=",
"isset",
"(",
"$",
"default",
"[",
"$",
"this",
"->",
"protocol",
"]",
")",
"?",
"$",
"default",
"[",
"$",
"this",
"->",
"protocol",
"]",
":",
"[",
"]",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"params",
"+",
"$",
"options",
"+",
"$",
"default",
";",
"if",
"(",
"$",
"removeContextData",
")",
"{",
"unset",
"(",
"$",
"result",
"[",
"'client'",
"]",
",",
"$",
"result",
"[",
"'seekable'",
"]",
",",
"$",
"result",
"[",
"'cache'",
"]",
")",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Get the stream context options available to the current stream
@param bool $removeContextData Set to true to remove contextual kvp's
like 'client' from the result.
@return array | [
"Get",
"the",
"stream",
"context",
"options",
"available",
"to",
"the",
"current",
"stream"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/StreamWrapper.php#L607-L630 | train |
aws/aws-sdk-php | src/S3/StreamWrapper.php | StreamWrapper.triggerError | private function triggerError($errors, $flags = null)
{
// This is triggered with things like file_exists()
if ($flags & STREAM_URL_STAT_QUIET) {
return $flags & STREAM_URL_STAT_LINK
// This is triggered for things like is_link()
? $this->formatUrlStat(false)
: false;
}
// This is triggered when doing things like lstat() or stat()
trigger_error(implode("\n", (array) $errors), E_USER_WARNING);
return false;
} | php | private function triggerError($errors, $flags = null)
{
// This is triggered with things like file_exists()
if ($flags & STREAM_URL_STAT_QUIET) {
return $flags & STREAM_URL_STAT_LINK
// This is triggered for things like is_link()
? $this->formatUrlStat(false)
: false;
}
// This is triggered when doing things like lstat() or stat()
trigger_error(implode("\n", (array) $errors), E_USER_WARNING);
return false;
} | [
"private",
"function",
"triggerError",
"(",
"$",
"errors",
",",
"$",
"flags",
"=",
"null",
")",
"{",
"// This is triggered with things like file_exists()",
"if",
"(",
"$",
"flags",
"&",
"STREAM_URL_STAT_QUIET",
")",
"{",
"return",
"$",
"flags",
"&",
"STREAM_URL_STAT_LINK",
"// This is triggered for things like is_link()",
"?",
"$",
"this",
"->",
"formatUrlStat",
"(",
"false",
")",
":",
"false",
";",
"}",
"// This is triggered when doing things like lstat() or stat()",
"trigger_error",
"(",
"implode",
"(",
"\"\\n\"",
",",
"(",
"array",
")",
"$",
"errors",
")",
",",
"E_USER_WARNING",
")",
";",
"return",
"false",
";",
"}"
] | Trigger one or more errors
@param string|array $errors Errors to trigger
@param mixed $flags If set to STREAM_URL_STAT_QUIET, then no
error or exception occurs
@return bool Returns false
@throws \RuntimeException if throw_errors is true | [
"Trigger",
"one",
"or",
"more",
"errors"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/StreamWrapper.php#L735-L749 | train |
aws/aws-sdk-php | src/S3/StreamWrapper.php | StreamWrapper.formatUrlStat | private function formatUrlStat($result = null)
{
$stat = $this->getStatTemplate();
switch (gettype($result)) {
case 'NULL':
case 'string':
// Directory with 0777 access - see "man 2 stat".
$stat['mode'] = $stat[2] = 0040777;
break;
case 'array':
// Regular file with 0777 access - see "man 2 stat".
$stat['mode'] = $stat[2] = 0100777;
// Pluck the content-length if available.
if (isset($result['ContentLength'])) {
$stat['size'] = $stat[7] = $result['ContentLength'];
} elseif (isset($result['Size'])) {
$stat['size'] = $stat[7] = $result['Size'];
}
if (isset($result['LastModified'])) {
// ListObjects or HeadObject result
$stat['mtime'] = $stat[9] = $stat['ctime'] = $stat[10]
= strtotime($result['LastModified']);
}
}
return $stat;
} | php | private function formatUrlStat($result = null)
{
$stat = $this->getStatTemplate();
switch (gettype($result)) {
case 'NULL':
case 'string':
// Directory with 0777 access - see "man 2 stat".
$stat['mode'] = $stat[2] = 0040777;
break;
case 'array':
// Regular file with 0777 access - see "man 2 stat".
$stat['mode'] = $stat[2] = 0100777;
// Pluck the content-length if available.
if (isset($result['ContentLength'])) {
$stat['size'] = $stat[7] = $result['ContentLength'];
} elseif (isset($result['Size'])) {
$stat['size'] = $stat[7] = $result['Size'];
}
if (isset($result['LastModified'])) {
// ListObjects or HeadObject result
$stat['mtime'] = $stat[9] = $stat['ctime'] = $stat[10]
= strtotime($result['LastModified']);
}
}
return $stat;
} | [
"private",
"function",
"formatUrlStat",
"(",
"$",
"result",
"=",
"null",
")",
"{",
"$",
"stat",
"=",
"$",
"this",
"->",
"getStatTemplate",
"(",
")",
";",
"switch",
"(",
"gettype",
"(",
"$",
"result",
")",
")",
"{",
"case",
"'NULL'",
":",
"case",
"'string'",
":",
"// Directory with 0777 access - see \"man 2 stat\".",
"$",
"stat",
"[",
"'mode'",
"]",
"=",
"$",
"stat",
"[",
"2",
"]",
"=",
"0040777",
";",
"break",
";",
"case",
"'array'",
":",
"// Regular file with 0777 access - see \"man 2 stat\".",
"$",
"stat",
"[",
"'mode'",
"]",
"=",
"$",
"stat",
"[",
"2",
"]",
"=",
"0100777",
";",
"// Pluck the content-length if available.",
"if",
"(",
"isset",
"(",
"$",
"result",
"[",
"'ContentLength'",
"]",
")",
")",
"{",
"$",
"stat",
"[",
"'size'",
"]",
"=",
"$",
"stat",
"[",
"7",
"]",
"=",
"$",
"result",
"[",
"'ContentLength'",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"result",
"[",
"'Size'",
"]",
")",
")",
"{",
"$",
"stat",
"[",
"'size'",
"]",
"=",
"$",
"stat",
"[",
"7",
"]",
"=",
"$",
"result",
"[",
"'Size'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"result",
"[",
"'LastModified'",
"]",
")",
")",
"{",
"// ListObjects or HeadObject result",
"$",
"stat",
"[",
"'mtime'",
"]",
"=",
"$",
"stat",
"[",
"9",
"]",
"=",
"$",
"stat",
"[",
"'ctime'",
"]",
"=",
"$",
"stat",
"[",
"10",
"]",
"=",
"strtotime",
"(",
"$",
"result",
"[",
"'LastModified'",
"]",
")",
";",
"}",
"}",
"return",
"$",
"stat",
";",
"}"
] | Prepare a url_stat result array
@param string|array $result Data to add
@return array Returns the modified url_stat result | [
"Prepare",
"a",
"url_stat",
"result",
"array"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/StreamWrapper.php#L758-L784 | train |
aws/aws-sdk-php | src/S3/StreamWrapper.php | StreamWrapper.createBucket | private function createBucket($path, array $params)
{
if ($this->getClient()->doesBucketExist($params['Bucket'])) {
return $this->triggerError("Bucket already exists: {$path}");
}
return $this->boolCall(function () use ($params, $path) {
$this->getClient()->createBucket($params);
$this->clearCacheKey($path);
return true;
});
} | php | private function createBucket($path, array $params)
{
if ($this->getClient()->doesBucketExist($params['Bucket'])) {
return $this->triggerError("Bucket already exists: {$path}");
}
return $this->boolCall(function () use ($params, $path) {
$this->getClient()->createBucket($params);
$this->clearCacheKey($path);
return true;
});
} | [
"private",
"function",
"createBucket",
"(",
"$",
"path",
",",
"array",
"$",
"params",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"doesBucketExist",
"(",
"$",
"params",
"[",
"'Bucket'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"triggerError",
"(",
"\"Bucket already exists: {$path}\"",
")",
";",
"}",
"return",
"$",
"this",
"->",
"boolCall",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"params",
",",
"$",
"path",
")",
"{",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"createBucket",
"(",
"$",
"params",
")",
";",
"$",
"this",
"->",
"clearCacheKey",
"(",
"$",
"path",
")",
";",
"return",
"true",
";",
"}",
")",
";",
"}"
] | Creates a bucket for the given parameters.
@param string $path Stream wrapper path
@param array $params A result of StreamWrapper::withPath()
@return bool Returns true on success or false on failure | [
"Creates",
"a",
"bucket",
"for",
"the",
"given",
"parameters",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/StreamWrapper.php#L794-L805 | train |
aws/aws-sdk-php | src/S3/StreamWrapper.php | StreamWrapper.deleteSubfolder | private function deleteSubfolder($path, $params)
{
// Use a key that adds a trailing slash if needed.
$prefix = rtrim($params['Key'], '/') . '/';
$result = $this->getClient()->listObjects([
'Bucket' => $params['Bucket'],
'Prefix' => $prefix,
'MaxKeys' => 1
]);
// Check if the bucket contains keys other than the placeholder
if ($contents = $result['Contents']) {
return (count($contents) > 1 || $contents[0]['Key'] != $prefix)
? $this->triggerError('Subfolder is not empty')
: $this->unlink(rtrim($path, '/') . '/');
}
return $result['CommonPrefixes']
? $this->triggerError('Subfolder contains nested folders')
: true;
} | php | private function deleteSubfolder($path, $params)
{
// Use a key that adds a trailing slash if needed.
$prefix = rtrim($params['Key'], '/') . '/';
$result = $this->getClient()->listObjects([
'Bucket' => $params['Bucket'],
'Prefix' => $prefix,
'MaxKeys' => 1
]);
// Check if the bucket contains keys other than the placeholder
if ($contents = $result['Contents']) {
return (count($contents) > 1 || $contents[0]['Key'] != $prefix)
? $this->triggerError('Subfolder is not empty')
: $this->unlink(rtrim($path, '/') . '/');
}
return $result['CommonPrefixes']
? $this->triggerError('Subfolder contains nested folders')
: true;
} | [
"private",
"function",
"deleteSubfolder",
"(",
"$",
"path",
",",
"$",
"params",
")",
"{",
"// Use a key that adds a trailing slash if needed.",
"$",
"prefix",
"=",
"rtrim",
"(",
"$",
"params",
"[",
"'Key'",
"]",
",",
"'/'",
")",
".",
"'/'",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"getClient",
"(",
")",
"->",
"listObjects",
"(",
"[",
"'Bucket'",
"=>",
"$",
"params",
"[",
"'Bucket'",
"]",
",",
"'Prefix'",
"=>",
"$",
"prefix",
",",
"'MaxKeys'",
"=>",
"1",
"]",
")",
";",
"// Check if the bucket contains keys other than the placeholder",
"if",
"(",
"$",
"contents",
"=",
"$",
"result",
"[",
"'Contents'",
"]",
")",
"{",
"return",
"(",
"count",
"(",
"$",
"contents",
")",
">",
"1",
"||",
"$",
"contents",
"[",
"0",
"]",
"[",
"'Key'",
"]",
"!=",
"$",
"prefix",
")",
"?",
"$",
"this",
"->",
"triggerError",
"(",
"'Subfolder is not empty'",
")",
":",
"$",
"this",
"->",
"unlink",
"(",
"rtrim",
"(",
"$",
"path",
",",
"'/'",
")",
".",
"'/'",
")",
";",
"}",
"return",
"$",
"result",
"[",
"'CommonPrefixes'",
"]",
"?",
"$",
"this",
"->",
"triggerError",
"(",
"'Subfolder contains nested folders'",
")",
":",
"true",
";",
"}"
] | Deletes a nested subfolder if it is empty.
@param string $path Path that is being deleted (e.g., 's3://a/b/c')
@param array $params A result of StreamWrapper::withPath()
@return bool | [
"Deletes",
"a",
"nested",
"subfolder",
"if",
"it",
"is",
"empty",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/StreamWrapper.php#L844-L864 | train |
aws/aws-sdk-php | src/S3/StreamWrapper.php | StreamWrapper.boolCall | private function boolCall(callable $fn, $flags = null)
{
try {
return $fn();
} catch (\Exception $e) {
return $this->triggerError($e->getMessage(), $flags);
}
} | php | private function boolCall(callable $fn, $flags = null)
{
try {
return $fn();
} catch (\Exception $e) {
return $this->triggerError($e->getMessage(), $flags);
}
} | [
"private",
"function",
"boolCall",
"(",
"callable",
"$",
"fn",
",",
"$",
"flags",
"=",
"null",
")",
"{",
"try",
"{",
"return",
"$",
"fn",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"this",
"->",
"triggerError",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"$",
"flags",
")",
";",
"}",
"}"
] | Invokes a callable and triggers an error if an exception occurs while
calling the function.
@param callable $fn
@param int $flags
@return bool | [
"Invokes",
"a",
"callable",
"and",
"triggers",
"an",
"error",
"if",
"an",
"exception",
"occurs",
"while",
"calling",
"the",
"function",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/StreamWrapper.php#L915-L922 | train |
aws/aws-sdk-php | src/S3/StreamWrapper.php | StreamWrapper.getSize | private function getSize()
{
$size = $this->body->getSize();
return $size !== null ? $size : $this->size;
} | php | private function getSize()
{
$size = $this->body->getSize();
return $size !== null ? $size : $this->size;
} | [
"private",
"function",
"getSize",
"(",
")",
"{",
"$",
"size",
"=",
"$",
"this",
"->",
"body",
"->",
"getSize",
"(",
")",
";",
"return",
"$",
"size",
"!==",
"null",
"?",
"$",
"size",
":",
"$",
"this",
"->",
"size",
";",
"}"
] | Returns the size of the opened object body.
@return int|null | [
"Returns",
"the",
"size",
"of",
"the",
"opened",
"object",
"body",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/StreamWrapper.php#L952-L957 | train |
aws/aws-sdk-php | src/Api/Operation.php | Operation.getInput | public function getInput()
{
if (!$this->input) {
if ($input = $this['input']) {
$this->input = $this->shapeFor($input);
} else {
$this->input = new StructureShape([], $this->shapeMap);
}
}
return $this->input;
} | php | public function getInput()
{
if (!$this->input) {
if ($input = $this['input']) {
$this->input = $this->shapeFor($input);
} else {
$this->input = new StructureShape([], $this->shapeMap);
}
}
return $this->input;
} | [
"public",
"function",
"getInput",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"input",
")",
"{",
"if",
"(",
"$",
"input",
"=",
"$",
"this",
"[",
"'input'",
"]",
")",
"{",
"$",
"this",
"->",
"input",
"=",
"$",
"this",
"->",
"shapeFor",
"(",
"$",
"input",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"input",
"=",
"new",
"StructureShape",
"(",
"[",
"]",
",",
"$",
"this",
"->",
"shapeMap",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"input",
";",
"}"
] | Get the input shape of the operation.
@return StructureShape | [
"Get",
"the",
"input",
"shape",
"of",
"the",
"operation",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Operation.php#L46-L57 | train |
aws/aws-sdk-php | src/Api/Operation.php | Operation.getOutput | public function getOutput()
{
if (!$this->output) {
if ($output = $this['output']) {
$this->output = $this->shapeFor($output);
} else {
$this->output = new StructureShape([], $this->shapeMap);
}
}
return $this->output;
} | php | public function getOutput()
{
if (!$this->output) {
if ($output = $this['output']) {
$this->output = $this->shapeFor($output);
} else {
$this->output = new StructureShape([], $this->shapeMap);
}
}
return $this->output;
} | [
"public",
"function",
"getOutput",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"output",
")",
"{",
"if",
"(",
"$",
"output",
"=",
"$",
"this",
"[",
"'output'",
"]",
")",
"{",
"$",
"this",
"->",
"output",
"=",
"$",
"this",
"->",
"shapeFor",
"(",
"$",
"output",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"output",
"=",
"new",
"StructureShape",
"(",
"[",
"]",
",",
"$",
"this",
"->",
"shapeMap",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"output",
";",
"}"
] | Get the output shape of the operation.
@return StructureShape | [
"Get",
"the",
"output",
"shape",
"of",
"the",
"operation",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Operation.php#L64-L75 | train |
aws/aws-sdk-php | src/Api/Operation.php | Operation.getErrors | public function getErrors()
{
if ($this->errors === null) {
if ($errors = $this['errors']) {
foreach ($errors as $key => $error) {
$errors[$key] = $this->shapeFor($error);
}
$this->errors = $errors;
} else {
$this->errors = [];
}
}
return $this->errors;
} | php | public function getErrors()
{
if ($this->errors === null) {
if ($errors = $this['errors']) {
foreach ($errors as $key => $error) {
$errors[$key] = $this->shapeFor($error);
}
$this->errors = $errors;
} else {
$this->errors = [];
}
}
return $this->errors;
} | [
"public",
"function",
"getErrors",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"errors",
"===",
"null",
")",
"{",
"if",
"(",
"$",
"errors",
"=",
"$",
"this",
"[",
"'errors'",
"]",
")",
"{",
"foreach",
"(",
"$",
"errors",
"as",
"$",
"key",
"=>",
"$",
"error",
")",
"{",
"$",
"errors",
"[",
"$",
"key",
"]",
"=",
"$",
"this",
"->",
"shapeFor",
"(",
"$",
"error",
")",
";",
"}",
"$",
"this",
"->",
"errors",
"=",
"$",
"errors",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"errors",
"=",
"[",
"]",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"errors",
";",
"}"
] | Get an array of operation error shapes.
@return Shape[] | [
"Get",
"an",
"array",
"of",
"operation",
"error",
"shapes",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Operation.php#L82-L96 | train |
aws/aws-sdk-php | src/History.php | History.start | public function start(CommandInterface $cmd, RequestInterface $req)
{
$ticket = uniqid();
$this->entries[$ticket] = [
'command' => $cmd,
'request' => $req,
'result' => null,
'exception' => null,
];
return $ticket;
} | php | public function start(CommandInterface $cmd, RequestInterface $req)
{
$ticket = uniqid();
$this->entries[$ticket] = [
'command' => $cmd,
'request' => $req,
'result' => null,
'exception' => null,
];
return $ticket;
} | [
"public",
"function",
"start",
"(",
"CommandInterface",
"$",
"cmd",
",",
"RequestInterface",
"$",
"req",
")",
"{",
"$",
"ticket",
"=",
"uniqid",
"(",
")",
";",
"$",
"this",
"->",
"entries",
"[",
"$",
"ticket",
"]",
"=",
"[",
"'command'",
"=>",
"$",
"cmd",
",",
"'request'",
"=>",
"$",
"req",
",",
"'result'",
"=>",
"null",
",",
"'exception'",
"=>",
"null",
",",
"]",
";",
"return",
"$",
"ticket",
";",
"}"
] | Initiate an entry being added to the history.
@param CommandInterface $cmd Command be executed.
@param RequestInterface $req Request being sent.
@return string Returns the ticket used to finish the entry. | [
"Initiate",
"an",
"entry",
"being",
"added",
"to",
"the",
"history",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/History.php#L97-L108 | train |
aws/aws-sdk-php | src/DynamoDb/DynamoDbClient.php | DynamoDbClient.registerSessionHandler | public function registerSessionHandler(array $config = [])
{
$handler = SessionHandler::fromClient($this, $config);
$handler->register();
return $handler;
} | php | public function registerSessionHandler(array $config = [])
{
$handler = SessionHandler::fromClient($this, $config);
$handler->register();
return $handler;
} | [
"public",
"function",
"registerSessionHandler",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"handler",
"=",
"SessionHandler",
"::",
"fromClient",
"(",
"$",
"this",
",",
"$",
"config",
")",
";",
"$",
"handler",
"->",
"register",
"(",
")",
";",
"return",
"$",
"handler",
";",
"}"
] | Convenience method for instantiating and registering the DynamoDB
Session handler with this DynamoDB client object.
@param array $config Array of options for the session handler factory
@return SessionHandler | [
"Convenience",
"method",
"for",
"instantiating",
"and",
"registering",
"the",
"DynamoDB",
"Session",
"handler",
"with",
"this",
"DynamoDB",
"client",
"object",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/DynamoDbClient.php#L108-L114 | train |
aws/aws-sdk-php | src/Sts/StsClient.php | StsClient.createCredentials | public function createCredentials(Result $result)
{
if (!$result->hasKey('Credentials')) {
throw new \InvalidArgumentException('Result contains no credentials');
}
$c = $result['Credentials'];
return new Credentials(
$c['AccessKeyId'],
$c['SecretAccessKey'],
isset($c['SessionToken']) ? $c['SessionToken'] : null,
isset($c['Expiration']) && $c['Expiration'] instanceof \DateTimeInterface
? (int) $c['Expiration']->format('U')
: null
);
} | php | public function createCredentials(Result $result)
{
if (!$result->hasKey('Credentials')) {
throw new \InvalidArgumentException('Result contains no credentials');
}
$c = $result['Credentials'];
return new Credentials(
$c['AccessKeyId'],
$c['SecretAccessKey'],
isset($c['SessionToken']) ? $c['SessionToken'] : null,
isset($c['Expiration']) && $c['Expiration'] instanceof \DateTimeInterface
? (int) $c['Expiration']->format('U')
: null
);
} | [
"public",
"function",
"createCredentials",
"(",
"Result",
"$",
"result",
")",
"{",
"if",
"(",
"!",
"$",
"result",
"->",
"hasKey",
"(",
"'Credentials'",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Result contains no credentials'",
")",
";",
"}",
"$",
"c",
"=",
"$",
"result",
"[",
"'Credentials'",
"]",
";",
"return",
"new",
"Credentials",
"(",
"$",
"c",
"[",
"'AccessKeyId'",
"]",
",",
"$",
"c",
"[",
"'SecretAccessKey'",
"]",
",",
"isset",
"(",
"$",
"c",
"[",
"'SessionToken'",
"]",
")",
"?",
"$",
"c",
"[",
"'SessionToken'",
"]",
":",
"null",
",",
"isset",
"(",
"$",
"c",
"[",
"'Expiration'",
"]",
")",
"&&",
"$",
"c",
"[",
"'Expiration'",
"]",
"instanceof",
"\\",
"DateTimeInterface",
"?",
"(",
"int",
")",
"$",
"c",
"[",
"'Expiration'",
"]",
"->",
"format",
"(",
"'U'",
")",
":",
"null",
")",
";",
"}"
] | Creates credentials from the result of an STS operations
@param Result $result Result of an STS operation
@return Credentials
@throws \InvalidArgumentException if the result contains no credentials | [
"Creates",
"credentials",
"from",
"the",
"result",
"of",
"an",
"STS",
"operations"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Sts/StsClient.php#L36-L52 | train |
aws/aws-sdk-php | src/Api/Parser/AbstractRestParser.php | AbstractRestParser.extractHeader | private function extractHeader(
$name,
Shape $shape,
ResponseInterface $response,
&$result
) {
$value = $response->getHeaderLine($shape['locationName'] ?: $name);
switch ($shape->getType()) {
case 'float':
case 'double':
$value = (float) $value;
break;
case 'long':
$value = (int) $value;
break;
case 'boolean':
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
break;
case 'blob':
$value = base64_decode($value);
break;
case 'timestamp':
try {
if (!empty($shape['timestampFormat'])
&& $shape['timestampFormat'] === 'unixTimestamp') {
$value = DateTimeResult::fromEpoch($value);
}
$value = new DateTimeResult($value);
break;
} catch (\Exception $e) {
// If the value cannot be parsed, then do not add it to the
// output structure.
return;
}
case 'string':
if ($shape['jsonvalue']) {
$value = $this->parseJson(base64_decode($value), $response);
}
break;
}
$result[$name] = $value;
} | php | private function extractHeader(
$name,
Shape $shape,
ResponseInterface $response,
&$result
) {
$value = $response->getHeaderLine($shape['locationName'] ?: $name);
switch ($shape->getType()) {
case 'float':
case 'double':
$value = (float) $value;
break;
case 'long':
$value = (int) $value;
break;
case 'boolean':
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
break;
case 'blob':
$value = base64_decode($value);
break;
case 'timestamp':
try {
if (!empty($shape['timestampFormat'])
&& $shape['timestampFormat'] === 'unixTimestamp') {
$value = DateTimeResult::fromEpoch($value);
}
$value = new DateTimeResult($value);
break;
} catch (\Exception $e) {
// If the value cannot be parsed, then do not add it to the
// output structure.
return;
}
case 'string':
if ($shape['jsonvalue']) {
$value = $this->parseJson(base64_decode($value), $response);
}
break;
}
$result[$name] = $value;
} | [
"private",
"function",
"extractHeader",
"(",
"$",
"name",
",",
"Shape",
"$",
"shape",
",",
"ResponseInterface",
"$",
"response",
",",
"&",
"$",
"result",
")",
"{",
"$",
"value",
"=",
"$",
"response",
"->",
"getHeaderLine",
"(",
"$",
"shape",
"[",
"'locationName'",
"]",
"?",
":",
"$",
"name",
")",
";",
"switch",
"(",
"$",
"shape",
"->",
"getType",
"(",
")",
")",
"{",
"case",
"'float'",
":",
"case",
"'double'",
":",
"$",
"value",
"=",
"(",
"float",
")",
"$",
"value",
";",
"break",
";",
"case",
"'long'",
":",
"$",
"value",
"=",
"(",
"int",
")",
"$",
"value",
";",
"break",
";",
"case",
"'boolean'",
":",
"$",
"value",
"=",
"filter_var",
"(",
"$",
"value",
",",
"FILTER_VALIDATE_BOOLEAN",
")",
";",
"break",
";",
"case",
"'blob'",
":",
"$",
"value",
"=",
"base64_decode",
"(",
"$",
"value",
")",
";",
"break",
";",
"case",
"'timestamp'",
":",
"try",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"shape",
"[",
"'timestampFormat'",
"]",
")",
"&&",
"$",
"shape",
"[",
"'timestampFormat'",
"]",
"===",
"'unixTimestamp'",
")",
"{",
"$",
"value",
"=",
"DateTimeResult",
"::",
"fromEpoch",
"(",
"$",
"value",
")",
";",
"}",
"$",
"value",
"=",
"new",
"DateTimeResult",
"(",
"$",
"value",
")",
";",
"break",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"// If the value cannot be parsed, then do not add it to the",
"// output structure.",
"return",
";",
"}",
"case",
"'string'",
":",
"if",
"(",
"$",
"shape",
"[",
"'jsonvalue'",
"]",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"parseJson",
"(",
"base64_decode",
"(",
"$",
"value",
")",
",",
"$",
"response",
")",
";",
"}",
"break",
";",
"}",
"$",
"result",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"}"
] | Extract a single header from the response into the result. | [
"Extract",
"a",
"single",
"header",
"from",
"the",
"response",
"into",
"the",
"result",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Parser/AbstractRestParser.php#L95-L138 | train |
aws/aws-sdk-php | src/Api/Parser/AbstractRestParser.php | AbstractRestParser.extractHeaders | private function extractHeaders(
$name,
Shape $shape,
ResponseInterface $response,
&$result
) {
// Check if the headers are prefixed by a location name
$result[$name] = [];
$prefix = $shape['locationName'];
$prefixLen = strlen($prefix);
foreach ($response->getHeaders() as $k => $values) {
if (!$prefixLen) {
$result[$name][$k] = implode(', ', $values);
} elseif (stripos($k, $prefix) === 0) {
$result[$name][substr($k, $prefixLen)] = implode(', ', $values);
}
}
} | php | private function extractHeaders(
$name,
Shape $shape,
ResponseInterface $response,
&$result
) {
// Check if the headers are prefixed by a location name
$result[$name] = [];
$prefix = $shape['locationName'];
$prefixLen = strlen($prefix);
foreach ($response->getHeaders() as $k => $values) {
if (!$prefixLen) {
$result[$name][$k] = implode(', ', $values);
} elseif (stripos($k, $prefix) === 0) {
$result[$name][substr($k, $prefixLen)] = implode(', ', $values);
}
}
} | [
"private",
"function",
"extractHeaders",
"(",
"$",
"name",
",",
"Shape",
"$",
"shape",
",",
"ResponseInterface",
"$",
"response",
",",
"&",
"$",
"result",
")",
"{",
"// Check if the headers are prefixed by a location name",
"$",
"result",
"[",
"$",
"name",
"]",
"=",
"[",
"]",
";",
"$",
"prefix",
"=",
"$",
"shape",
"[",
"'locationName'",
"]",
";",
"$",
"prefixLen",
"=",
"strlen",
"(",
"$",
"prefix",
")",
";",
"foreach",
"(",
"$",
"response",
"->",
"getHeaders",
"(",
")",
"as",
"$",
"k",
"=>",
"$",
"values",
")",
"{",
"if",
"(",
"!",
"$",
"prefixLen",
")",
"{",
"$",
"result",
"[",
"$",
"name",
"]",
"[",
"$",
"k",
"]",
"=",
"implode",
"(",
"', '",
",",
"$",
"values",
")",
";",
"}",
"elseif",
"(",
"stripos",
"(",
"$",
"k",
",",
"$",
"prefix",
")",
"===",
"0",
")",
"{",
"$",
"result",
"[",
"$",
"name",
"]",
"[",
"substr",
"(",
"$",
"k",
",",
"$",
"prefixLen",
")",
"]",
"=",
"implode",
"(",
"', '",
",",
"$",
"values",
")",
";",
"}",
"}",
"}"
] | Extract a map of headers with an optional prefix from the response. | [
"Extract",
"a",
"map",
"of",
"headers",
"with",
"an",
"optional",
"prefix",
"from",
"the",
"response",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Parser/AbstractRestParser.php#L143-L161 | train |
aws/aws-sdk-php | src/Api/Parser/AbstractRestParser.php | AbstractRestParser.extractStatus | private function extractStatus(
$name,
ResponseInterface $response,
array &$result
) {
$result[$name] = (int) $response->getStatusCode();
} | php | private function extractStatus(
$name,
ResponseInterface $response,
array &$result
) {
$result[$name] = (int) $response->getStatusCode();
} | [
"private",
"function",
"extractStatus",
"(",
"$",
"name",
",",
"ResponseInterface",
"$",
"response",
",",
"array",
"&",
"$",
"result",
")",
"{",
"$",
"result",
"[",
"$",
"name",
"]",
"=",
"(",
"int",
")",
"$",
"response",
"->",
"getStatusCode",
"(",
")",
";",
"}"
] | Places the status code of the response into the result array. | [
"Places",
"the",
"status",
"code",
"of",
"the",
"response",
"into",
"the",
"result",
"array",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Parser/AbstractRestParser.php#L166-L172 | train |
aws/aws-sdk-php | src/Signature/SignatureV4.php | SignatureV4.getHeaderBlacklist | private function getHeaderBlacklist()
{
return [
'cache-control' => true,
'content-type' => true,
'content-length' => true,
'expect' => true,
'max-forwards' => true,
'pragma' => true,
'range' => true,
'te' => true,
'if-match' => true,
'if-none-match' => true,
'if-modified-since' => true,
'if-unmodified-since' => true,
'if-range' => true,
'accept' => true,
'authorization' => true,
'proxy-authorization' => true,
'from' => true,
'referer' => true,
'user-agent' => true,
'x-amzn-trace-id' => true,
'aws-sdk-invocation-id' => true,
'aws-sdk-retry' => true,
];
} | php | private function getHeaderBlacklist()
{
return [
'cache-control' => true,
'content-type' => true,
'content-length' => true,
'expect' => true,
'max-forwards' => true,
'pragma' => true,
'range' => true,
'te' => true,
'if-match' => true,
'if-none-match' => true,
'if-modified-since' => true,
'if-unmodified-since' => true,
'if-range' => true,
'accept' => true,
'authorization' => true,
'proxy-authorization' => true,
'from' => true,
'referer' => true,
'user-agent' => true,
'x-amzn-trace-id' => true,
'aws-sdk-invocation-id' => true,
'aws-sdk-retry' => true,
];
} | [
"private",
"function",
"getHeaderBlacklist",
"(",
")",
"{",
"return",
"[",
"'cache-control'",
"=>",
"true",
",",
"'content-type'",
"=>",
"true",
",",
"'content-length'",
"=>",
"true",
",",
"'expect'",
"=>",
"true",
",",
"'max-forwards'",
"=>",
"true",
",",
"'pragma'",
"=>",
"true",
",",
"'range'",
"=>",
"true",
",",
"'te'",
"=>",
"true",
",",
"'if-match'",
"=>",
"true",
",",
"'if-none-match'",
"=>",
"true",
",",
"'if-modified-since'",
"=>",
"true",
",",
"'if-unmodified-since'",
"=>",
"true",
",",
"'if-range'",
"=>",
"true",
",",
"'accept'",
"=>",
"true",
",",
"'authorization'",
"=>",
"true",
",",
"'proxy-authorization'",
"=>",
"true",
",",
"'from'",
"=>",
"true",
",",
"'referer'",
"=>",
"true",
",",
"'user-agent'",
"=>",
"true",
",",
"'x-amzn-trace-id'",
"=>",
"true",
",",
"'aws-sdk-invocation-id'",
"=>",
"true",
",",
"'aws-sdk-retry'",
"=>",
"true",
",",
"]",
";",
"}"
] | The following headers are not signed because signing these headers
would potentially cause a signature mismatch when sending a request
through a proxy or if modified at the HTTP client level.
@return array | [
"The",
"following",
"headers",
"are",
"not",
"signed",
"because",
"signing",
"these",
"headers",
"would",
"potentially",
"cause",
"a",
"signature",
"mismatch",
"when",
"sending",
"a",
"request",
"through",
"a",
"proxy",
"or",
"if",
"modified",
"at",
"the",
"HTTP",
"client",
"level",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Signature/SignatureV4.php#L36-L62 | train |
aws/aws-sdk-php | src/Signature/SignatureV4.php | SignatureV4.getPresignHeaders | private function getPresignHeaders(array $headers)
{
$presignHeaders = [];
$blacklist = $this->getHeaderBlacklist();
foreach ($headers as $name => $value) {
$lName = strtolower($name);
if (!isset($blacklist[$lName])
&& $name !== self::AMZ_CONTENT_SHA256_HEADER
) {
$presignHeaders[] = $lName;
}
}
return $presignHeaders;
} | php | private function getPresignHeaders(array $headers)
{
$presignHeaders = [];
$blacklist = $this->getHeaderBlacklist();
foreach ($headers as $name => $value) {
$lName = strtolower($name);
if (!isset($blacklist[$lName])
&& $name !== self::AMZ_CONTENT_SHA256_HEADER
) {
$presignHeaders[] = $lName;
}
}
return $presignHeaders;
} | [
"private",
"function",
"getPresignHeaders",
"(",
"array",
"$",
"headers",
")",
"{",
"$",
"presignHeaders",
"=",
"[",
"]",
";",
"$",
"blacklist",
"=",
"$",
"this",
"->",
"getHeaderBlacklist",
"(",
")",
";",
"foreach",
"(",
"$",
"headers",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"lName",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"blacklist",
"[",
"$",
"lName",
"]",
")",
"&&",
"$",
"name",
"!==",
"self",
"::",
"AMZ_CONTENT_SHA256_HEADER",
")",
"{",
"$",
"presignHeaders",
"[",
"]",
"=",
"$",
"lName",
";",
"}",
"}",
"return",
"$",
"presignHeaders",
";",
"}"
] | Get the headers that were used to pre-sign the request.
Used for the X-Amz-SignedHeaders header.
@param array $headers
@return array | [
"Get",
"the",
"headers",
"that",
"were",
"used",
"to",
"pre",
"-",
"sign",
"the",
"request",
".",
"Used",
"for",
"the",
"X",
"-",
"Amz",
"-",
"SignedHeaders",
"header",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Signature/SignatureV4.php#L122-L135 | train |
aws/aws-sdk-php | src/Signature/SignatureV4.php | SignatureV4.convertPostToGet | public static function convertPostToGet(RequestInterface $request)
{
if ($request->getMethod() !== 'POST') {
throw new \InvalidArgumentException('Expected a POST request but '
. 'received a ' . $request->getMethod() . ' request.');
}
$sr = $request->withMethod('GET')
->withBody(Psr7\stream_for(''))
->withoutHeader('Content-Type')
->withoutHeader('Content-Length');
// Move POST fields to the query if they are present
if ($request->getHeaderLine('Content-Type') === 'application/x-www-form-urlencoded') {
$body = (string) $request->getBody();
$sr = $sr->withUri($sr->getUri()->withQuery($body));
}
return $sr;
} | php | public static function convertPostToGet(RequestInterface $request)
{
if ($request->getMethod() !== 'POST') {
throw new \InvalidArgumentException('Expected a POST request but '
. 'received a ' . $request->getMethod() . ' request.');
}
$sr = $request->withMethod('GET')
->withBody(Psr7\stream_for(''))
->withoutHeader('Content-Type')
->withoutHeader('Content-Length');
// Move POST fields to the query if they are present
if ($request->getHeaderLine('Content-Type') === 'application/x-www-form-urlencoded') {
$body = (string) $request->getBody();
$sr = $sr->withUri($sr->getUri()->withQuery($body));
}
return $sr;
} | [
"public",
"static",
"function",
"convertPostToGet",
"(",
"RequestInterface",
"$",
"request",
")",
"{",
"if",
"(",
"$",
"request",
"->",
"getMethod",
"(",
")",
"!==",
"'POST'",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Expected a POST request but '",
".",
"'received a '",
".",
"$",
"request",
"->",
"getMethod",
"(",
")",
".",
"' request.'",
")",
";",
"}",
"$",
"sr",
"=",
"$",
"request",
"->",
"withMethod",
"(",
"'GET'",
")",
"->",
"withBody",
"(",
"Psr7",
"\\",
"stream_for",
"(",
"''",
")",
")",
"->",
"withoutHeader",
"(",
"'Content-Type'",
")",
"->",
"withoutHeader",
"(",
"'Content-Length'",
")",
";",
"// Move POST fields to the query if they are present",
"if",
"(",
"$",
"request",
"->",
"getHeaderLine",
"(",
"'Content-Type'",
")",
"===",
"'application/x-www-form-urlencoded'",
")",
"{",
"$",
"body",
"=",
"(",
"string",
")",
"$",
"request",
"->",
"getBody",
"(",
")",
";",
"$",
"sr",
"=",
"$",
"sr",
"->",
"withUri",
"(",
"$",
"sr",
"->",
"getUri",
"(",
")",
"->",
"withQuery",
"(",
"$",
"body",
")",
")",
";",
"}",
"return",
"$",
"sr",
";",
"}"
] | Converts a POST request to a GET request by moving POST fields into the
query string.
Useful for pre-signing query protocol requests.
@param RequestInterface $request Request to clone
@return RequestInterface
@throws \InvalidArgumentException if the method is not POST | [
"Converts",
"a",
"POST",
"request",
"to",
"a",
"GET",
"request",
"by",
"moving",
"POST",
"fields",
"into",
"the",
"query",
"string",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Signature/SignatureV4.php#L188-L207 | train |
aws/aws-sdk-php | src/EndpointDiscovery/ConfigurationProvider.php | ConfigurationProvider.env | public static function env($cacheLimit = self::DEFAULT_CACHE_LIMIT)
{
return function () use ($cacheLimit) {
// Use config from environment variables, if available
$enabled = getenv(self::ENV_ENABLED);
if ($enabled === false || $enabled === '') {
$enabled = getenv(self::ENV_ENABLED_ALT);
}
if ($enabled !== false && $enabled !== '') {
return Promise\promise_for(
new Configuration($enabled, $cacheLimit)
);
}
return self::reject('Could not find environment variable config'
. ' in ' . self::ENV_ENABLED);
};
} | php | public static function env($cacheLimit = self::DEFAULT_CACHE_LIMIT)
{
return function () use ($cacheLimit) {
// Use config from environment variables, if available
$enabled = getenv(self::ENV_ENABLED);
if ($enabled === false || $enabled === '') {
$enabled = getenv(self::ENV_ENABLED_ALT);
}
if ($enabled !== false && $enabled !== '') {
return Promise\promise_for(
new Configuration($enabled, $cacheLimit)
);
}
return self::reject('Could not find environment variable config'
. ' in ' . self::ENV_ENABLED);
};
} | [
"public",
"static",
"function",
"env",
"(",
"$",
"cacheLimit",
"=",
"self",
"::",
"DEFAULT_CACHE_LIMIT",
")",
"{",
"return",
"function",
"(",
")",
"use",
"(",
"$",
"cacheLimit",
")",
"{",
"// Use config from environment variables, if available",
"$",
"enabled",
"=",
"getenv",
"(",
"self",
"::",
"ENV_ENABLED",
")",
";",
"if",
"(",
"$",
"enabled",
"===",
"false",
"||",
"$",
"enabled",
"===",
"''",
")",
"{",
"$",
"enabled",
"=",
"getenv",
"(",
"self",
"::",
"ENV_ENABLED_ALT",
")",
";",
"}",
"if",
"(",
"$",
"enabled",
"!==",
"false",
"&&",
"$",
"enabled",
"!==",
"''",
")",
"{",
"return",
"Promise",
"\\",
"promise_for",
"(",
"new",
"Configuration",
"(",
"$",
"enabled",
",",
"$",
"cacheLimit",
")",
")",
";",
"}",
"return",
"self",
"::",
"reject",
"(",
"'Could not find environment variable config'",
".",
"' in '",
".",
"self",
"::",
"ENV_ENABLED",
")",
";",
"}",
";",
"}"
] | Provider that creates config from environment variables.
@param $cacheLimit
@return callable | [
"Provider",
"that",
"creates",
"config",
"from",
"environment",
"variables",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/EndpointDiscovery/ConfigurationProvider.php#L153-L170 | train |
aws/aws-sdk-php | src/EndpointDiscovery/ConfigurationProvider.php | ConfigurationProvider.ini | public static function ini(
$profile = null,
$filename = null,
$cacheLimit = self::DEFAULT_CACHE_LIMIT
) {
$filename = $filename ?: (self::getHomeDir() . '/.aws/config');
$profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
return function () use ($profile, $filename, $cacheLimit) {
if (!is_readable($filename)) {
return self::reject("Cannot read configuration from $filename");
}
$data = \Aws\parse_ini_file($filename, true);
if ($data === false) {
return self::reject("Invalid config file: $filename");
}
if (!isset($data[$profile])) {
return self::reject("'$profile' not found in config file");
}
if (!isset($data[$profile]['endpoint_discovery_enabled'])) {
return self::reject("Required endpoint discovery config values
not present in INI profile '{$profile}' ({$filename})");
}
return Promise\promise_for(
new Configuration(
$data[$profile]['endpoint_discovery_enabled'],
$cacheLimit
)
);
};
} | php | public static function ini(
$profile = null,
$filename = null,
$cacheLimit = self::DEFAULT_CACHE_LIMIT
) {
$filename = $filename ?: (self::getHomeDir() . '/.aws/config');
$profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
return function () use ($profile, $filename, $cacheLimit) {
if (!is_readable($filename)) {
return self::reject("Cannot read configuration from $filename");
}
$data = \Aws\parse_ini_file($filename, true);
if ($data === false) {
return self::reject("Invalid config file: $filename");
}
if (!isset($data[$profile])) {
return self::reject("'$profile' not found in config file");
}
if (!isset($data[$profile]['endpoint_discovery_enabled'])) {
return self::reject("Required endpoint discovery config values
not present in INI profile '{$profile}' ({$filename})");
}
return Promise\promise_for(
new Configuration(
$data[$profile]['endpoint_discovery_enabled'],
$cacheLimit
)
);
};
} | [
"public",
"static",
"function",
"ini",
"(",
"$",
"profile",
"=",
"null",
",",
"$",
"filename",
"=",
"null",
",",
"$",
"cacheLimit",
"=",
"self",
"::",
"DEFAULT_CACHE_LIMIT",
")",
"{",
"$",
"filename",
"=",
"$",
"filename",
"?",
":",
"(",
"self",
"::",
"getHomeDir",
"(",
")",
".",
"'/.aws/config'",
")",
";",
"$",
"profile",
"=",
"$",
"profile",
"?",
":",
"(",
"getenv",
"(",
"self",
"::",
"ENV_PROFILE",
")",
"?",
":",
"'default'",
")",
";",
"return",
"function",
"(",
")",
"use",
"(",
"$",
"profile",
",",
"$",
"filename",
",",
"$",
"cacheLimit",
")",
"{",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"filename",
")",
")",
"{",
"return",
"self",
"::",
"reject",
"(",
"\"Cannot read configuration from $filename\"",
")",
";",
"}",
"$",
"data",
"=",
"\\",
"Aws",
"\\",
"parse_ini_file",
"(",
"$",
"filename",
",",
"true",
")",
";",
"if",
"(",
"$",
"data",
"===",
"false",
")",
"{",
"return",
"self",
"::",
"reject",
"(",
"\"Invalid config file: $filename\"",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"$",
"profile",
"]",
")",
")",
"{",
"return",
"self",
"::",
"reject",
"(",
"\"'$profile' not found in config file\"",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"$",
"profile",
"]",
"[",
"'endpoint_discovery_enabled'",
"]",
")",
")",
"{",
"return",
"self",
"::",
"reject",
"(",
"\"Required endpoint discovery config values \n not present in INI profile '{$profile}' ({$filename})\"",
")",
";",
"}",
"return",
"Promise",
"\\",
"promise_for",
"(",
"new",
"Configuration",
"(",
"$",
"data",
"[",
"$",
"profile",
"]",
"[",
"'endpoint_discovery_enabled'",
"]",
",",
"$",
"cacheLimit",
")",
")",
";",
"}",
";",
"}"
] | Config provider that creates config 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/config".
@param string|null $filename If provided, uses a custom filename rather
than looking in the home directory.
@param int $cacheLimit
@return callable | [
"Config",
"provider",
"that",
"creates",
"config",
"using",
"an",
"ini",
"file",
"stored",
"in",
"the",
"current",
"user",
"s",
"home",
"directory",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/EndpointDiscovery/ConfigurationProvider.php#L220-L251 | train |
aws/aws-sdk-php | src/MockHandler.php | MockHandler.appendException | public function appendException()
{
foreach (func_get_args() as $value) {
if ($value instanceof \Exception || $value instanceof \Throwable) {
$this->queue[] = $value;
} else {
throw new \InvalidArgumentException('Expected an \Exception or \Throwable.');
}
}
} | php | public function appendException()
{
foreach (func_get_args() as $value) {
if ($value instanceof \Exception || $value instanceof \Throwable) {
$this->queue[] = $value;
} else {
throw new \InvalidArgumentException('Expected an \Exception or \Throwable.');
}
}
} | [
"public",
"function",
"appendException",
"(",
")",
"{",
"foreach",
"(",
"func_get_args",
"(",
")",
"as",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"instanceof",
"\\",
"Exception",
"||",
"$",
"value",
"instanceof",
"\\",
"Throwable",
")",
"{",
"$",
"this",
"->",
"queue",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Expected an \\Exception or \\Throwable.'",
")",
";",
"}",
"}",
"}"
] | Adds one or more \Exception or \Throwable to the queue | [
"Adds",
"one",
"or",
"more",
"\\",
"Exception",
"or",
"\\",
"Throwable",
"to",
"the",
"queue"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/MockHandler.php#L64-L73 | train |
aws/aws-sdk-php | src/CloudTrail/LogFileReader.php | LogFileReader.read | public function read($s3BucketName, $logFileKey)
{
// Create a command for getting the log file object
$command = $this->s3Client->getCommand('GetObject', [
'Bucket' => (string) $s3BucketName,
'Key' => (string) $logFileKey,
'ResponseContentEncoding' => 'x-gzip'
]);
// Make sure gzip encoding header is sent and accepted in order to
// inflate the response data.
$command['@http']['headers']['Accept-Encoding'] = 'gzip';
// Get the JSON response data and extract the log records
$result = $this->s3Client->execute($command);
$logData = json_decode($result['Body'], true);
return isset($logData['Records']) ? $logData['Records'] : [];
} | php | public function read($s3BucketName, $logFileKey)
{
// Create a command for getting the log file object
$command = $this->s3Client->getCommand('GetObject', [
'Bucket' => (string) $s3BucketName,
'Key' => (string) $logFileKey,
'ResponseContentEncoding' => 'x-gzip'
]);
// Make sure gzip encoding header is sent and accepted in order to
// inflate the response data.
$command['@http']['headers']['Accept-Encoding'] = 'gzip';
// Get the JSON response data and extract the log records
$result = $this->s3Client->execute($command);
$logData = json_decode($result['Body'], true);
return isset($logData['Records']) ? $logData['Records'] : [];
} | [
"public",
"function",
"read",
"(",
"$",
"s3BucketName",
",",
"$",
"logFileKey",
")",
"{",
"// Create a command for getting the log file object",
"$",
"command",
"=",
"$",
"this",
"->",
"s3Client",
"->",
"getCommand",
"(",
"'GetObject'",
",",
"[",
"'Bucket'",
"=>",
"(",
"string",
")",
"$",
"s3BucketName",
",",
"'Key'",
"=>",
"(",
"string",
")",
"$",
"logFileKey",
",",
"'ResponseContentEncoding'",
"=>",
"'x-gzip'",
"]",
")",
";",
"// Make sure gzip encoding header is sent and accepted in order to",
"// inflate the response data.",
"$",
"command",
"[",
"'@http'",
"]",
"[",
"'headers'",
"]",
"[",
"'Accept-Encoding'",
"]",
"=",
"'gzip'",
";",
"// Get the JSON response data and extract the log records",
"$",
"result",
"=",
"$",
"this",
"->",
"s3Client",
"->",
"execute",
"(",
"$",
"command",
")",
";",
"$",
"logData",
"=",
"json_decode",
"(",
"$",
"result",
"[",
"'Body'",
"]",
",",
"true",
")",
";",
"return",
"isset",
"(",
"$",
"logData",
"[",
"'Records'",
"]",
")",
"?",
"$",
"logData",
"[",
"'Records'",
"]",
":",
"[",
"]",
";",
"}"
] | Downloads, unzips, and reads a CloudTrail log file from Amazon S3
@param string $s3BucketName The bucket name of the log file in Amazon S3
@param string $logFileKey The key of the log file in Amazon S3
@return array | [
"Downloads",
"unzips",
"and",
"reads",
"a",
"CloudTrail",
"log",
"file",
"from",
"Amazon",
"S3"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudTrail/LogFileReader.php#L36-L54 | train |
aws/aws-sdk-php | src/WrappedHttpHandler.php | WrappedHttpHandler.parseError | private function parseError(
array $err,
RequestInterface $request,
CommandInterface $command,
array $stats
) {
if (!isset($err['exception'])) {
throw new \RuntimeException('The HTTP handler was rejected without an "exception" key value pair.');
}
$serviceError = "AWS HTTP error: " . $err['exception']->getMessage();
if (!isset($err['response'])) {
$parts = ['response' => null];
} else {
try {
$parts = call_user_func($this->errorParser, $err['response']);
$serviceError .= " {$parts['code']} ({$parts['type']}): "
. "{$parts['message']} - " . $err['response']->getBody();
} catch (ParserException $e) {
$parts = [];
$serviceError .= ' Unable to parse error information from '
. "response - {$e->getMessage()}";
}
$parts['response'] = $err['response'];
}
$parts['exception'] = $err['exception'];
$parts['request'] = $request;
$parts['connection_error'] = !empty($err['connection_error']);
$parts['transfer_stats'] = $stats;
return new $this->exceptionClass(
sprintf(
'Error executing "%s" on "%s"; %s',
$command->getName(),
$request->getUri(),
$serviceError
),
$command,
$parts,
$err['exception']
);
} | php | private function parseError(
array $err,
RequestInterface $request,
CommandInterface $command,
array $stats
) {
if (!isset($err['exception'])) {
throw new \RuntimeException('The HTTP handler was rejected without an "exception" key value pair.');
}
$serviceError = "AWS HTTP error: " . $err['exception']->getMessage();
if (!isset($err['response'])) {
$parts = ['response' => null];
} else {
try {
$parts = call_user_func($this->errorParser, $err['response']);
$serviceError .= " {$parts['code']} ({$parts['type']}): "
. "{$parts['message']} - " . $err['response']->getBody();
} catch (ParserException $e) {
$parts = [];
$serviceError .= ' Unable to parse error information from '
. "response - {$e->getMessage()}";
}
$parts['response'] = $err['response'];
}
$parts['exception'] = $err['exception'];
$parts['request'] = $request;
$parts['connection_error'] = !empty($err['connection_error']);
$parts['transfer_stats'] = $stats;
return new $this->exceptionClass(
sprintf(
'Error executing "%s" on "%s"; %s',
$command->getName(),
$request->getUri(),
$serviceError
),
$command,
$parts,
$err['exception']
);
} | [
"private",
"function",
"parseError",
"(",
"array",
"$",
"err",
",",
"RequestInterface",
"$",
"request",
",",
"CommandInterface",
"$",
"command",
",",
"array",
"$",
"stats",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"err",
"[",
"'exception'",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'The HTTP handler was rejected without an \"exception\" key value pair.'",
")",
";",
"}",
"$",
"serviceError",
"=",
"\"AWS HTTP error: \"",
".",
"$",
"err",
"[",
"'exception'",
"]",
"->",
"getMessage",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"err",
"[",
"'response'",
"]",
")",
")",
"{",
"$",
"parts",
"=",
"[",
"'response'",
"=>",
"null",
"]",
";",
"}",
"else",
"{",
"try",
"{",
"$",
"parts",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"errorParser",
",",
"$",
"err",
"[",
"'response'",
"]",
")",
";",
"$",
"serviceError",
".=",
"\" {$parts['code']} ({$parts['type']}): \"",
".",
"\"{$parts['message']} - \"",
".",
"$",
"err",
"[",
"'response'",
"]",
"->",
"getBody",
"(",
")",
";",
"}",
"catch",
"(",
"ParserException",
"$",
"e",
")",
"{",
"$",
"parts",
"=",
"[",
"]",
";",
"$",
"serviceError",
".=",
"' Unable to parse error information from '",
".",
"\"response - {$e->getMessage()}\"",
";",
"}",
"$",
"parts",
"[",
"'response'",
"]",
"=",
"$",
"err",
"[",
"'response'",
"]",
";",
"}",
"$",
"parts",
"[",
"'exception'",
"]",
"=",
"$",
"err",
"[",
"'exception'",
"]",
";",
"$",
"parts",
"[",
"'request'",
"]",
"=",
"$",
"request",
";",
"$",
"parts",
"[",
"'connection_error'",
"]",
"=",
"!",
"empty",
"(",
"$",
"err",
"[",
"'connection_error'",
"]",
")",
";",
"$",
"parts",
"[",
"'transfer_stats'",
"]",
"=",
"$",
"stats",
";",
"return",
"new",
"$",
"this",
"->",
"exceptionClass",
"(",
"sprintf",
"(",
"'Error executing \"%s\" on \"%s\"; %s'",
",",
"$",
"command",
"->",
"getName",
"(",
")",
",",
"$",
"request",
"->",
"getUri",
"(",
")",
",",
"$",
"serviceError",
")",
",",
"$",
"command",
",",
"$",
"parts",
",",
"$",
"err",
"[",
"'exception'",
"]",
")",
";",
"}"
] | Parses a rejection into an AWS error.
@param array $err Rejection error array.
@param RequestInterface $request Request that was sent.
@param CommandInterface $command Command being sent.
@param array $stats Transfer statistics
@return \Exception | [
"Parses",
"a",
"rejection",
"into",
"an",
"AWS",
"error",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/WrappedHttpHandler.php#L158-L202 | train |
aws/aws-sdk-php | src/CloudTrail/LogFileIterator.php | LogFileIterator.buildListObjectsIterator | private function buildListObjectsIterator(array $options)
{
// Extract and normalize the date values from the options
$startDate = isset($options[self::START_DATE])
? $this->normalizeDateValue($options[self::START_DATE])
: null;
$endDate = isset($options[self::END_DATE])
? $this->normalizeDateValue($options[self::END_DATE])
: null;
// Determine the parts of the key prefix of the log files being read
$parts = [
'prefix' => isset($options[self::KEY_PREFIX])
? $options[self::KEY_PREFIX]
: null,
'account' => isset($options[self::ACCOUNT_ID])
? $options[self::ACCOUNT_ID]
: self::PREFIX_WILDCARD,
'region' => isset($options[self::LOG_REGION])
? $options[self::LOG_REGION]
: self::PREFIX_WILDCARD,
'date' => $this->determineDateForPrefix($startDate, $endDate),
];
// Determine the longest key prefix that can be used to retrieve all
// of the relevant log files.
$candidatePrefix = ltrim(strtr(self::PREFIX_TEMPLATE, $parts), '/');
$logKeyPrefix = $candidatePrefix;
$index = strpos($candidatePrefix, self::PREFIX_WILDCARD);
if ($index !== false) {
$logKeyPrefix = substr($candidatePrefix, 0, $index);
}
// Create an iterator that will emit all of the objects matching the
// key prefix.
$objectsIterator = $this->s3Client->getIterator('ListObjects', [
'Bucket' => $this->s3BucketName,
'Prefix' => $logKeyPrefix,
]);
// Apply regex and/or date filters to the objects iterator to emit only
// log files matching the options.
$objectsIterator = $this->applyRegexFilter(
$objectsIterator,
$logKeyPrefix,
$candidatePrefix
);
$objectsIterator = $this->applyDateFilter(
$objectsIterator,
$startDate,
$endDate
);
return $objectsIterator;
} | php | private function buildListObjectsIterator(array $options)
{
// Extract and normalize the date values from the options
$startDate = isset($options[self::START_DATE])
? $this->normalizeDateValue($options[self::START_DATE])
: null;
$endDate = isset($options[self::END_DATE])
? $this->normalizeDateValue($options[self::END_DATE])
: null;
// Determine the parts of the key prefix of the log files being read
$parts = [
'prefix' => isset($options[self::KEY_PREFIX])
? $options[self::KEY_PREFIX]
: null,
'account' => isset($options[self::ACCOUNT_ID])
? $options[self::ACCOUNT_ID]
: self::PREFIX_WILDCARD,
'region' => isset($options[self::LOG_REGION])
? $options[self::LOG_REGION]
: self::PREFIX_WILDCARD,
'date' => $this->determineDateForPrefix($startDate, $endDate),
];
// Determine the longest key prefix that can be used to retrieve all
// of the relevant log files.
$candidatePrefix = ltrim(strtr(self::PREFIX_TEMPLATE, $parts), '/');
$logKeyPrefix = $candidatePrefix;
$index = strpos($candidatePrefix, self::PREFIX_WILDCARD);
if ($index !== false) {
$logKeyPrefix = substr($candidatePrefix, 0, $index);
}
// Create an iterator that will emit all of the objects matching the
// key prefix.
$objectsIterator = $this->s3Client->getIterator('ListObjects', [
'Bucket' => $this->s3BucketName,
'Prefix' => $logKeyPrefix,
]);
// Apply regex and/or date filters to the objects iterator to emit only
// log files matching the options.
$objectsIterator = $this->applyRegexFilter(
$objectsIterator,
$logKeyPrefix,
$candidatePrefix
);
$objectsIterator = $this->applyDateFilter(
$objectsIterator,
$startDate,
$endDate
);
return $objectsIterator;
} | [
"private",
"function",
"buildListObjectsIterator",
"(",
"array",
"$",
"options",
")",
"{",
"// Extract and normalize the date values from the options",
"$",
"startDate",
"=",
"isset",
"(",
"$",
"options",
"[",
"self",
"::",
"START_DATE",
"]",
")",
"?",
"$",
"this",
"->",
"normalizeDateValue",
"(",
"$",
"options",
"[",
"self",
"::",
"START_DATE",
"]",
")",
":",
"null",
";",
"$",
"endDate",
"=",
"isset",
"(",
"$",
"options",
"[",
"self",
"::",
"END_DATE",
"]",
")",
"?",
"$",
"this",
"->",
"normalizeDateValue",
"(",
"$",
"options",
"[",
"self",
"::",
"END_DATE",
"]",
")",
":",
"null",
";",
"// Determine the parts of the key prefix of the log files being read",
"$",
"parts",
"=",
"[",
"'prefix'",
"=>",
"isset",
"(",
"$",
"options",
"[",
"self",
"::",
"KEY_PREFIX",
"]",
")",
"?",
"$",
"options",
"[",
"self",
"::",
"KEY_PREFIX",
"]",
":",
"null",
",",
"'account'",
"=>",
"isset",
"(",
"$",
"options",
"[",
"self",
"::",
"ACCOUNT_ID",
"]",
")",
"?",
"$",
"options",
"[",
"self",
"::",
"ACCOUNT_ID",
"]",
":",
"self",
"::",
"PREFIX_WILDCARD",
",",
"'region'",
"=>",
"isset",
"(",
"$",
"options",
"[",
"self",
"::",
"LOG_REGION",
"]",
")",
"?",
"$",
"options",
"[",
"self",
"::",
"LOG_REGION",
"]",
":",
"self",
"::",
"PREFIX_WILDCARD",
",",
"'date'",
"=>",
"$",
"this",
"->",
"determineDateForPrefix",
"(",
"$",
"startDate",
",",
"$",
"endDate",
")",
",",
"]",
";",
"// Determine the longest key prefix that can be used to retrieve all",
"// of the relevant log files.",
"$",
"candidatePrefix",
"=",
"ltrim",
"(",
"strtr",
"(",
"self",
"::",
"PREFIX_TEMPLATE",
",",
"$",
"parts",
")",
",",
"'/'",
")",
";",
"$",
"logKeyPrefix",
"=",
"$",
"candidatePrefix",
";",
"$",
"index",
"=",
"strpos",
"(",
"$",
"candidatePrefix",
",",
"self",
"::",
"PREFIX_WILDCARD",
")",
";",
"if",
"(",
"$",
"index",
"!==",
"false",
")",
"{",
"$",
"logKeyPrefix",
"=",
"substr",
"(",
"$",
"candidatePrefix",
",",
"0",
",",
"$",
"index",
")",
";",
"}",
"// Create an iterator that will emit all of the objects matching the",
"// key prefix.",
"$",
"objectsIterator",
"=",
"$",
"this",
"->",
"s3Client",
"->",
"getIterator",
"(",
"'ListObjects'",
",",
"[",
"'Bucket'",
"=>",
"$",
"this",
"->",
"s3BucketName",
",",
"'Prefix'",
"=>",
"$",
"logKeyPrefix",
",",
"]",
")",
";",
"// Apply regex and/or date filters to the objects iterator to emit only",
"// log files matching the options.",
"$",
"objectsIterator",
"=",
"$",
"this",
"->",
"applyRegexFilter",
"(",
"$",
"objectsIterator",
",",
"$",
"logKeyPrefix",
",",
"$",
"candidatePrefix",
")",
";",
"$",
"objectsIterator",
"=",
"$",
"this",
"->",
"applyDateFilter",
"(",
"$",
"objectsIterator",
",",
"$",
"startDate",
",",
"$",
"endDate",
")",
";",
"return",
"$",
"objectsIterator",
";",
"}"
] | Constructs an S3 ListObjects iterator, optionally decorated with
FilterIterators, based on the provided options.
@param array $options
@return \Iterator | [
"Constructs",
"an",
"S3",
"ListObjects",
"iterator",
"optionally",
"decorated",
"with",
"FilterIterators",
"based",
"on",
"the",
"provided",
"options",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudTrail/LogFileIterator.php#L150-L206 | train |
aws/aws-sdk-php | src/CloudTrail/LogFileIterator.php | LogFileIterator.normalizeDateValue | private function normalizeDateValue($date)
{
if (is_string($date)) {
$date = strtotime($date);
} elseif ($date instanceof \DateTime) {
$date = $date->format('U');
} elseif (!is_int($date)) {
throw new \InvalidArgumentException('Date values must be a '
. 'string, an int, or a DateTime object.');
}
return $date;
} | php | private function normalizeDateValue($date)
{
if (is_string($date)) {
$date = strtotime($date);
} elseif ($date instanceof \DateTime) {
$date = $date->format('U');
} elseif (!is_int($date)) {
throw new \InvalidArgumentException('Date values must be a '
. 'string, an int, or a DateTime object.');
}
return $date;
} | [
"private",
"function",
"normalizeDateValue",
"(",
"$",
"date",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"date",
")",
")",
"{",
"$",
"date",
"=",
"strtotime",
"(",
"$",
"date",
")",
";",
"}",
"elseif",
"(",
"$",
"date",
"instanceof",
"\\",
"DateTime",
")",
"{",
"$",
"date",
"=",
"$",
"date",
"->",
"format",
"(",
"'U'",
")",
";",
"}",
"elseif",
"(",
"!",
"is_int",
"(",
"$",
"date",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Date values must be a '",
".",
"'string, an int, or a DateTime object.'",
")",
";",
"}",
"return",
"$",
"date",
";",
"}"
] | Normalizes a date value to a unix timestamp
@param string|\DateTime|int $date
@return int
@throws \InvalidArgumentException if the value cannot be converted to
a timestamp | [
"Normalizes",
"a",
"date",
"value",
"to",
"a",
"unix",
"timestamp"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudTrail/LogFileIterator.php#L217-L229 | train |
aws/aws-sdk-php | src/CloudTrail/LogFileIterator.php | LogFileIterator.determineDateForPrefix | private function determineDateForPrefix($startDate, $endDate)
{
// The default date value should look like "*/*/*" after joining
$dateParts = array_fill_keys(['Y', 'm', 'd'], self::PREFIX_WILDCARD);
// Narrow down the date by replacing the WILDCARDs with values if they
// are the same for the start and end date.
if ($startDate && $endDate) {
foreach ($dateParts as $key => &$value) {
$candidateValue = date($key, $startDate);
if ($candidateValue === date($key, $endDate)) {
$value = $candidateValue;
} else {
break;
}
}
}
return join('/', $dateParts);
} | php | private function determineDateForPrefix($startDate, $endDate)
{
// The default date value should look like "*/*/*" after joining
$dateParts = array_fill_keys(['Y', 'm', 'd'], self::PREFIX_WILDCARD);
// Narrow down the date by replacing the WILDCARDs with values if they
// are the same for the start and end date.
if ($startDate && $endDate) {
foreach ($dateParts as $key => &$value) {
$candidateValue = date($key, $startDate);
if ($candidateValue === date($key, $endDate)) {
$value = $candidateValue;
} else {
break;
}
}
}
return join('/', $dateParts);
} | [
"private",
"function",
"determineDateForPrefix",
"(",
"$",
"startDate",
",",
"$",
"endDate",
")",
"{",
"// The default date value should look like \"*/*/*\" after joining",
"$",
"dateParts",
"=",
"array_fill_keys",
"(",
"[",
"'Y'",
",",
"'m'",
",",
"'d'",
"]",
",",
"self",
"::",
"PREFIX_WILDCARD",
")",
";",
"// Narrow down the date by replacing the WILDCARDs with values if they",
"// are the same for the start and end date.",
"if",
"(",
"$",
"startDate",
"&&",
"$",
"endDate",
")",
"{",
"foreach",
"(",
"$",
"dateParts",
"as",
"$",
"key",
"=>",
"&",
"$",
"value",
")",
"{",
"$",
"candidateValue",
"=",
"date",
"(",
"$",
"key",
",",
"$",
"startDate",
")",
";",
"if",
"(",
"$",
"candidateValue",
"===",
"date",
"(",
"$",
"key",
",",
"$",
"endDate",
")",
")",
"{",
"$",
"value",
"=",
"$",
"candidateValue",
";",
"}",
"else",
"{",
"break",
";",
"}",
"}",
"}",
"return",
"join",
"(",
"'/'",
",",
"$",
"dateParts",
")",
";",
"}"
] | Uses the provided date values to determine the date portion of the prefix | [
"Uses",
"the",
"provided",
"date",
"values",
"to",
"determine",
"the",
"date",
"portion",
"of",
"the",
"prefix"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudTrail/LogFileIterator.php#L234-L253 | train |
aws/aws-sdk-php | src/CloudTrail/LogFileIterator.php | LogFileIterator.applyRegexFilter | private function applyRegexFilter(
$objectsIterator,
$logKeyPrefix,
$candidatePrefix
) {
// If the prefix and candidate prefix are not the same, then there were
// WILDCARDs.
if ($logKeyPrefix !== $candidatePrefix) {
// Turn the candidate prefix into a regex by trimming and
// converting WILDCARDs to regex notation.
$regex = rtrim($candidatePrefix, '/' . self::PREFIX_WILDCARD) . '/';
$regex = strtr($regex, [self::PREFIX_WILDCARD => '[^/]+']);
// After trimming WILDCARDs or the end, if the regex is the same as
// the prefix, then no regex is needed.
if ($logKeyPrefix !== $regex) {
// Apply a regex filter iterator to remove files that don't
// match the provided options.
$objectsIterator = new \CallbackFilterIterator(
$objectsIterator,
function ($object) use ($regex) {
return preg_match("#{$regex}#", $object['Key']);
}
);
}
}
return $objectsIterator;
} | php | private function applyRegexFilter(
$objectsIterator,
$logKeyPrefix,
$candidatePrefix
) {
// If the prefix and candidate prefix are not the same, then there were
// WILDCARDs.
if ($logKeyPrefix !== $candidatePrefix) {
// Turn the candidate prefix into a regex by trimming and
// converting WILDCARDs to regex notation.
$regex = rtrim($candidatePrefix, '/' . self::PREFIX_WILDCARD) . '/';
$regex = strtr($regex, [self::PREFIX_WILDCARD => '[^/]+']);
// After trimming WILDCARDs or the end, if the regex is the same as
// the prefix, then no regex is needed.
if ($logKeyPrefix !== $regex) {
// Apply a regex filter iterator to remove files that don't
// match the provided options.
$objectsIterator = new \CallbackFilterIterator(
$objectsIterator,
function ($object) use ($regex) {
return preg_match("#{$regex}#", $object['Key']);
}
);
}
}
return $objectsIterator;
} | [
"private",
"function",
"applyRegexFilter",
"(",
"$",
"objectsIterator",
",",
"$",
"logKeyPrefix",
",",
"$",
"candidatePrefix",
")",
"{",
"// If the prefix and candidate prefix are not the same, then there were",
"// WILDCARDs.",
"if",
"(",
"$",
"logKeyPrefix",
"!==",
"$",
"candidatePrefix",
")",
"{",
"// Turn the candidate prefix into a regex by trimming and",
"// converting WILDCARDs to regex notation.",
"$",
"regex",
"=",
"rtrim",
"(",
"$",
"candidatePrefix",
",",
"'/'",
".",
"self",
"::",
"PREFIX_WILDCARD",
")",
".",
"'/'",
";",
"$",
"regex",
"=",
"strtr",
"(",
"$",
"regex",
",",
"[",
"self",
"::",
"PREFIX_WILDCARD",
"=>",
"'[^/]+'",
"]",
")",
";",
"// After trimming WILDCARDs or the end, if the regex is the same as",
"// the prefix, then no regex is needed.",
"if",
"(",
"$",
"logKeyPrefix",
"!==",
"$",
"regex",
")",
"{",
"// Apply a regex filter iterator to remove files that don't",
"// match the provided options.",
"$",
"objectsIterator",
"=",
"new",
"\\",
"CallbackFilterIterator",
"(",
"$",
"objectsIterator",
",",
"function",
"(",
"$",
"object",
")",
"use",
"(",
"$",
"regex",
")",
"{",
"return",
"preg_match",
"(",
"\"#{$regex}#\"",
",",
"$",
"object",
"[",
"'Key'",
"]",
")",
";",
"}",
")",
";",
"}",
"}",
"return",
"$",
"objectsIterator",
";",
"}"
] | Applies a regex iterator filter that limits the ListObjects result set
based on the provided options.
@param \Iterator $objectsIterator
@param string $logKeyPrefix
@param string $candidatePrefix
@return \Iterator | [
"Applies",
"a",
"regex",
"iterator",
"filter",
"that",
"limits",
"the",
"ListObjects",
"result",
"set",
"based",
"on",
"the",
"provided",
"options",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudTrail/LogFileIterator.php#L265-L293 | train |
aws/aws-sdk-php | src/CloudTrail/LogFileIterator.php | LogFileIterator.applyDateFilter | private function applyDateFilter($objectsIterator, $startDate, $endDate)
{
// If either a start or end date was provided, filter out dates that
// don't match the date range.
if ($startDate || $endDate) {
$fn = function ($object) use ($startDate, $endDate) {
if (!preg_match('/[0-9]{8}T[0-9]{4}Z/', $object['Key'], $m)) {
return false;
}
$date = strtotime($m[0]);
return (!$startDate || $date >= $startDate)
&& (!$endDate || $date <= $endDate);
};
$objectsIterator = new \CallbackFilterIterator($objectsIterator, $fn);
}
return $objectsIterator;
} | php | private function applyDateFilter($objectsIterator, $startDate, $endDate)
{
// If either a start or end date was provided, filter out dates that
// don't match the date range.
if ($startDate || $endDate) {
$fn = function ($object) use ($startDate, $endDate) {
if (!preg_match('/[0-9]{8}T[0-9]{4}Z/', $object['Key'], $m)) {
return false;
}
$date = strtotime($m[0]);
return (!$startDate || $date >= $startDate)
&& (!$endDate || $date <= $endDate);
};
$objectsIterator = new \CallbackFilterIterator($objectsIterator, $fn);
}
return $objectsIterator;
} | [
"private",
"function",
"applyDateFilter",
"(",
"$",
"objectsIterator",
",",
"$",
"startDate",
",",
"$",
"endDate",
")",
"{",
"// If either a start or end date was provided, filter out dates that",
"// don't match the date range.",
"if",
"(",
"$",
"startDate",
"||",
"$",
"endDate",
")",
"{",
"$",
"fn",
"=",
"function",
"(",
"$",
"object",
")",
"use",
"(",
"$",
"startDate",
",",
"$",
"endDate",
")",
"{",
"if",
"(",
"!",
"preg_match",
"(",
"'/[0-9]{8}T[0-9]{4}Z/'",
",",
"$",
"object",
"[",
"'Key'",
"]",
",",
"$",
"m",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"date",
"=",
"strtotime",
"(",
"$",
"m",
"[",
"0",
"]",
")",
";",
"return",
"(",
"!",
"$",
"startDate",
"||",
"$",
"date",
">=",
"$",
"startDate",
")",
"&&",
"(",
"!",
"$",
"endDate",
"||",
"$",
"date",
"<=",
"$",
"endDate",
")",
";",
"}",
";",
"$",
"objectsIterator",
"=",
"new",
"\\",
"CallbackFilterIterator",
"(",
"$",
"objectsIterator",
",",
"$",
"fn",
")",
";",
"}",
"return",
"$",
"objectsIterator",
";",
"}"
] | Applies an iterator filter to restrict the ListObjects result set to the
specified date range.
@param \Iterator $objectsIterator
@param int $startDate
@param int $endDate
@return \Iterator | [
"Applies",
"an",
"iterator",
"filter",
"to",
"restrict",
"the",
"ListObjects",
"result",
"set",
"to",
"the",
"specified",
"date",
"range",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudTrail/LogFileIterator.php#L305-L323 | train |
aws/aws-sdk-php | src/Api/ApiProvider.php | ApiProvider.getVersions | public function getVersions($service)
{
if (!isset($this->manifest)) {
$this->buildVersionsList($service);
}
if (!isset($this->manifest[$service]['versions'])) {
return [];
}
return array_values(array_unique($this->manifest[$service]['versions']));
} | php | public function getVersions($service)
{
if (!isset($this->manifest)) {
$this->buildVersionsList($service);
}
if (!isset($this->manifest[$service]['versions'])) {
return [];
}
return array_values(array_unique($this->manifest[$service]['versions']));
} | [
"public",
"function",
"getVersions",
"(",
"$",
"service",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"manifest",
")",
")",
"{",
"$",
"this",
"->",
"buildVersionsList",
"(",
"$",
"service",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"manifest",
"[",
"$",
"service",
"]",
"[",
"'versions'",
"]",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"return",
"array_values",
"(",
"array_unique",
"(",
"$",
"this",
"->",
"manifest",
"[",
"$",
"service",
"]",
"[",
"'versions'",
"]",
")",
")",
";",
"}"
] | Retrieves a list of valid versions for the specified service.
@param string $service Service name
@return array | [
"Retrieves",
"a",
"list",
"of",
"valid",
"versions",
"for",
"the",
"specified",
"service",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/ApiProvider.php#L154-L165 | train |
aws/aws-sdk-php | src/Api/ApiProvider.php | ApiProvider.buildVersionsList | private function buildVersionsList($service)
{
$dir = "{$this->modelsDir}/{$service}/";
if (!is_dir($dir)) {
return;
}
// Get versions, remove . and .., and sort in descending order.
$results = array_diff(scandir($dir, SCANDIR_SORT_DESCENDING), ['..', '.']);
if (!$results) {
$this->manifest[$service] = ['versions' => []];
} else {
$this->manifest[$service] = [
'versions' => [
'latest' => $results[0]
]
];
$this->manifest[$service]['versions'] += array_combine($results, $results);
}
} | php | private function buildVersionsList($service)
{
$dir = "{$this->modelsDir}/{$service}/";
if (!is_dir($dir)) {
return;
}
// Get versions, remove . and .., and sort in descending order.
$results = array_diff(scandir($dir, SCANDIR_SORT_DESCENDING), ['..', '.']);
if (!$results) {
$this->manifest[$service] = ['versions' => []];
} else {
$this->manifest[$service] = [
'versions' => [
'latest' => $results[0]
]
];
$this->manifest[$service]['versions'] += array_combine($results, $results);
}
} | [
"private",
"function",
"buildVersionsList",
"(",
"$",
"service",
")",
"{",
"$",
"dir",
"=",
"\"{$this->modelsDir}/{$service}/\"",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"return",
";",
"}",
"// Get versions, remove . and .., and sort in descending order.",
"$",
"results",
"=",
"array_diff",
"(",
"scandir",
"(",
"$",
"dir",
",",
"SCANDIR_SORT_DESCENDING",
")",
",",
"[",
"'..'",
",",
"'.'",
"]",
")",
";",
"if",
"(",
"!",
"$",
"results",
")",
"{",
"$",
"this",
"->",
"manifest",
"[",
"$",
"service",
"]",
"=",
"[",
"'versions'",
"=>",
"[",
"]",
"]",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"manifest",
"[",
"$",
"service",
"]",
"=",
"[",
"'versions'",
"=>",
"[",
"'latest'",
"=>",
"$",
"results",
"[",
"0",
"]",
"]",
"]",
";",
"$",
"this",
"->",
"manifest",
"[",
"$",
"service",
"]",
"[",
"'versions'",
"]",
"+=",
"array_combine",
"(",
"$",
"results",
",",
"$",
"results",
")",
";",
"}",
"}"
] | Build the versions list for the specified service by globbing the dir. | [
"Build",
"the",
"versions",
"list",
"for",
"the",
"specified",
"service",
"by",
"globbing",
"the",
"dir",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/ApiProvider.php#L222-L243 | train |
aws/aws-sdk-php | src/Sqs/SqsClient.php | SqsClient.calculateMessageAttributesMd5 | private static function calculateMessageAttributesMd5($message)
{
if (empty($message['MessageAttributes'])
|| !is_array($message['MessageAttributes'])
) {
return null;
}
ksort($message['MessageAttributes']);
$attributeValues = "";
foreach ($message['MessageAttributes'] as $name => $details) {
$attributeValues .= self::getEncodedStringPiece($name);
$attributeValues .= self::getEncodedStringPiece($details['DataType']);
if (substr($details['DataType'], 0, 6) === 'Binary') {
$attributeValues .= pack('c', 0x02);
$attributeValues .= self::getEncodedBinaryPiece(
$details['BinaryValue']
);
} else {
$attributeValues .= pack('c', 0x01);
$attributeValues .= self::getEncodedStringPiece(
$details['StringValue']
);
}
}
return md5($attributeValues);
} | php | private static function calculateMessageAttributesMd5($message)
{
if (empty($message['MessageAttributes'])
|| !is_array($message['MessageAttributes'])
) {
return null;
}
ksort($message['MessageAttributes']);
$attributeValues = "";
foreach ($message['MessageAttributes'] as $name => $details) {
$attributeValues .= self::getEncodedStringPiece($name);
$attributeValues .= self::getEncodedStringPiece($details['DataType']);
if (substr($details['DataType'], 0, 6) === 'Binary') {
$attributeValues .= pack('c', 0x02);
$attributeValues .= self::getEncodedBinaryPiece(
$details['BinaryValue']
);
} else {
$attributeValues .= pack('c', 0x01);
$attributeValues .= self::getEncodedStringPiece(
$details['StringValue']
);
}
}
return md5($attributeValues);
} | [
"private",
"static",
"function",
"calculateMessageAttributesMd5",
"(",
"$",
"message",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"message",
"[",
"'MessageAttributes'",
"]",
")",
"||",
"!",
"is_array",
"(",
"$",
"message",
"[",
"'MessageAttributes'",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"ksort",
"(",
"$",
"message",
"[",
"'MessageAttributes'",
"]",
")",
";",
"$",
"attributeValues",
"=",
"\"\"",
";",
"foreach",
"(",
"$",
"message",
"[",
"'MessageAttributes'",
"]",
"as",
"$",
"name",
"=>",
"$",
"details",
")",
"{",
"$",
"attributeValues",
".=",
"self",
"::",
"getEncodedStringPiece",
"(",
"$",
"name",
")",
";",
"$",
"attributeValues",
".=",
"self",
"::",
"getEncodedStringPiece",
"(",
"$",
"details",
"[",
"'DataType'",
"]",
")",
";",
"if",
"(",
"substr",
"(",
"$",
"details",
"[",
"'DataType'",
"]",
",",
"0",
",",
"6",
")",
"===",
"'Binary'",
")",
"{",
"$",
"attributeValues",
".=",
"pack",
"(",
"'c'",
",",
"0x02",
")",
";",
"$",
"attributeValues",
".=",
"self",
"::",
"getEncodedBinaryPiece",
"(",
"$",
"details",
"[",
"'BinaryValue'",
"]",
")",
";",
"}",
"else",
"{",
"$",
"attributeValues",
".=",
"pack",
"(",
"'c'",
",",
"0x01",
")",
";",
"$",
"attributeValues",
".=",
"self",
"::",
"getEncodedStringPiece",
"(",
"$",
"details",
"[",
"'StringValue'",
"]",
")",
";",
"}",
"}",
"return",
"md5",
"(",
"$",
"attributeValues",
")",
";",
"}"
] | Calculates the expected md5 hash of message attributes according to the encoding
scheme detailed in SQS documentation.
@param array $message Message containing attributes for validation.
Retrieved when using MessageAttributeNames on
ReceiveMessage.
@return string|null The md5 hash of the message attributes according to
the encoding scheme. Returns null when there are no
attributes.
@link http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-attributes.html#message-attributes-items-validation | [
"Calculates",
"the",
"expected",
"md5",
"hash",
"of",
"message",
"attributes",
"according",
"to",
"the",
"encoding",
"scheme",
"detailed",
"in",
"SQS",
"documentation",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Sqs/SqsClient.php#L126-L153 | train |
aws/aws-sdk-php | src/Sqs/SqsClient.php | SqsClient.validateMd5 | private function validateMd5()
{
return static function (callable $handler) {
return function (
CommandInterface $c,
RequestInterface $r = null
) use ($handler) {
if ($c->getName() !== 'ReceiveMessage') {
return $handler($c, $r);
}
return $handler($c, $r)
->then(
function ($result) use ($c, $r) {
foreach ((array) $result['Messages'] as $msg) {
$bodyMd5 = self::calculateBodyMd5($msg);
if (isset($msg['MD5OfBody'])
&& $bodyMd5 !== $msg['MD5OfBody']
) {
throw new SqsException(
sprintf(
'MD5 mismatch. Expected %s, found %s',
$msg['MD5OfBody'],
$bodyMd5
),
$c,
[
'code' => 'ClientChecksumMismatch',
'request' => $r
]
);
}
if (isset($msg['MD5OfMessageAttributes'])) {
$messageAttributesMd5 = self::calculateMessageAttributesMd5($msg);
if ($messageAttributesMd5 !== $msg['MD5OfMessageAttributes']) {
throw new SqsException(
sprintf(
'Attribute MD5 mismatch. Expected %s, found %s',
$msg['MD5OfMessageAttributes'],
$messageAttributesMd5
? $messageAttributesMd5
: 'No Attributes'
),
$c,
[
'code' => 'ClientChecksumMismatch',
'request' => $r
]
);
}
} else if (isset($msg['MessageAttributes'])) {
throw new SqsException(
sprintf(
'No Attribute MD5 found. Expected %s',
self::calculateMessageAttributesMd5($msg)
),
$c,
[
'code' => 'ClientChecksumMismatch',
'request' => $r
]
);
}
}
return $result;
}
);
};
};
} | php | private function validateMd5()
{
return static function (callable $handler) {
return function (
CommandInterface $c,
RequestInterface $r = null
) use ($handler) {
if ($c->getName() !== 'ReceiveMessage') {
return $handler($c, $r);
}
return $handler($c, $r)
->then(
function ($result) use ($c, $r) {
foreach ((array) $result['Messages'] as $msg) {
$bodyMd5 = self::calculateBodyMd5($msg);
if (isset($msg['MD5OfBody'])
&& $bodyMd5 !== $msg['MD5OfBody']
) {
throw new SqsException(
sprintf(
'MD5 mismatch. Expected %s, found %s',
$msg['MD5OfBody'],
$bodyMd5
),
$c,
[
'code' => 'ClientChecksumMismatch',
'request' => $r
]
);
}
if (isset($msg['MD5OfMessageAttributes'])) {
$messageAttributesMd5 = self::calculateMessageAttributesMd5($msg);
if ($messageAttributesMd5 !== $msg['MD5OfMessageAttributes']) {
throw new SqsException(
sprintf(
'Attribute MD5 mismatch. Expected %s, found %s',
$msg['MD5OfMessageAttributes'],
$messageAttributesMd5
? $messageAttributesMd5
: 'No Attributes'
),
$c,
[
'code' => 'ClientChecksumMismatch',
'request' => $r
]
);
}
} else if (isset($msg['MessageAttributes'])) {
throw new SqsException(
sprintf(
'No Attribute MD5 found. Expected %s',
self::calculateMessageAttributesMd5($msg)
),
$c,
[
'code' => 'ClientChecksumMismatch',
'request' => $r
]
);
}
}
return $result;
}
);
};
};
} | [
"private",
"function",
"validateMd5",
"(",
")",
"{",
"return",
"static",
"function",
"(",
"callable",
"$",
"handler",
")",
"{",
"return",
"function",
"(",
"CommandInterface",
"$",
"c",
",",
"RequestInterface",
"$",
"r",
"=",
"null",
")",
"use",
"(",
"$",
"handler",
")",
"{",
"if",
"(",
"$",
"c",
"->",
"getName",
"(",
")",
"!==",
"'ReceiveMessage'",
")",
"{",
"return",
"$",
"handler",
"(",
"$",
"c",
",",
"$",
"r",
")",
";",
"}",
"return",
"$",
"handler",
"(",
"$",
"c",
",",
"$",
"r",
")",
"->",
"then",
"(",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"$",
"c",
",",
"$",
"r",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"result",
"[",
"'Messages'",
"]",
"as",
"$",
"msg",
")",
"{",
"$",
"bodyMd5",
"=",
"self",
"::",
"calculateBodyMd5",
"(",
"$",
"msg",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"msg",
"[",
"'MD5OfBody'",
"]",
")",
"&&",
"$",
"bodyMd5",
"!==",
"$",
"msg",
"[",
"'MD5OfBody'",
"]",
")",
"{",
"throw",
"new",
"SqsException",
"(",
"sprintf",
"(",
"'MD5 mismatch. Expected %s, found %s'",
",",
"$",
"msg",
"[",
"'MD5OfBody'",
"]",
",",
"$",
"bodyMd5",
")",
",",
"$",
"c",
",",
"[",
"'code'",
"=>",
"'ClientChecksumMismatch'",
",",
"'request'",
"=>",
"$",
"r",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"msg",
"[",
"'MD5OfMessageAttributes'",
"]",
")",
")",
"{",
"$",
"messageAttributesMd5",
"=",
"self",
"::",
"calculateMessageAttributesMd5",
"(",
"$",
"msg",
")",
";",
"if",
"(",
"$",
"messageAttributesMd5",
"!==",
"$",
"msg",
"[",
"'MD5OfMessageAttributes'",
"]",
")",
"{",
"throw",
"new",
"SqsException",
"(",
"sprintf",
"(",
"'Attribute MD5 mismatch. Expected %s, found %s'",
",",
"$",
"msg",
"[",
"'MD5OfMessageAttributes'",
"]",
",",
"$",
"messageAttributesMd5",
"?",
"$",
"messageAttributesMd5",
":",
"'No Attributes'",
")",
",",
"$",
"c",
",",
"[",
"'code'",
"=>",
"'ClientChecksumMismatch'",
",",
"'request'",
"=>",
"$",
"r",
"]",
")",
";",
"}",
"}",
"else",
"if",
"(",
"isset",
"(",
"$",
"msg",
"[",
"'MessageAttributes'",
"]",
")",
")",
"{",
"throw",
"new",
"SqsException",
"(",
"sprintf",
"(",
"'No Attribute MD5 found. Expected %s'",
",",
"self",
"::",
"calculateMessageAttributesMd5",
"(",
"$",
"msg",
")",
")",
",",
"$",
"c",
",",
"[",
"'code'",
"=>",
"'ClientChecksumMismatch'",
",",
"'request'",
"=>",
"$",
"r",
"]",
")",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}",
")",
";",
"}",
";",
"}",
";",
"}"
] | Validates ReceiveMessage body and message attribute MD5s.
@return callable | [
"Validates",
"ReceiveMessage",
"body",
"and",
"message",
"attribute",
"MD5s",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Sqs/SqsClient.php#L185-L255 | train |
aws/aws-sdk-php | src/Crypto/DecryptionTrait.php | DecryptionTrait.decrypt | protected function decrypt(
$cipherText,
MaterialsProvider $provider,
MetadataEnvelope $envelope,
array $cipherOptions = []
) {
$cipherOptions['Iv'] = base64_decode(
$envelope[MetadataEnvelope::IV_HEADER]
);
$cipherOptions['TagLength'] =
$envelope[MetadataEnvelope::CRYPTO_TAG_LENGTH_HEADER] / 8;
$cek = $provider->decryptCek(
base64_decode(
$envelope[MetadataEnvelope::CONTENT_KEY_V2_HEADER]
),
json_decode(
$envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER],
true
)
);
$cipherOptions['KeySize'] = strlen($cek) * 8;
$cipherOptions['Cipher'] = $this->getCipherFromAesName(
$envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER]
);
$decryptionSteam = $this->getDecryptingStream(
$cipherText,
$cek,
$cipherOptions
);
unset($cek);
return $decryptionSteam;
} | php | protected function decrypt(
$cipherText,
MaterialsProvider $provider,
MetadataEnvelope $envelope,
array $cipherOptions = []
) {
$cipherOptions['Iv'] = base64_decode(
$envelope[MetadataEnvelope::IV_HEADER]
);
$cipherOptions['TagLength'] =
$envelope[MetadataEnvelope::CRYPTO_TAG_LENGTH_HEADER] / 8;
$cek = $provider->decryptCek(
base64_decode(
$envelope[MetadataEnvelope::CONTENT_KEY_V2_HEADER]
),
json_decode(
$envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER],
true
)
);
$cipherOptions['KeySize'] = strlen($cek) * 8;
$cipherOptions['Cipher'] = $this->getCipherFromAesName(
$envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER]
);
$decryptionSteam = $this->getDecryptingStream(
$cipherText,
$cek,
$cipherOptions
);
unset($cek);
return $decryptionSteam;
} | [
"protected",
"function",
"decrypt",
"(",
"$",
"cipherText",
",",
"MaterialsProvider",
"$",
"provider",
",",
"MetadataEnvelope",
"$",
"envelope",
",",
"array",
"$",
"cipherOptions",
"=",
"[",
"]",
")",
"{",
"$",
"cipherOptions",
"[",
"'Iv'",
"]",
"=",
"base64_decode",
"(",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"IV_HEADER",
"]",
")",
";",
"$",
"cipherOptions",
"[",
"'TagLength'",
"]",
"=",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"CRYPTO_TAG_LENGTH_HEADER",
"]",
"/",
"8",
";",
"$",
"cek",
"=",
"$",
"provider",
"->",
"decryptCek",
"(",
"base64_decode",
"(",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"CONTENT_KEY_V2_HEADER",
"]",
")",
",",
"json_decode",
"(",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"MATERIALS_DESCRIPTION_HEADER",
"]",
",",
"true",
")",
")",
";",
"$",
"cipherOptions",
"[",
"'KeySize'",
"]",
"=",
"strlen",
"(",
"$",
"cek",
")",
"*",
"8",
";",
"$",
"cipherOptions",
"[",
"'Cipher'",
"]",
"=",
"$",
"this",
"->",
"getCipherFromAesName",
"(",
"$",
"envelope",
"[",
"MetadataEnvelope",
"::",
"CONTENT_CRYPTO_SCHEME_HEADER",
"]",
")",
";",
"$",
"decryptionSteam",
"=",
"$",
"this",
"->",
"getDecryptingStream",
"(",
"$",
"cipherText",
",",
"$",
"cek",
",",
"$",
"cipherOptions",
")",
";",
"unset",
"(",
"$",
"cek",
")",
";",
"return",
"$",
"decryptionSteam",
";",
"}"
] | Builds an AesStreamInterface using cipher options loaded from the
MetadataEnvelope and MaterialsProvider.
@param string $cipherText Plain-text data to be encrypted using the
materials, algorithm, and data provided.
@param MaterialsProvider $provider A provider to supply and encrypt
materials used in encryption.
@param MetadataEnvelope $envelope A storage envelope for encryption
metadata to be read from.
@param array $cipherOptions Additional verification options.
@return AesStreamInterface
@throws \InvalidArgumentException Thrown when a value in $cipherOptions
is not valid.
@internal | [
"Builds",
"an",
"AesStreamInterface",
"using",
"cipher",
"options",
"loaded",
"from",
"the",
"MetadataEnvelope",
"and",
"MaterialsProvider",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Crypto/DecryptionTrait.php#L55-L90 | train |
aws/aws-sdk-php | src/DynamoDb/Marshaler.php | Marshaler.marshalJson | public function marshalJson($json)
{
$data = json_decode($json);
if (!($data instanceof \stdClass)) {
throw new \InvalidArgumentException(
'The JSON document must be valid and be an object at its root.'
);
}
return current($this->marshalValue($data));
} | php | public function marshalJson($json)
{
$data = json_decode($json);
if (!($data instanceof \stdClass)) {
throw new \InvalidArgumentException(
'The JSON document must be valid and be an object at its root.'
);
}
return current($this->marshalValue($data));
} | [
"public",
"function",
"marshalJson",
"(",
"$",
"json",
")",
"{",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"json",
")",
";",
"if",
"(",
"!",
"(",
"$",
"data",
"instanceof",
"\\",
"stdClass",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'The JSON document must be valid and be an object at its root.'",
")",
";",
"}",
"return",
"current",
"(",
"$",
"this",
"->",
"marshalValue",
"(",
"$",
"data",
")",
")",
";",
"}"
] | Marshal a JSON document from a string to a DynamoDB item.
The result is an array formatted in the proper parameter structure
required by the DynamoDB API for items.
@param string $json A valid JSON document.
@return array Item formatted for DynamoDB.
@throws \InvalidArgumentException if the JSON is invalid. | [
"Marshal",
"a",
"JSON",
"document",
"from",
"a",
"string",
"to",
"a",
"DynamoDB",
"item",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/Marshaler.php#L95-L105 | train |
aws/aws-sdk-php | src/DynamoDb/Marshaler.php | Marshaler.marshalValue | public function marshalValue($value)
{
$type = gettype($value);
// Handle string values.
if ($type === 'string') {
if ($value === '') {
return $this->handleInvalid('empty strings are invalid');
}
return ['S' => $value];
}
// Handle number values.
if ($type === 'integer'
|| $type === 'double'
|| $value instanceof NumberValue
) {
return ['N' => (string) $value];
}
// Handle boolean values.
if ($type === 'boolean') {
return ['BOOL' => $value];
}
// Handle null values.
if ($type === 'NULL') {
return ['NULL' => true];
}
// Handle set values.
if ($value instanceof SetValue) {
if (count($value) === 0) {
return $this->handleInvalid('empty sets are invalid');
}
$previousType = null;
$data = [];
foreach ($value as $v) {
$marshaled = $this->marshalValue($v);
$setType = key($marshaled);
if (!$previousType) {
$previousType = $setType;
} elseif ($setType !== $previousType) {
return $this->handleInvalid('sets must be uniform in type');
}
$data[] = current($marshaled);
}
return [$previousType . 'S' => array_values(array_unique($data))];
}
// Handle list and map values.
$dbType = 'L';
if ($value instanceof \stdClass) {
$type = 'array';
$dbType = 'M';
}
if ($type === 'array' || $value instanceof \Traversable) {
$data = [];
$index = 0;
foreach ($value as $k => $v) {
if ($v = $this->marshalValue($v)) {
$data[$k] = $v;
if ($dbType === 'L' && (!is_int($k) || $k != $index++)) {
$dbType = 'M';
}
}
}
return [$dbType => $data];
}
// Handle binary values.
if (is_resource($value) || $value instanceof StreamInterface) {
$value = $this->binary($value);
}
if ($value instanceof BinaryValue) {
return ['B' => (string) $value];
}
// Handle invalid values.
return $this->handleInvalid('encountered unexpected value');
} | php | public function marshalValue($value)
{
$type = gettype($value);
// Handle string values.
if ($type === 'string') {
if ($value === '') {
return $this->handleInvalid('empty strings are invalid');
}
return ['S' => $value];
}
// Handle number values.
if ($type === 'integer'
|| $type === 'double'
|| $value instanceof NumberValue
) {
return ['N' => (string) $value];
}
// Handle boolean values.
if ($type === 'boolean') {
return ['BOOL' => $value];
}
// Handle null values.
if ($type === 'NULL') {
return ['NULL' => true];
}
// Handle set values.
if ($value instanceof SetValue) {
if (count($value) === 0) {
return $this->handleInvalid('empty sets are invalid');
}
$previousType = null;
$data = [];
foreach ($value as $v) {
$marshaled = $this->marshalValue($v);
$setType = key($marshaled);
if (!$previousType) {
$previousType = $setType;
} elseif ($setType !== $previousType) {
return $this->handleInvalid('sets must be uniform in type');
}
$data[] = current($marshaled);
}
return [$previousType . 'S' => array_values(array_unique($data))];
}
// Handle list and map values.
$dbType = 'L';
if ($value instanceof \stdClass) {
$type = 'array';
$dbType = 'M';
}
if ($type === 'array' || $value instanceof \Traversable) {
$data = [];
$index = 0;
foreach ($value as $k => $v) {
if ($v = $this->marshalValue($v)) {
$data[$k] = $v;
if ($dbType === 'L' && (!is_int($k) || $k != $index++)) {
$dbType = 'M';
}
}
}
return [$dbType => $data];
}
// Handle binary values.
if (is_resource($value) || $value instanceof StreamInterface) {
$value = $this->binary($value);
}
if ($value instanceof BinaryValue) {
return ['B' => (string) $value];
}
// Handle invalid values.
return $this->handleInvalid('encountered unexpected value');
} | [
"public",
"function",
"marshalValue",
"(",
"$",
"value",
")",
"{",
"$",
"type",
"=",
"gettype",
"(",
"$",
"value",
")",
";",
"// Handle string values.",
"if",
"(",
"$",
"type",
"===",
"'string'",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"''",
")",
"{",
"return",
"$",
"this",
"->",
"handleInvalid",
"(",
"'empty strings are invalid'",
")",
";",
"}",
"return",
"[",
"'S'",
"=>",
"$",
"value",
"]",
";",
"}",
"// Handle number values.",
"if",
"(",
"$",
"type",
"===",
"'integer'",
"||",
"$",
"type",
"===",
"'double'",
"||",
"$",
"value",
"instanceof",
"NumberValue",
")",
"{",
"return",
"[",
"'N'",
"=>",
"(",
"string",
")",
"$",
"value",
"]",
";",
"}",
"// Handle boolean values.",
"if",
"(",
"$",
"type",
"===",
"'boolean'",
")",
"{",
"return",
"[",
"'BOOL'",
"=>",
"$",
"value",
"]",
";",
"}",
"// Handle null values.",
"if",
"(",
"$",
"type",
"===",
"'NULL'",
")",
"{",
"return",
"[",
"'NULL'",
"=>",
"true",
"]",
";",
"}",
"// Handle set values.",
"if",
"(",
"$",
"value",
"instanceof",
"SetValue",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"value",
")",
"===",
"0",
")",
"{",
"return",
"$",
"this",
"->",
"handleInvalid",
"(",
"'empty sets are invalid'",
")",
";",
"}",
"$",
"previousType",
"=",
"null",
";",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"value",
"as",
"$",
"v",
")",
"{",
"$",
"marshaled",
"=",
"$",
"this",
"->",
"marshalValue",
"(",
"$",
"v",
")",
";",
"$",
"setType",
"=",
"key",
"(",
"$",
"marshaled",
")",
";",
"if",
"(",
"!",
"$",
"previousType",
")",
"{",
"$",
"previousType",
"=",
"$",
"setType",
";",
"}",
"elseif",
"(",
"$",
"setType",
"!==",
"$",
"previousType",
")",
"{",
"return",
"$",
"this",
"->",
"handleInvalid",
"(",
"'sets must be uniform in type'",
")",
";",
"}",
"$",
"data",
"[",
"]",
"=",
"current",
"(",
"$",
"marshaled",
")",
";",
"}",
"return",
"[",
"$",
"previousType",
".",
"'S'",
"=>",
"array_values",
"(",
"array_unique",
"(",
"$",
"data",
")",
")",
"]",
";",
"}",
"// Handle list and map values.",
"$",
"dbType",
"=",
"'L'",
";",
"if",
"(",
"$",
"value",
"instanceof",
"\\",
"stdClass",
")",
"{",
"$",
"type",
"=",
"'array'",
";",
"$",
"dbType",
"=",
"'M'",
";",
"}",
"if",
"(",
"$",
"type",
"===",
"'array'",
"||",
"$",
"value",
"instanceof",
"\\",
"Traversable",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"index",
"=",
"0",
";",
"foreach",
"(",
"$",
"value",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"$",
"v",
"=",
"$",
"this",
"->",
"marshalValue",
"(",
"$",
"v",
")",
")",
"{",
"$",
"data",
"[",
"$",
"k",
"]",
"=",
"$",
"v",
";",
"if",
"(",
"$",
"dbType",
"===",
"'L'",
"&&",
"(",
"!",
"is_int",
"(",
"$",
"k",
")",
"||",
"$",
"k",
"!=",
"$",
"index",
"++",
")",
")",
"{",
"$",
"dbType",
"=",
"'M'",
";",
"}",
"}",
"}",
"return",
"[",
"$",
"dbType",
"=>",
"$",
"data",
"]",
";",
"}",
"// Handle binary values.",
"if",
"(",
"is_resource",
"(",
"$",
"value",
")",
"||",
"$",
"value",
"instanceof",
"StreamInterface",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"binary",
"(",
"$",
"value",
")",
";",
"}",
"if",
"(",
"$",
"value",
"instanceof",
"BinaryValue",
")",
"{",
"return",
"[",
"'B'",
"=>",
"(",
"string",
")",
"$",
"value",
"]",
";",
"}",
"// Handle invalid values.",
"return",
"$",
"this",
"->",
"handleInvalid",
"(",
"'encountered unexpected value'",
")",
";",
"}"
] | Marshal a native PHP value into a DynamoDB attribute value.
The result is an associative array that is formatted in the proper
`[TYPE => VALUE]` parameter structure required by the DynamoDB API.
@param mixed $value A scalar, array, or `stdClass` value.
@return array Attribute formatted for DynamoDB.
@throws \UnexpectedValueException if the value cannot be marshaled. | [
"Marshal",
"a",
"native",
"PHP",
"value",
"into",
"a",
"DynamoDB",
"attribute",
"value",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/Marshaler.php#L133-L215 | train |
aws/aws-sdk-php | src/S3/BatchDelete.php | BatchDelete.fromListObjects | public static function fromListObjects(
AwsClientInterface $client,
array $listObjectsParams,
array $options = []
) {
$iter = $client->getPaginator('ListObjects', $listObjectsParams);
$bucket = $listObjectsParams['Bucket'];
$fn = function (BatchDelete $that) use ($iter) {
return $iter->each(function ($result) use ($that) {
$promises = [];
if (is_array($result['Contents'])) {
foreach ($result['Contents'] as $object) {
if ($promise = $that->enqueue($object)) {
$promises[] = $promise;
}
}
}
return $promises ? Promise\all($promises) : null;
});
};
return new self($client, $bucket, $fn, $options);
} | php | public static function fromListObjects(
AwsClientInterface $client,
array $listObjectsParams,
array $options = []
) {
$iter = $client->getPaginator('ListObjects', $listObjectsParams);
$bucket = $listObjectsParams['Bucket'];
$fn = function (BatchDelete $that) use ($iter) {
return $iter->each(function ($result) use ($that) {
$promises = [];
if (is_array($result['Contents'])) {
foreach ($result['Contents'] as $object) {
if ($promise = $that->enqueue($object)) {
$promises[] = $promise;
}
}
}
return $promises ? Promise\all($promises) : null;
});
};
return new self($client, $bucket, $fn, $options);
} | [
"public",
"static",
"function",
"fromListObjects",
"(",
"AwsClientInterface",
"$",
"client",
",",
"array",
"$",
"listObjectsParams",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"iter",
"=",
"$",
"client",
"->",
"getPaginator",
"(",
"'ListObjects'",
",",
"$",
"listObjectsParams",
")",
";",
"$",
"bucket",
"=",
"$",
"listObjectsParams",
"[",
"'Bucket'",
"]",
";",
"$",
"fn",
"=",
"function",
"(",
"BatchDelete",
"$",
"that",
")",
"use",
"(",
"$",
"iter",
")",
"{",
"return",
"$",
"iter",
"->",
"each",
"(",
"function",
"(",
"$",
"result",
")",
"use",
"(",
"$",
"that",
")",
"{",
"$",
"promises",
"=",
"[",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"result",
"[",
"'Contents'",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"result",
"[",
"'Contents'",
"]",
"as",
"$",
"object",
")",
"{",
"if",
"(",
"$",
"promise",
"=",
"$",
"that",
"->",
"enqueue",
"(",
"$",
"object",
")",
")",
"{",
"$",
"promises",
"[",
"]",
"=",
"$",
"promise",
";",
"}",
"}",
"}",
"return",
"$",
"promises",
"?",
"Promise",
"\\",
"all",
"(",
"$",
"promises",
")",
":",
"null",
";",
"}",
")",
";",
"}",
";",
"return",
"new",
"self",
"(",
"$",
"client",
",",
"$",
"bucket",
",",
"$",
"fn",
",",
"$",
"options",
")",
";",
"}"
] | Creates a BatchDelete object from all of the paginated results of a
ListObjects operation. Each result that is returned by the ListObjects
operation will be deleted.
@param AwsClientInterface $client AWS Client to use.
@param array $listObjectsParams ListObjects API parameters
@param array $options BatchDelete options.
@return BatchDelete | [
"Creates",
"a",
"BatchDelete",
"object",
"from",
"all",
"of",
"the",
"paginated",
"results",
"of",
"a",
"ListObjects",
"operation",
".",
"Each",
"result",
"that",
"is",
"returned",
"by",
"the",
"ListObjects",
"operation",
"will",
"be",
"deleted",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/BatchDelete.php#L62-L84 | train |
aws/aws-sdk-php | src/S3/BatchDelete.php | BatchDelete.createPromise | private function createPromise()
{
// Create the promise
$promise = call_user_func($this->promiseCreator, $this);
$this->promiseCreator = null;
// Cleans up the promise state and references.
$cleanup = function () {
$this->before = $this->client = $this->queue = null;
};
// When done, ensure cleanup and that any remaining are processed.
return $promise->then(
function () use ($cleanup) {
return Promise\promise_for($this->flushQueue())
->then($cleanup);
},
function ($reason) use ($cleanup) {
$cleanup();
return Promise\rejection_for($reason);
}
);
} | php | private function createPromise()
{
// Create the promise
$promise = call_user_func($this->promiseCreator, $this);
$this->promiseCreator = null;
// Cleans up the promise state and references.
$cleanup = function () {
$this->before = $this->client = $this->queue = null;
};
// When done, ensure cleanup and that any remaining are processed.
return $promise->then(
function () use ($cleanup) {
return Promise\promise_for($this->flushQueue())
->then($cleanup);
},
function ($reason) use ($cleanup) {
$cleanup();
return Promise\rejection_for($reason);
}
);
} | [
"private",
"function",
"createPromise",
"(",
")",
"{",
"// Create the promise",
"$",
"promise",
"=",
"call_user_func",
"(",
"$",
"this",
"->",
"promiseCreator",
",",
"$",
"this",
")",
";",
"$",
"this",
"->",
"promiseCreator",
"=",
"null",
";",
"// Cleans up the promise state and references.",
"$",
"cleanup",
"=",
"function",
"(",
")",
"{",
"$",
"this",
"->",
"before",
"=",
"$",
"this",
"->",
"client",
"=",
"$",
"this",
"->",
"queue",
"=",
"null",
";",
"}",
";",
"// When done, ensure cleanup and that any remaining are processed.",
"return",
"$",
"promise",
"->",
"then",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"cleanup",
")",
"{",
"return",
"Promise",
"\\",
"promise_for",
"(",
"$",
"this",
"->",
"flushQueue",
"(",
")",
")",
"->",
"then",
"(",
"$",
"cleanup",
")",
";",
"}",
",",
"function",
"(",
"$",
"reason",
")",
"use",
"(",
"$",
"cleanup",
")",
"{",
"$",
"cleanup",
"(",
")",
";",
"return",
"Promise",
"\\",
"rejection_for",
"(",
"$",
"reason",
")",
";",
"}",
")",
";",
"}"
] | Returns a promise that will clean up any references when it completes.
@return PromiseInterface | [
"Returns",
"a",
"promise",
"that",
"will",
"clean",
"up",
"any",
"references",
"when",
"it",
"completes",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/BatchDelete.php#L214-L236 | train |
aws/aws-sdk-php | src/CloudFront/CookieSigner.php | CookieSigner.getSignedCookie | public function getSignedCookie($url = null, $expires = null, $policy = null)
{
if ($url) {
$this->validateUrl($url);
}
$cookieParameters = [];
$signature = $this->signer->getSignature($url, $expires, $policy);
foreach ($signature as $key => $value) {
$cookieParameters["CloudFront-$key"] = $value;
}
return $cookieParameters;
} | php | public function getSignedCookie($url = null, $expires = null, $policy = null)
{
if ($url) {
$this->validateUrl($url);
}
$cookieParameters = [];
$signature = $this->signer->getSignature($url, $expires, $policy);
foreach ($signature as $key => $value) {
$cookieParameters["CloudFront-$key"] = $value;
}
return $cookieParameters;
} | [
"public",
"function",
"getSignedCookie",
"(",
"$",
"url",
"=",
"null",
",",
"$",
"expires",
"=",
"null",
",",
"$",
"policy",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"url",
")",
"{",
"$",
"this",
"->",
"validateUrl",
"(",
"$",
"url",
")",
";",
"}",
"$",
"cookieParameters",
"=",
"[",
"]",
";",
"$",
"signature",
"=",
"$",
"this",
"->",
"signer",
"->",
"getSignature",
"(",
"$",
"url",
",",
"$",
"expires",
",",
"$",
"policy",
")",
";",
"foreach",
"(",
"$",
"signature",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"cookieParameters",
"[",
"\"CloudFront-$key\"",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"cookieParameters",
";",
"}"
] | Create a signed Amazon CloudFront Cookie.
@param string $url URL to sign (can include query string
and wildcards). Not required
when passing a custom $policy.
@param string|integer|null $expires UTC Unix timestamp used when signing
with a canned policy. Not required
when passing a custom $policy.
@param string $policy JSON policy. Use this option when
creating a signed cookie for a custom
policy.
@return array The authenticated cookie parameters
@throws \InvalidArgumentException if the URL provided is invalid
@link http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-cookies.html | [
"Create",
"a",
"signed",
"Amazon",
"CloudFront",
"Cookie",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CloudFront/CookieSigner.php#L43-L56 | train |
aws/aws-sdk-php | src/EndpointDiscovery/EndpointList.php | EndpointList.getExpired | private function getExpired()
{
if (count($this->expired) < 1) {
return null;
}
$expired = key($this->expired);
$this->increment($this->expired);
return $expired;
} | php | private function getExpired()
{
if (count($this->expired) < 1) {
return null;
}
$expired = key($this->expired);
$this->increment($this->expired);
return $expired;
} | [
"private",
"function",
"getExpired",
"(",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"expired",
")",
"<",
"1",
")",
"{",
"return",
"null",
";",
"}",
"$",
"expired",
"=",
"key",
"(",
"$",
"this",
"->",
"expired",
")",
";",
"$",
"this",
"->",
"increment",
"(",
"$",
"this",
"->",
"expired",
")",
";",
"return",
"$",
"expired",
";",
"}"
] | Get an expired endpoint. Returns null if none found.
@return null|string | [
"Get",
"an",
"expired",
"endpoint",
".",
"Returns",
"null",
"if",
"none",
"found",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/EndpointDiscovery/EndpointList.php#L69-L77 | train |
aws/aws-sdk-php | src/DynamoDb/WriteRequestBatch.php | WriteRequestBatch.put | public function put(array $item, $table = null)
{
$this->queue[] = [
'table' => $this->determineTable($table),
'data' => ['PutRequest' => ['Item' => $item]],
];
$this->autoFlush();
return $this;
} | php | public function put(array $item, $table = null)
{
$this->queue[] = [
'table' => $this->determineTable($table),
'data' => ['PutRequest' => ['Item' => $item]],
];
$this->autoFlush();
return $this;
} | [
"public",
"function",
"put",
"(",
"array",
"$",
"item",
",",
"$",
"table",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"queue",
"[",
"]",
"=",
"[",
"'table'",
"=>",
"$",
"this",
"->",
"determineTable",
"(",
"$",
"table",
")",
",",
"'data'",
"=>",
"[",
"'PutRequest'",
"=>",
"[",
"'Item'",
"=>",
"$",
"item",
"]",
"]",
",",
"]",
";",
"$",
"this",
"->",
"autoFlush",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Adds a put item request to the batch.
@param array $item Data for an item to put. Format:
[
'attribute1' => ['type' => 'value'],
'attribute2' => ['type' => 'value'],
...
]
@param string|null $table The name of the table. This must be specified
unless the "table" option was provided in the
config of the WriteRequestBatch.
@return $this | [
"Adds",
"a",
"put",
"item",
"request",
"to",
"the",
"batch",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/WriteRequestBatch.php#L106-L116 | train |
aws/aws-sdk-php | src/DynamoDb/WriteRequestBatch.php | WriteRequestBatch.delete | public function delete(array $key, $table = null)
{
$this->queue[] = [
'table' => $this->determineTable($table),
'data' => ['DeleteRequest' => ['Key' => $key]],
];
$this->autoFlush();
return $this;
} | php | public function delete(array $key, $table = null)
{
$this->queue[] = [
'table' => $this->determineTable($table),
'data' => ['DeleteRequest' => ['Key' => $key]],
];
$this->autoFlush();
return $this;
} | [
"public",
"function",
"delete",
"(",
"array",
"$",
"key",
",",
"$",
"table",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"queue",
"[",
"]",
"=",
"[",
"'table'",
"=>",
"$",
"this",
"->",
"determineTable",
"(",
"$",
"table",
")",
",",
"'data'",
"=>",
"[",
"'DeleteRequest'",
"=>",
"[",
"'Key'",
"=>",
"$",
"key",
"]",
"]",
",",
"]",
";",
"$",
"this",
"->",
"autoFlush",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Adds a delete item request to the batch.
@param array $key Key of an item to delete. Format:
[
'key1' => ['type' => 'value'],
...
]
@param string|null $table The name of the table. This must be specified
unless the "table" option was provided in the
config of the WriteRequestBatch.
@return $this | [
"Adds",
"a",
"delete",
"item",
"request",
"to",
"the",
"batch",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/WriteRequestBatch.php#L132-L142 | train |
aws/aws-sdk-php | src/DynamoDb/WriteRequestBatch.php | WriteRequestBatch.flush | public function flush($untilEmpty = true)
{
// Send BatchWriteItem requests until the queue is empty
$keepFlushing = true;
while ($this->queue && $keepFlushing) {
$commands = $this->prepareCommands();
$pool = new CommandPool($this->client, $commands, [
'before' => $this->config['before'],
'concurrency' => $this->config['pool_size'],
'fulfilled' => function (ResultInterface $result) {
// Re-queue any unprocessed items
if ($result->hasKey('UnprocessedItems')) {
$this->retryUnprocessed($result['UnprocessedItems']);
}
},
'rejected' => function ($reason) {
if ($reason instanceof AwsException) {
$code = $reason->getAwsErrorCode();
if ($code === 'ProvisionedThroughputExceededException') {
$this->retryUnprocessed($reason->getCommand()['RequestItems']);
} elseif (is_callable($this->config['error'])) {
$this->config['error']($reason);
}
}
}
]);
$pool->promise()->wait();
$keepFlushing = (bool) $untilEmpty;
}
return $this;
} | php | public function flush($untilEmpty = true)
{
// Send BatchWriteItem requests until the queue is empty
$keepFlushing = true;
while ($this->queue && $keepFlushing) {
$commands = $this->prepareCommands();
$pool = new CommandPool($this->client, $commands, [
'before' => $this->config['before'],
'concurrency' => $this->config['pool_size'],
'fulfilled' => function (ResultInterface $result) {
// Re-queue any unprocessed items
if ($result->hasKey('UnprocessedItems')) {
$this->retryUnprocessed($result['UnprocessedItems']);
}
},
'rejected' => function ($reason) {
if ($reason instanceof AwsException) {
$code = $reason->getAwsErrorCode();
if ($code === 'ProvisionedThroughputExceededException') {
$this->retryUnprocessed($reason->getCommand()['RequestItems']);
} elseif (is_callable($this->config['error'])) {
$this->config['error']($reason);
}
}
}
]);
$pool->promise()->wait();
$keepFlushing = (bool) $untilEmpty;
}
return $this;
} | [
"public",
"function",
"flush",
"(",
"$",
"untilEmpty",
"=",
"true",
")",
"{",
"// Send BatchWriteItem requests until the queue is empty",
"$",
"keepFlushing",
"=",
"true",
";",
"while",
"(",
"$",
"this",
"->",
"queue",
"&&",
"$",
"keepFlushing",
")",
"{",
"$",
"commands",
"=",
"$",
"this",
"->",
"prepareCommands",
"(",
")",
";",
"$",
"pool",
"=",
"new",
"CommandPool",
"(",
"$",
"this",
"->",
"client",
",",
"$",
"commands",
",",
"[",
"'before'",
"=>",
"$",
"this",
"->",
"config",
"[",
"'before'",
"]",
",",
"'concurrency'",
"=>",
"$",
"this",
"->",
"config",
"[",
"'pool_size'",
"]",
",",
"'fulfilled'",
"=>",
"function",
"(",
"ResultInterface",
"$",
"result",
")",
"{",
"// Re-queue any unprocessed items",
"if",
"(",
"$",
"result",
"->",
"hasKey",
"(",
"'UnprocessedItems'",
")",
")",
"{",
"$",
"this",
"->",
"retryUnprocessed",
"(",
"$",
"result",
"[",
"'UnprocessedItems'",
"]",
")",
";",
"}",
"}",
",",
"'rejected'",
"=>",
"function",
"(",
"$",
"reason",
")",
"{",
"if",
"(",
"$",
"reason",
"instanceof",
"AwsException",
")",
"{",
"$",
"code",
"=",
"$",
"reason",
"->",
"getAwsErrorCode",
"(",
")",
";",
"if",
"(",
"$",
"code",
"===",
"'ProvisionedThroughputExceededException'",
")",
"{",
"$",
"this",
"->",
"retryUnprocessed",
"(",
"$",
"reason",
"->",
"getCommand",
"(",
")",
"[",
"'RequestItems'",
"]",
")",
";",
"}",
"elseif",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"config",
"[",
"'error'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"config",
"[",
"'error'",
"]",
"(",
"$",
"reason",
")",
";",
"}",
"}",
"}",
"]",
")",
";",
"$",
"pool",
"->",
"promise",
"(",
")",
"->",
"wait",
"(",
")",
";",
"$",
"keepFlushing",
"=",
"(",
"bool",
")",
"$",
"untilEmpty",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Flushes the batch by combining all the queued put and delete requests
into BatchWriteItem commands and executing them. Unprocessed items are
automatically re-queued.
@param bool $untilEmpty If true, flushing will continue until the queue
is completely empty. This will make sure that
unprocessed items are all eventually sent.
@return $this | [
"Flushes",
"the",
"batch",
"by",
"combining",
"all",
"the",
"queued",
"put",
"and",
"delete",
"requests",
"into",
"BatchWriteItem",
"commands",
"and",
"executing",
"them",
".",
"Unprocessed",
"items",
"are",
"automatically",
"re",
"-",
"queued",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/WriteRequestBatch.php#L155-L186 | train |
aws/aws-sdk-php | src/DynamoDb/WriteRequestBatch.php | WriteRequestBatch.autoFlush | private function autoFlush()
{
if ($this->config['autoflush']
&& count($this->queue) >= $this->config['threshold']
) {
// Flush only once. Unprocessed items are handled in a later flush.
$this->flush(false);
}
} | php | private function autoFlush()
{
if ($this->config['autoflush']
&& count($this->queue) >= $this->config['threshold']
) {
// Flush only once. Unprocessed items are handled in a later flush.
$this->flush(false);
}
} | [
"private",
"function",
"autoFlush",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"[",
"'autoflush'",
"]",
"&&",
"count",
"(",
"$",
"this",
"->",
"queue",
")",
">=",
"$",
"this",
"->",
"config",
"[",
"'threshold'",
"]",
")",
"{",
"// Flush only once. Unprocessed items are handled in a later flush.",
"$",
"this",
"->",
"flush",
"(",
"false",
")",
";",
"}",
"}"
] | If autoflush is enabled and the threshold is met, flush the batch | [
"If",
"autoflush",
"is",
"enabled",
"and",
"the",
"threshold",
"is",
"met",
"flush",
"the",
"batch"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/WriteRequestBatch.php#L238-L246 | train |
aws/aws-sdk-php | src/S3/Crypto/HeadersMetadataStrategy.php | HeadersMetadataStrategy.save | public function save(MetadataEnvelope $envelope, array $args)
{
foreach ($envelope as $header=>$value) {
$args['Metadata'][$header] = $value;
}
return $args;
} | php | public function save(MetadataEnvelope $envelope, array $args)
{
foreach ($envelope as $header=>$value) {
$args['Metadata'][$header] = $value;
}
return $args;
} | [
"public",
"function",
"save",
"(",
"MetadataEnvelope",
"$",
"envelope",
",",
"array",
"$",
"args",
")",
"{",
"foreach",
"(",
"$",
"envelope",
"as",
"$",
"header",
"=>",
"$",
"value",
")",
"{",
"$",
"args",
"[",
"'Metadata'",
"]",
"[",
"$",
"header",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"args",
";",
"}"
] | Places the information in the MetadataEnvelope in to the Meatadata for
the PutObject request of the encrypted object.
@param MetadataEnvelope $envelope Encryption data to save according to
the strategy.
@param array $args Arguments for PutObject that can be manipulated to
store strategy related information.
@return array Updated arguments for PutObject. | [
"Places",
"the",
"information",
"in",
"the",
"MetadataEnvelope",
"in",
"to",
"the",
"Meatadata",
"for",
"the",
"PutObject",
"request",
"of",
"the",
"encrypted",
"object",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/Crypto/HeadersMetadataStrategy.php#L20-L27 | train |
aws/aws-sdk-php | src/S3/Crypto/HeadersMetadataStrategy.php | HeadersMetadataStrategy.load | public function load(array $args)
{
$envelope = new MetadataEnvelope();
$constantValues = MetadataEnvelope::getConstantValues();
foreach ($constantValues as $constant) {
if (!empty($args['Metadata'][$constant])) {
$envelope[$constant] = $args['Metadata'][$constant];
}
}
return $envelope;
} | php | public function load(array $args)
{
$envelope = new MetadataEnvelope();
$constantValues = MetadataEnvelope::getConstantValues();
foreach ($constantValues as $constant) {
if (!empty($args['Metadata'][$constant])) {
$envelope[$constant] = $args['Metadata'][$constant];
}
}
return $envelope;
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"args",
")",
"{",
"$",
"envelope",
"=",
"new",
"MetadataEnvelope",
"(",
")",
";",
"$",
"constantValues",
"=",
"MetadataEnvelope",
"::",
"getConstantValues",
"(",
")",
";",
"foreach",
"(",
"$",
"constantValues",
"as",
"$",
"constant",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"args",
"[",
"'Metadata'",
"]",
"[",
"$",
"constant",
"]",
")",
")",
"{",
"$",
"envelope",
"[",
"$",
"constant",
"]",
"=",
"$",
"args",
"[",
"'Metadata'",
"]",
"[",
"$",
"constant",
"]",
";",
"}",
"}",
"return",
"$",
"envelope",
";",
"}"
] | Generates a MetadataEnvelope according to the Metadata headers from the
GetObject result.
@param array $args Arguments from Command and Result that contains
S3 Object information, relevant headers, and command
configuration.
@return MetadataEnvelope | [
"Generates",
"a",
"MetadataEnvelope",
"according",
"to",
"the",
"Metadata",
"headers",
"from",
"the",
"GetObject",
"result",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/S3/Crypto/HeadersMetadataStrategy.php#L39-L51 | train |
aws/aws-sdk-php | src/Api/Serializer/XmlBody.php | XmlBody.build | public function build(Shape $shape, array $args)
{
$xml = new XMLWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$this->format($shape, $shape['locationName'] ?: $shape['name'], $args, $xml);
$xml->endDocument();
return $xml->outputMemory();
} | php | public function build(Shape $shape, array $args)
{
$xml = new XMLWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$this->format($shape, $shape['locationName'] ?: $shape['name'], $args, $xml);
$xml->endDocument();
return $xml->outputMemory();
} | [
"public",
"function",
"build",
"(",
"Shape",
"$",
"shape",
",",
"array",
"$",
"args",
")",
"{",
"$",
"xml",
"=",
"new",
"XMLWriter",
"(",
")",
";",
"$",
"xml",
"->",
"openMemory",
"(",
")",
";",
"$",
"xml",
"->",
"startDocument",
"(",
"'1.0'",
",",
"'UTF-8'",
")",
";",
"$",
"this",
"->",
"format",
"(",
"$",
"shape",
",",
"$",
"shape",
"[",
"'locationName'",
"]",
"?",
":",
"$",
"shape",
"[",
"'name'",
"]",
",",
"$",
"args",
",",
"$",
"xml",
")",
";",
"$",
"xml",
"->",
"endDocument",
"(",
")",
";",
"return",
"$",
"xml",
"->",
"outputMemory",
"(",
")",
";",
"}"
] | Builds the XML body based on an array of arguments.
@param Shape $shape Operation being constructed
@param array $args Associative array of arguments
@return string | [
"Builds",
"the",
"XML",
"body",
"based",
"on",
"an",
"array",
"of",
"arguments",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/Serializer/XmlBody.php#L36-L45 | train |
aws/aws-sdk-php | src/DynamoDb/SessionHandler.php | SessionHandler.fromClient | public static function fromClient(DynamoDbClient $client, array $config = [])
{
$config += ['locking' => false];
if ($config['locking']) {
$connection = new LockingSessionConnection($client, $config);
} else {
$connection = new StandardSessionConnection($client, $config);
}
return new static($connection);
} | php | public static function fromClient(DynamoDbClient $client, array $config = [])
{
$config += ['locking' => false];
if ($config['locking']) {
$connection = new LockingSessionConnection($client, $config);
} else {
$connection = new StandardSessionConnection($client, $config);
}
return new static($connection);
} | [
"public",
"static",
"function",
"fromClient",
"(",
"DynamoDbClient",
"$",
"client",
",",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"config",
"+=",
"[",
"'locking'",
"=>",
"false",
"]",
";",
"if",
"(",
"$",
"config",
"[",
"'locking'",
"]",
")",
"{",
"$",
"connection",
"=",
"new",
"LockingSessionConnection",
"(",
"$",
"client",
",",
"$",
"config",
")",
";",
"}",
"else",
"{",
"$",
"connection",
"=",
"new",
"StandardSessionConnection",
"(",
"$",
"client",
",",
"$",
"config",
")",
";",
"}",
"return",
"new",
"static",
"(",
"$",
"connection",
")",
";",
"}"
] | Creates a new DynamoDB Session Handler.
The configuration array accepts the following array keys and values:
- table_name: Name of table to store the sessions.
- hash_key: Name of hash key in table. Default: "id".
- session_lifetime: Lifetime of inactive sessions expiration.
- consistent_read: Whether or not to use consistent reads.
- batch_config: Batch options used for garbage collection.
- locking: Whether or not to use session locking.
- max_lock_wait_time: Max time (s) to wait for lock acquisition.
- min_lock_retry_microtime: Min time (µs) to wait between lock attempts.
- max_lock_retry_microtime: Max time (µs) to wait between lock attempts.
@param DynamoDbClient $client Client for doing DynamoDB operations
@param array $config Configuration for the Session Handler
@return SessionHandler | [
"Creates",
"a",
"new",
"DynamoDB",
"Session",
"Handler",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/SessionHandler.php#L60-L70 | train |
aws/aws-sdk-php | src/DynamoDb/SessionHandler.php | SessionHandler.close | public function close()
{
$id = session_id();
// Make sure the session is unlocked and the expiration time is updated,
// even if the write did not occur
if ($this->openSessionId !== $id || !$this->sessionWritten) {
$result = $this->connection->write($this->formatId($id), '', false);
$this->sessionWritten = (bool) $result;
}
return $this->sessionWritten;
} | php | public function close()
{
$id = session_id();
// Make sure the session is unlocked and the expiration time is updated,
// even if the write did not occur
if ($this->openSessionId !== $id || !$this->sessionWritten) {
$result = $this->connection->write($this->formatId($id), '', false);
$this->sessionWritten = (bool) $result;
}
return $this->sessionWritten;
} | [
"public",
"function",
"close",
"(",
")",
"{",
"$",
"id",
"=",
"session_id",
"(",
")",
";",
"// Make sure the session is unlocked and the expiration time is updated,",
"// even if the write did not occur",
"if",
"(",
"$",
"this",
"->",
"openSessionId",
"!==",
"$",
"id",
"||",
"!",
"$",
"this",
"->",
"sessionWritten",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"connection",
"->",
"write",
"(",
"$",
"this",
"->",
"formatId",
"(",
"$",
"id",
")",
",",
"''",
",",
"false",
")",
";",
"$",
"this",
"->",
"sessionWritten",
"=",
"(",
"bool",
")",
"$",
"result",
";",
"}",
"return",
"$",
"this",
"->",
"sessionWritten",
";",
"}"
] | Close a session from writing.
@return bool Success | [
"Close",
"a",
"session",
"from",
"writing",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/SessionHandler.php#L112-L123 | train |
aws/aws-sdk-php | src/DynamoDb/SessionHandler.php | SessionHandler.read | public function read($id)
{
$this->openSessionId = $id;
// PHP expects an empty string to be returned from this method if no
// data is retrieved
$this->dataRead = '';
// Get session data using the selected locking strategy
$item = $this->connection->read($this->formatId($id));
// Return the data if it is not expired. If it is expired, remove it
if (isset($item['expires']) && isset($item['data'])) {
$this->dataRead = $item['data'];
if ($item['expires'] <= time()) {
$this->dataRead = '';
$this->destroy($id);
}
}
return $this->dataRead;
} | php | public function read($id)
{
$this->openSessionId = $id;
// PHP expects an empty string to be returned from this method if no
// data is retrieved
$this->dataRead = '';
// Get session data using the selected locking strategy
$item = $this->connection->read($this->formatId($id));
// Return the data if it is not expired. If it is expired, remove it
if (isset($item['expires']) && isset($item['data'])) {
$this->dataRead = $item['data'];
if ($item['expires'] <= time()) {
$this->dataRead = '';
$this->destroy($id);
}
}
return $this->dataRead;
} | [
"public",
"function",
"read",
"(",
"$",
"id",
")",
"{",
"$",
"this",
"->",
"openSessionId",
"=",
"$",
"id",
";",
"// PHP expects an empty string to be returned from this method if no",
"// data is retrieved",
"$",
"this",
"->",
"dataRead",
"=",
"''",
";",
"// Get session data using the selected locking strategy",
"$",
"item",
"=",
"$",
"this",
"->",
"connection",
"->",
"read",
"(",
"$",
"this",
"->",
"formatId",
"(",
"$",
"id",
")",
")",
";",
"// Return the data if it is not expired. If it is expired, remove it",
"if",
"(",
"isset",
"(",
"$",
"item",
"[",
"'expires'",
"]",
")",
"&&",
"isset",
"(",
"$",
"item",
"[",
"'data'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"dataRead",
"=",
"$",
"item",
"[",
"'data'",
"]",
";",
"if",
"(",
"$",
"item",
"[",
"'expires'",
"]",
"<=",
"time",
"(",
")",
")",
"{",
"$",
"this",
"->",
"dataRead",
"=",
"''",
";",
"$",
"this",
"->",
"destroy",
"(",
"$",
"id",
")",
";",
"}",
"}",
"return",
"$",
"this",
"->",
"dataRead",
";",
"}"
] | Read a session stored in DynamoDB.
@param string $id Session ID.
@return string Session data. | [
"Read",
"a",
"session",
"stored",
"in",
"DynamoDB",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/SessionHandler.php#L132-L152 | train |
aws/aws-sdk-php | src/DynamoDb/SessionHandler.php | SessionHandler.write | public function write($id, $data)
{
$changed = $id !== $this->openSessionId
|| $data !== $this->dataRead;
$this->openSessionId = $id;
// Write the session data using the selected locking strategy
$this->sessionWritten = $this->connection
->write($this->formatId($id), $data, $changed);
return $this->sessionWritten;
} | php | public function write($id, $data)
{
$changed = $id !== $this->openSessionId
|| $data !== $this->dataRead;
$this->openSessionId = $id;
// Write the session data using the selected locking strategy
$this->sessionWritten = $this->connection
->write($this->formatId($id), $data, $changed);
return $this->sessionWritten;
} | [
"public",
"function",
"write",
"(",
"$",
"id",
",",
"$",
"data",
")",
"{",
"$",
"changed",
"=",
"$",
"id",
"!==",
"$",
"this",
"->",
"openSessionId",
"||",
"$",
"data",
"!==",
"$",
"this",
"->",
"dataRead",
";",
"$",
"this",
"->",
"openSessionId",
"=",
"$",
"id",
";",
"// Write the session data using the selected locking strategy",
"$",
"this",
"->",
"sessionWritten",
"=",
"$",
"this",
"->",
"connection",
"->",
"write",
"(",
"$",
"this",
"->",
"formatId",
"(",
"$",
"id",
")",
",",
"$",
"data",
",",
"$",
"changed",
")",
";",
"return",
"$",
"this",
"->",
"sessionWritten",
";",
"}"
] | Write a session to DynamoDB.
@param string $id Session ID.
@param string $data Serialized session data to write.
@return bool Whether or not the operation succeeded. | [
"Write",
"a",
"session",
"to",
"DynamoDB",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/SessionHandler.php#L162-L173 | train |
aws/aws-sdk-php | src/DynamoDb/SessionHandler.php | SessionHandler.destroy | public function destroy($id)
{
$this->openSessionId = $id;
// Delete the session data using the selected locking strategy
$this->sessionWritten
= $this->connection->delete($this->formatId($id));
return $this->sessionWritten;
} | php | public function destroy($id)
{
$this->openSessionId = $id;
// Delete the session data using the selected locking strategy
$this->sessionWritten
= $this->connection->delete($this->formatId($id));
return $this->sessionWritten;
} | [
"public",
"function",
"destroy",
"(",
"$",
"id",
")",
"{",
"$",
"this",
"->",
"openSessionId",
"=",
"$",
"id",
";",
"// Delete the session data using the selected locking strategy",
"$",
"this",
"->",
"sessionWritten",
"=",
"$",
"this",
"->",
"connection",
"->",
"delete",
"(",
"$",
"this",
"->",
"formatId",
"(",
"$",
"id",
")",
")",
";",
"return",
"$",
"this",
"->",
"sessionWritten",
";",
"}"
] | Delete a session stored in DynamoDB.
@param string $id Session ID.
@return bool Whether or not the operation succeeded. | [
"Delete",
"a",
"session",
"stored",
"in",
"DynamoDB",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/DynamoDb/SessionHandler.php#L182-L190 | train |
aws/aws-sdk-php | src/Multipart/AbstractUploader.php | AbstractUploader.isEof | private function isEof($seekable)
{
return $seekable
? $this->source->tell() < $this->source->getSize()
: !$this->source->eof();
} | php | private function isEof($seekable)
{
return $seekable
? $this->source->tell() < $this->source->getSize()
: !$this->source->eof();
} | [
"private",
"function",
"isEof",
"(",
"$",
"seekable",
")",
"{",
"return",
"$",
"seekable",
"?",
"$",
"this",
"->",
"source",
"->",
"tell",
"(",
")",
"<",
"$",
"this",
"->",
"source",
"->",
"getSize",
"(",
")",
":",
"!",
"$",
"this",
"->",
"source",
"->",
"eof",
"(",
")",
";",
"}"
] | Checks if the source is at EOF.
@param bool $seekable
@return bool | [
"Checks",
"if",
"the",
"source",
"is",
"at",
"EOF",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Multipart/AbstractUploader.php#L97-L102 | train |
aws/aws-sdk-php | src/Multipart/AbstractUploader.php | AbstractUploader.determineSource | private function determineSource($source)
{
// Use the contents of a file as the data source.
if (is_string($source)) {
$source = Psr7\try_fopen($source, 'r');
}
// Create a source stream.
$stream = Psr7\stream_for($source);
if (!$stream->isReadable()) {
throw new IAE('Source stream must be readable.');
}
return $stream;
} | php | private function determineSource($source)
{
// Use the contents of a file as the data source.
if (is_string($source)) {
$source = Psr7\try_fopen($source, 'r');
}
// Create a source stream.
$stream = Psr7\stream_for($source);
if (!$stream->isReadable()) {
throw new IAE('Source stream must be readable.');
}
return $stream;
} | [
"private",
"function",
"determineSource",
"(",
"$",
"source",
")",
"{",
"// Use the contents of a file as the data source.",
"if",
"(",
"is_string",
"(",
"$",
"source",
")",
")",
"{",
"$",
"source",
"=",
"Psr7",
"\\",
"try_fopen",
"(",
"$",
"source",
",",
"'r'",
")",
";",
"}",
"// Create a source stream.",
"$",
"stream",
"=",
"Psr7",
"\\",
"stream_for",
"(",
"$",
"source",
")",
";",
"if",
"(",
"!",
"$",
"stream",
"->",
"isReadable",
"(",
")",
")",
"{",
"throw",
"new",
"IAE",
"(",
"'Source stream must be readable.'",
")",
";",
"}",
"return",
"$",
"stream",
";",
"}"
] | Turns the provided source into a stream and stores it.
If a string is provided, it is assumed to be a filename, otherwise, it
passes the value directly to `Psr7\stream_for()`.
@param mixed $source
@return Stream | [
"Turns",
"the",
"provided",
"source",
"into",
"a",
"stream",
"and",
"stores",
"it",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Multipart/AbstractUploader.php#L114-L128 | train |
aws/aws-sdk-php | src/Polly/PollyClient.php | PollyClient.createSynthesizeSpeechPreSignedUrl | public function createSynthesizeSpeechPreSignedUrl(array $args)
{
$uri = new Uri($this->getEndpoint());
$uri = $uri->withPath('/v1/speech');
// Formatting parameters follows rest-json protocol
$this->formatter = $this->formatter ?: new JsonBody($this->getApi());
$queryArray = json_decode(
$this->formatter->build(
$this->getApi()->getOperation('SynthesizeSpeech')->getInput(),
$args
),
true
);
// Mocking a 'GET' request in pre-signing the Url
$query = Psr7\build_query($queryArray);
$uri = $uri->withQuery($query);
$request = new Request('GET', $uri);
$request = $request->withBody(Psr7\stream_for(''));
$signer = new SignatureV4('polly', $this->getRegion());
return (string) $signer->presign(
$request,
$this->getCredentials()->wait(),
'+15 minutes'
)->getUri();
} | php | public function createSynthesizeSpeechPreSignedUrl(array $args)
{
$uri = new Uri($this->getEndpoint());
$uri = $uri->withPath('/v1/speech');
// Formatting parameters follows rest-json protocol
$this->formatter = $this->formatter ?: new JsonBody($this->getApi());
$queryArray = json_decode(
$this->formatter->build(
$this->getApi()->getOperation('SynthesizeSpeech')->getInput(),
$args
),
true
);
// Mocking a 'GET' request in pre-signing the Url
$query = Psr7\build_query($queryArray);
$uri = $uri->withQuery($query);
$request = new Request('GET', $uri);
$request = $request->withBody(Psr7\stream_for(''));
$signer = new SignatureV4('polly', $this->getRegion());
return (string) $signer->presign(
$request,
$this->getCredentials()->wait(),
'+15 minutes'
)->getUri();
} | [
"public",
"function",
"createSynthesizeSpeechPreSignedUrl",
"(",
"array",
"$",
"args",
")",
"{",
"$",
"uri",
"=",
"new",
"Uri",
"(",
"$",
"this",
"->",
"getEndpoint",
"(",
")",
")",
";",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withPath",
"(",
"'/v1/speech'",
")",
";",
"// Formatting parameters follows rest-json protocol",
"$",
"this",
"->",
"formatter",
"=",
"$",
"this",
"->",
"formatter",
"?",
":",
"new",
"JsonBody",
"(",
"$",
"this",
"->",
"getApi",
"(",
")",
")",
";",
"$",
"queryArray",
"=",
"json_decode",
"(",
"$",
"this",
"->",
"formatter",
"->",
"build",
"(",
"$",
"this",
"->",
"getApi",
"(",
")",
"->",
"getOperation",
"(",
"'SynthesizeSpeech'",
")",
"->",
"getInput",
"(",
")",
",",
"$",
"args",
")",
",",
"true",
")",
";",
"// Mocking a 'GET' request in pre-signing the Url",
"$",
"query",
"=",
"Psr7",
"\\",
"build_query",
"(",
"$",
"queryArray",
")",
";",
"$",
"uri",
"=",
"$",
"uri",
"->",
"withQuery",
"(",
"$",
"query",
")",
";",
"$",
"request",
"=",
"new",
"Request",
"(",
"'GET'",
",",
"$",
"uri",
")",
";",
"$",
"request",
"=",
"$",
"request",
"->",
"withBody",
"(",
"Psr7",
"\\",
"stream_for",
"(",
"''",
")",
")",
";",
"$",
"signer",
"=",
"new",
"SignatureV4",
"(",
"'polly'",
",",
"$",
"this",
"->",
"getRegion",
"(",
")",
")",
";",
"return",
"(",
"string",
")",
"$",
"signer",
"->",
"presign",
"(",
"$",
"request",
",",
"$",
"this",
"->",
"getCredentials",
"(",
")",
"->",
"wait",
"(",
")",
",",
"'+15 minutes'",
")",
"->",
"getUri",
"(",
")",
";",
"}"
] | Create a pre-signed URL for Polly operation `SynthesizeSpeech`
@param array $args parameters array for `SynthesizeSpeech`
More information @see Aws\Polly\PollyClient::SynthesizeSpeech
@return string | [
"Create",
"a",
"pre",
"-",
"signed",
"URL",
"for",
"Polly",
"operation",
"SynthesizeSpeech"
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Polly/PollyClient.php#L45-L72 | train |
aws/aws-sdk-php | build/ClassAnnotationUpdater.php | ClassAnnotationUpdater.update | public function update()
{
// copy the code into memory
$backup = file($this->reflection->getFileName());
list($preamble, $class) = $this->splitClassFile($backup);
$preamble = $this->stripOutExistingDocBlock($preamble);
$preamble .= $this->buildUpdatedDocBlock();
if ($this->writeClassFile(implode(PHP_EOL, [$preamble, $class]))
&& $this->commandLineLint($this->reflection->getFileName())
) {
return true;
}
$this->writeClassFile(implode('', $backup));
return false;
} | php | public function update()
{
// copy the code into memory
$backup = file($this->reflection->getFileName());
list($preamble, $class) = $this->splitClassFile($backup);
$preamble = $this->stripOutExistingDocBlock($preamble);
$preamble .= $this->buildUpdatedDocBlock();
if ($this->writeClassFile(implode(PHP_EOL, [$preamble, $class]))
&& $this->commandLineLint($this->reflection->getFileName())
) {
return true;
}
$this->writeClassFile(implode('', $backup));
return false;
} | [
"public",
"function",
"update",
"(",
")",
"{",
"// copy the code into memory",
"$",
"backup",
"=",
"file",
"(",
"$",
"this",
"->",
"reflection",
"->",
"getFileName",
"(",
")",
")",
";",
"list",
"(",
"$",
"preamble",
",",
"$",
"class",
")",
"=",
"$",
"this",
"->",
"splitClassFile",
"(",
"$",
"backup",
")",
";",
"$",
"preamble",
"=",
"$",
"this",
"->",
"stripOutExistingDocBlock",
"(",
"$",
"preamble",
")",
";",
"$",
"preamble",
".=",
"$",
"this",
"->",
"buildUpdatedDocBlock",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"writeClassFile",
"(",
"implode",
"(",
"PHP_EOL",
",",
"[",
"$",
"preamble",
",",
"$",
"class",
"]",
")",
")",
"&&",
"$",
"this",
"->",
"commandLineLint",
"(",
"$",
"this",
"->",
"reflection",
"->",
"getFileName",
"(",
")",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"this",
"->",
"writeClassFile",
"(",
"implode",
"(",
"''",
",",
"$",
"backup",
")",
")",
";",
"return",
"false",
";",
"}"
] | Performs update on class file and lints the output. If the output fails
linting, the change is reverted.
@return bool TRUE on success, FALSE on failure | [
"Performs",
"update",
"on",
"class",
"file",
"and",
"lints",
"the",
"output",
".",
"If",
"the",
"output",
"fails",
"linting",
"the",
"change",
"is",
"reverted",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/build/ClassAnnotationUpdater.php#L39-L56 | train |
aws/aws-sdk-php | src/Api/TimestampShape.php | TimestampShape.format | public static function format($value, $format)
{
if ($value instanceof \DateTime) {
$value = $value->getTimestamp();
} elseif (is_string($value)) {
$value = strtotime($value);
} elseif (!is_int($value)) {
throw new \InvalidArgumentException('Unable to handle the provided'
. ' timestamp type: ' . gettype($value));
}
switch ($format) {
case 'iso8601':
return gmdate('Y-m-d\TH:i:s\Z', $value);
case 'rfc822':
return gmdate('D, d M Y H:i:s \G\M\T', $value);
case 'unixTimestamp':
return $value;
default:
throw new \UnexpectedValueException('Unknown timestamp format: '
. $format);
}
} | php | public static function format($value, $format)
{
if ($value instanceof \DateTime) {
$value = $value->getTimestamp();
} elseif (is_string($value)) {
$value = strtotime($value);
} elseif (!is_int($value)) {
throw new \InvalidArgumentException('Unable to handle the provided'
. ' timestamp type: ' . gettype($value));
}
switch ($format) {
case 'iso8601':
return gmdate('Y-m-d\TH:i:s\Z', $value);
case 'rfc822':
return gmdate('D, d M Y H:i:s \G\M\T', $value);
case 'unixTimestamp':
return $value;
default:
throw new \UnexpectedValueException('Unknown timestamp format: '
. $format);
}
} | [
"public",
"static",
"function",
"format",
"(",
"$",
"value",
",",
"$",
"format",
")",
"{",
"if",
"(",
"$",
"value",
"instanceof",
"\\",
"DateTime",
")",
"{",
"$",
"value",
"=",
"$",
"value",
"->",
"getTimestamp",
"(",
")",
";",
"}",
"elseif",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"strtotime",
"(",
"$",
"value",
")",
";",
"}",
"elseif",
"(",
"!",
"is_int",
"(",
"$",
"value",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Unable to handle the provided'",
".",
"' timestamp type: '",
".",
"gettype",
"(",
"$",
"value",
")",
")",
";",
"}",
"switch",
"(",
"$",
"format",
")",
"{",
"case",
"'iso8601'",
":",
"return",
"gmdate",
"(",
"'Y-m-d\\TH:i:s\\Z'",
",",
"$",
"value",
")",
";",
"case",
"'rfc822'",
":",
"return",
"gmdate",
"(",
"'D, d M Y H:i:s \\G\\M\\T'",
",",
"$",
"value",
")",
";",
"case",
"'unixTimestamp'",
":",
"return",
"$",
"value",
";",
"default",
":",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"'Unknown timestamp format: '",
".",
"$",
"format",
")",
";",
"}",
"}"
] | Formats a timestamp value for a service.
@param mixed $value Value to format
@param string $format Format used to serialize the value
@return int|string
@throws \UnexpectedValueException if the format is unknown.
@throws \InvalidArgumentException if the value is an unsupported type. | [
"Formats",
"a",
"timestamp",
"value",
"for",
"a",
"service",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Api/TimestampShape.php#L25-L47 | train |
aws/aws-sdk-php | src/Signature/SignatureProvider.php | SignatureProvider.resolve | public static function resolve(callable $provider, $version, $service, $region)
{
$result = $provider($version, $service, $region);
if ($result instanceof SignatureInterface) {
return $result;
}
throw new UnresolvedSignatureException(
"Unable to resolve a signature for $version/$service/$region.\n"
. "Valid signature versions include v4 and anonymous."
);
} | php | public static function resolve(callable $provider, $version, $service, $region)
{
$result = $provider($version, $service, $region);
if ($result instanceof SignatureInterface) {
return $result;
}
throw new UnresolvedSignatureException(
"Unable to resolve a signature for $version/$service/$region.\n"
. "Valid signature versions include v4 and anonymous."
);
} | [
"public",
"static",
"function",
"resolve",
"(",
"callable",
"$",
"provider",
",",
"$",
"version",
",",
"$",
"service",
",",
"$",
"region",
")",
"{",
"$",
"result",
"=",
"$",
"provider",
"(",
"$",
"version",
",",
"$",
"service",
",",
"$",
"region",
")",
";",
"if",
"(",
"$",
"result",
"instanceof",
"SignatureInterface",
")",
"{",
"return",
"$",
"result",
";",
"}",
"throw",
"new",
"UnresolvedSignatureException",
"(",
"\"Unable to resolve a signature for $version/$service/$region.\\n\"",
".",
"\"Valid signature versions include v4 and anonymous.\"",
")",
";",
"}"
] | Resolves and signature provider and ensures a non-null return value.
@param callable $provider Provider function to invoke.
@param string $version Signature version.
@param string $service Service name.
@param string $region Region name.
@return SignatureInterface
@throws UnresolvedSignatureException | [
"Resolves",
"and",
"signature",
"provider",
"and",
"ensures",
"a",
"non",
"-",
"null",
"return",
"value",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Signature/SignatureProvider.php#L59-L70 | train |
aws/aws-sdk-php | src/Signature/SignatureProvider.php | SignatureProvider.memoize | public static function memoize(callable $provider)
{
$cache = [];
return function ($version, $service, $region) use (&$cache, $provider) {
$key = "($version)($service)($region)";
if (!isset($cache[$key])) {
$cache[$key] = $provider($version, $service, $region);
}
return $cache[$key];
};
} | php | public static function memoize(callable $provider)
{
$cache = [];
return function ($version, $service, $region) use (&$cache, $provider) {
$key = "($version)($service)($region)";
if (!isset($cache[$key])) {
$cache[$key] = $provider($version, $service, $region);
}
return $cache[$key];
};
} | [
"public",
"static",
"function",
"memoize",
"(",
"callable",
"$",
"provider",
")",
"{",
"$",
"cache",
"=",
"[",
"]",
";",
"return",
"function",
"(",
"$",
"version",
",",
"$",
"service",
",",
"$",
"region",
")",
"use",
"(",
"&",
"$",
"cache",
",",
"$",
"provider",
")",
"{",
"$",
"key",
"=",
"\"($version)($service)($region)\"",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"cache",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"cache",
"[",
"$",
"key",
"]",
"=",
"$",
"provider",
"(",
"$",
"version",
",",
"$",
"service",
",",
"$",
"region",
")",
";",
"}",
"return",
"$",
"cache",
"[",
"$",
"key",
"]",
";",
"}",
";",
"}"
] | Creates a signature provider that caches previously created signature
objects. The computed cache key is the concatenation of the version,
service, and region.
@param callable $provider Signature provider to wrap.
@return callable | [
"Creates",
"a",
"signature",
"provider",
"that",
"caches",
"previously",
"created",
"signature",
"objects",
".",
"The",
"computed",
"cache",
"key",
"is",
"the",
"concatenation",
"of",
"the",
"version",
"service",
"and",
"region",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Signature/SignatureProvider.php#L91-L101 | train |
aws/aws-sdk-php | src/Ses/SesClient.php | SesClient.generateSmtpPassword | public static function generateSmtpPassword(CredentialsInterface $creds)
{
static $version = "\x02";
static $algo = 'sha256';
static $message = 'SendRawEmail';
$signature = hash_hmac($algo, $message, $creds->getSecretKey(), true);
return base64_encode($version . $signature);
} | php | public static function generateSmtpPassword(CredentialsInterface $creds)
{
static $version = "\x02";
static $algo = 'sha256';
static $message = 'SendRawEmail';
$signature = hash_hmac($algo, $message, $creds->getSecretKey(), true);
return base64_encode($version . $signature);
} | [
"public",
"static",
"function",
"generateSmtpPassword",
"(",
"CredentialsInterface",
"$",
"creds",
")",
"{",
"static",
"$",
"version",
"=",
"\"\\x02\"",
";",
"static",
"$",
"algo",
"=",
"'sha256'",
";",
"static",
"$",
"message",
"=",
"'SendRawEmail'",
";",
"$",
"signature",
"=",
"hash_hmac",
"(",
"$",
"algo",
",",
"$",
"message",
",",
"$",
"creds",
"->",
"getSecretKey",
"(",
")",
",",
"true",
")",
";",
"return",
"base64_encode",
"(",
"$",
"version",
".",
"$",
"signature",
")",
";",
"}"
] | Create an SMTP password for a given IAM user's credentials.
The SMTP username is the Access Key ID for the provided credentials.
@link http://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html#smtp-credentials-convert
@param CredentialsInterface $creds
@return string | [
"Create",
"an",
"SMTP",
"password",
"for",
"a",
"given",
"IAM",
"user",
"s",
"credentials",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/Ses/SesClient.php#L166-L174 | train |
aws/aws-sdk-php | src/CommandPool.php | CommandPool.batch | public static function batch(
AwsClientInterface $client,
$commands,
array $config = []
) {
$results = [];
self::cmpCallback($config, 'fulfilled', $results);
self::cmpCallback($config, 'rejected', $results);
return (new self($client, $commands, $config))
->promise()
->then(static function () use (&$results) {
ksort($results);
return $results;
})
->wait();
} | php | public static function batch(
AwsClientInterface $client,
$commands,
array $config = []
) {
$results = [];
self::cmpCallback($config, 'fulfilled', $results);
self::cmpCallback($config, 'rejected', $results);
return (new self($client, $commands, $config))
->promise()
->then(static function () use (&$results) {
ksort($results);
return $results;
})
->wait();
} | [
"public",
"static",
"function",
"batch",
"(",
"AwsClientInterface",
"$",
"client",
",",
"$",
"commands",
",",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"self",
"::",
"cmpCallback",
"(",
"$",
"config",
",",
"'fulfilled'",
",",
"$",
"results",
")",
";",
"self",
"::",
"cmpCallback",
"(",
"$",
"config",
",",
"'rejected'",
",",
"$",
"results",
")",
";",
"return",
"(",
"new",
"self",
"(",
"$",
"client",
",",
"$",
"commands",
",",
"$",
"config",
")",
")",
"->",
"promise",
"(",
")",
"->",
"then",
"(",
"static",
"function",
"(",
")",
"use",
"(",
"&",
"$",
"results",
")",
"{",
"ksort",
"(",
"$",
"results",
")",
";",
"return",
"$",
"results",
";",
"}",
")",
"->",
"wait",
"(",
")",
";",
"}"
] | Executes a pool synchronously and aggregates the results of the pool
into an indexed array in the same order as the passed in array.
@param AwsClientInterface $client Client used to execute commands.
@param mixed $commands Iterable that yields commands.
@param array $config Configuration options.
@return array
@see \Aws\CommandPool::__construct for available configuration options. | [
"Executes",
"a",
"pool",
"synchronously",
"and",
"aggregates",
"the",
"results",
"of",
"the",
"pool",
"into",
"an",
"indexed",
"array",
"in",
"the",
"same",
"order",
"as",
"the",
"passed",
"in",
"array",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CommandPool.php#L93-L109 | train |
aws/aws-sdk-php | src/CommandPool.php | CommandPool.cmpCallback | private static function cmpCallback(array &$config, $name, array &$results)
{
if (!isset($config[$name])) {
$config[$name] = function ($v, $k) use (&$results) {
$results[$k] = $v;
};
} else {
$currentFn = $config[$name];
$config[$name] = function ($v, $k) use (&$results, $currentFn) {
$currentFn($v, $k);
$results[$k] = $v;
};
}
} | php | private static function cmpCallback(array &$config, $name, array &$results)
{
if (!isset($config[$name])) {
$config[$name] = function ($v, $k) use (&$results) {
$results[$k] = $v;
};
} else {
$currentFn = $config[$name];
$config[$name] = function ($v, $k) use (&$results, $currentFn) {
$currentFn($v, $k);
$results[$k] = $v;
};
}
} | [
"private",
"static",
"function",
"cmpCallback",
"(",
"array",
"&",
"$",
"config",
",",
"$",
"name",
",",
"array",
"&",
"$",
"results",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"config",
"[",
"$",
"name",
"]",
")",
")",
"{",
"$",
"config",
"[",
"$",
"name",
"]",
"=",
"function",
"(",
"$",
"v",
",",
"$",
"k",
")",
"use",
"(",
"&",
"$",
"results",
")",
"{",
"$",
"results",
"[",
"$",
"k",
"]",
"=",
"$",
"v",
";",
"}",
";",
"}",
"else",
"{",
"$",
"currentFn",
"=",
"$",
"config",
"[",
"$",
"name",
"]",
";",
"$",
"config",
"[",
"$",
"name",
"]",
"=",
"function",
"(",
"$",
"v",
",",
"$",
"k",
")",
"use",
"(",
"&",
"$",
"results",
",",
"$",
"currentFn",
")",
"{",
"$",
"currentFn",
"(",
"$",
"v",
",",
"$",
"k",
")",
";",
"$",
"results",
"[",
"$",
"k",
"]",
"=",
"$",
"v",
";",
"}",
";",
"}",
"}"
] | Adds an onFulfilled or onRejected callback that aggregates results into
an array. If a callback is already present, it is replaced with the
composed function.
@param array $config
@param $name
@param array $results | [
"Adds",
"an",
"onFulfilled",
"or",
"onRejected",
"callback",
"that",
"aggregates",
"results",
"into",
"an",
"array",
".",
"If",
"a",
"callback",
"is",
"already",
"present",
"it",
"is",
"replaced",
"with",
"the",
"composed",
"function",
"."
] | 874c1040edab52df3873157aa54ea51833d48c0e | https://github.com/aws/aws-sdk-php/blob/874c1040edab52df3873157aa54ea51833d48c0e/src/CommandPool.php#L136-L149 | train |