Serializer.php 2.8 KB

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