| 1 |
<?php |
| 2 |
namespace Aws; |
| 3 |
|
| 4 |
use Aws\Api\Service; |
| 5 |
use Psr\Http\Message\RequestInterface; |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
class IdempotencyTokenMiddleware |
| 11 |
{ |
| 12 |
|
| 13 |
private $service; |
| 14 |
|
| 15 |
|
| 16 |
private $bytesGenerator; |
| 17 |
|
| 18 |
|
| 19 |
private $nextHandler; |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
public static function wrap( |
| 41 |
Service $service, |
| 42 |
?callable $bytesGenerator = null |
| 43 |
) { |
| 44 |
return function (callable $handler) use ($service, $bytesGenerator) { |
| 45 |
return new self($handler, $service, $bytesGenerator); |
| 46 |
}; |
| 47 |
} |
| 48 |
|
| 49 |
public function __construct( |
| 50 |
callable $nextHandler, |
| 51 |
Service $service, |
| 52 |
?callable $bytesGenerator = null |
| 53 |
) { |
| 54 |
$this->bytesGenerator = $bytesGenerator |
| 55 |
?: $this->findCompatibleRandomSource(); |
| 56 |
$this->service = $service; |
| 57 |
$this->nextHandler = $nextHandler; |
| 58 |
} |
| 59 |
|
| 60 |
public function __invoke( |
| 61 |
CommandInterface $command, |
| 62 |
?RequestInterface $request = null |
| 63 |
) { |
| 64 |
$handler = $this->nextHandler; |
| 65 |
if ($this->bytesGenerator) { |
| 66 |
$operation = $this->service->getOperation($command->getName()); |
| 67 |
$members = $operation->getInput()->getMembers(); |
| 68 |
foreach ($members as $member => $value) { |
| 69 |
if ($value['idempotencyToken']) { |
| 70 |
$bytes = call_user_func($this->bytesGenerator, 16); |
| 71 |
|
| 72 |
$command[$member] = $command[$member] |
| 73 |
?: $this->getUuidV4($bytes); |
| 74 |
|
| 75 |
break; |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
return $handler($command, $request); |
| 80 |
} |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
private static function getUuidV4($bytes) |
| 93 |
{ |
| 94 |
|
| 95 |
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40); |
| 96 |
|
| 97 |
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80); |
| 98 |
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4)); |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
private function findCompatibleRandomSource() |
| 107 |
{ |
| 108 |
if (function_exists('random_bytes')) { |
| 109 |
return 'random_bytes'; |
| 110 |
} |
| 111 |
|
| 112 |
if (function_exists('openssl_random_pseudo_bytes')) { |
| 113 |
return 'openssl_random_pseudo_bytes'; |
| 114 |
} |
| 115 |
|
| 116 |
if (function_exists('mcrypt_create_iv')) { |
| 117 |
return 'mcrypt_create_iv'; |
| 118 |
} |
| 119 |
} |
| 120 |
} |