| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\Aws; |
| 4 |
|
| 5 |
use Dudlewebs\WPMCS\s3\Aws\Api\Service; |
| 6 |
use Dudlewebs\WPMCS\s3\Psr\Http\Message\RequestInterface; |
| 7 |
use Dudlewebs\WPMCS\s3\Psr\Log\InvalidArgumentException; |
| 8 |
/** |
| 9 |
* Used to update the host based on a modeled endpoint trait |
| 10 |
* |
| 11 |
* IMPORTANT: this middleware must be added after the "build" step. |
| 12 |
* |
| 13 |
* @internal |
| 14 |
*/ |
| 15 |
class EndpointParameterMiddleware |
| 16 |
{ |
| 17 |
/** @var callable */ |
| 18 |
private $nextHandler; |
| 19 |
/** @var Service */ |
| 20 |
private $service; |
| 21 |
/** |
| 22 |
* Create a middleware wrapper function |
| 23 |
* |
| 24 |
* @param Service $service |
| 25 |
* @param array $args |
| 26 |
* @return \Closure |
| 27 |
*/ |
| 28 |
public static function wrap(Service $service) |
| 29 |
{ |
| 30 |
return function (callable $handler) use($service) { |
| 31 |
return new self($handler, $service); |
| 32 |
}; |
| 33 |
} |
| 34 |
public function __construct(callable $nextHandler, Service $service) |
| 35 |
{ |
| 36 |
$this->nextHandler = $nextHandler; |
| 37 |
$this->service = $service; |
| 38 |
} |
| 39 |
public function __invoke(CommandInterface $command, RequestInterface $request) |
| 40 |
{ |
| 41 |
$nextHandler = $this->nextHandler; |
| 42 |
$operation = $this->service->getOperation($command->getName()); |
| 43 |
if (!empty($operation['endpoint']['hostPrefix'])) { |
| 44 |
$prefix = $operation['endpoint']['hostPrefix']; |
| 45 |
// Captures endpoint parameters stored in the modeled host. |
| 46 |
// These are denoted by enclosure in braces, i.e. '{param}' |
| 47 |
\preg_match_all("/\\{([a-zA-Z0-9]+)}/", $prefix, $parameters); |
| 48 |
if (!empty($parameters[1])) { |
| 49 |
// Captured parameters without braces stored in $parameters[1], |
| 50 |
// which should correspond to members in the Command object |
| 51 |
foreach ($parameters[1] as $index => $parameter) { |
| 52 |
if (empty($command[$parameter])) { |
| 53 |
throw new \InvalidArgumentException("The parameter '{$parameter}' must be set and not empty."); |
| 54 |
} |
| 55 |
// Captured parameters with braces stored in $parameters[0], |
| 56 |
// which are replaced by their corresponding Command value |
| 57 |
$prefix = \str_replace($parameters[0][$index], $command[$parameter], $prefix); |
| 58 |
} |
| 59 |
} |
| 60 |
$uri = $request->getUri(); |
| 61 |
$host = $prefix . $uri->getHost(); |
| 62 |
if (!\Dudlewebs\WPMCS\s3\Aws\is_valid_hostname($host)) { |
| 63 |
throw new \InvalidArgumentException("The supplied parameters result in an invalid hostname: '{$host}'."); |
| 64 |
} |
| 65 |
$request = $request->withUri($uri->withHost($host)); |
| 66 |
} |
| 67 |
return $nextHandler($command, $request); |
| 68 |
} |
| 69 |
} |
| 70 |
|