Serializer.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Qcloud\Cos;
  3. use GuzzleHttp\Command\CommandInterface;
  4. use GuzzleHttp\Command\Guzzle\SchemaValidator;
  5. use GuzzleHttp\Command\Guzzle\DescriptionInterface;
  6. use GuzzleHttp\Command\Guzzle\Serializer as DefaultSerializer;
  7. use Psr\Http\Message\RequestInterface;
  8. /**
  9. * Override Request serializer to modify authentication mechanism
  10. */
  11. class Serializer extends DefaultSerializer
  12. {
  13. /**
  14. * {@inheritdoc}
  15. */
  16. public function __construct(
  17. DescriptionInterface $description,
  18. array $requestLocations = []
  19. ) {
  20. // Override Guzzle's body location as it isn't raw binary data
  21. $requestLocations['body'] = new Request\BodyLocation;
  22. parent::__construct($description, $requestLocations);
  23. }
  24. /**
  25. * Authorization header is Loco's preferred authorization method.
  26. * Add Authorization header to request if API key is set, unless query is explicitly configured as auth method.
  27. * Unset key from command to avoid sending it as a query param.
  28. *
  29. * @override
  30. *
  31. * @param CommandInterface $command
  32. * @param RequestInterface $request
  33. *
  34. * @return RequestInterface
  35. *
  36. * @throws \InvalidArgumentException
  37. */
  38. protected function prepareRequest(
  39. CommandInterface $command,
  40. RequestInterface $request
  41. ) {
  42. /*
  43. if ($command->offsetExists('key') === true) {
  44. $mode = empty($command->offsetGet('auth')) === false
  45. ? $command->offsetGet('auth')
  46. : 'loco';
  47. if ($mode !== 'query') {
  48. // else use Authorization header of various types
  49. if ($mode === 'loco') {
  50. $value = 'Loco '.$command->offsetGet('key');
  51. $request = $request->withHeader('Authorization', $value);
  52. } elseif ($mode === 'basic') {
  53. $value = 'Basic '.base64_encode($command->offsetGet('key').':');
  54. $request = $request->withHeader('Authorization', $value);
  55. } else {
  56. throw new \InvalidArgumentException("Invalid auth type: {$mode}");
  57. }
  58. // avoid request sending key parameter in query string
  59. $command->offsetUnset('key');
  60. }
  61. }
  62. // Remap legacy parameters to common `data` binding on request body
  63. static $remap = [
  64. 'import' => ['src'=>'data'],
  65. 'translate' => ['translation'=>'data'],
  66. ];
  67. $name = $command->getName();
  68. if (isset($remap[$name])) {
  69. foreach ($remap[$name] as $old => $new) {
  70. if ($command->offsetExists($old)) {
  71. $command->offsetSet($new, $command->offsetGet($old));
  72. $command->offsetUnset($old);
  73. }
  74. }
  75. }
  76. */
  77. return parent::prepareRequest($command, $request);
  78. }
  79. }