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