1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* php-guard/curl <https://github.com/php-guard/curl> |
4
|
|
|
* Copyright (C) 2018 by Alexandre Le Borgne <[email protected]>. |
5
|
|
|
* |
6
|
|
|
* This program is free software: you can redistribute it and/or modify |
7
|
|
|
* it under the terms of the GNU General Public License as published by |
8
|
|
|
* the Free Software Foundation, either version 3 of the License, or |
9
|
|
|
* (at your option) any later version. |
10
|
|
|
* |
11
|
|
|
* This program is distributed in the hope that it will be useful, |
12
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
13
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
14
|
|
|
* GNU General Public License for more details. |
15
|
|
|
* |
16
|
|
|
* You should have received a copy of the GNU General Public License |
17
|
|
|
* along with this program. If not, see <http://www.gnu.org/licenses/>. |
18
|
|
|
*/ |
19
|
|
|
|
20
|
|
|
namespace PhpGuard\Curl\RequestModifier; |
21
|
|
|
|
22
|
|
|
use PhpGuard\Curl\Collection\Headers; |
23
|
|
|
use PhpGuard\Curl\CurlRequest; |
24
|
|
|
|
25
|
|
|
class FileRequestModifier implements RequestModifierInterface |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* Modify a request. |
29
|
|
|
* |
30
|
|
|
* @param CurlRequest $request |
31
|
|
|
* |
32
|
|
|
* @return CurlRequest |
33
|
|
|
*/ |
34
|
13 |
|
public function modify(CurlRequest $request): CurlRequest |
35
|
|
|
{ |
36
|
13 |
|
$data = $request->getData(); |
37
|
13 |
|
$headers = $request->getHeaders(); |
38
|
|
|
|
39
|
13 |
|
if (is_array($data)) { |
40
|
5 |
|
if (!preg_match(Headers::CONTENT_TYPE_PATTERN_JSON, $headers[Headers::CONTENT_TYPE])) { |
41
|
5 |
|
$hasFile = false; |
42
|
5 |
|
foreach ($data as $key => $value) { |
43
|
5 |
|
if (is_string($value) && 0 === strpos($value, '@') && is_file(substr($value, 1))) { |
44
|
2 |
|
$hasFile = true; |
45
|
2 |
|
if (class_exists('CURLFile')) { |
46
|
2 |
|
$data[$key] = new \CURLFile(substr($value, 1)); |
47
|
|
|
} |
48
|
5 |
|
} elseif ($value instanceof \CURLFile) { |
49
|
5 |
|
$hasFile = true; |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
5 |
|
if ($hasFile) { |
54
|
3 |
|
$headers[Headers::CONTENT_TYPE] = Headers::CONTENT_TYPE_MULTIPART_FORM_DATA; |
55
|
|
|
} else { |
56
|
2 |
|
$headers[Headers::CONTENT_TYPE] = Headers::CONTENT_TYPE_FORM_URL_ENCODED; |
57
|
|
|
|
58
|
2 |
|
$data = http_build_query($data, '', '&'); |
59
|
|
|
} |
60
|
|
|
|
61
|
5 |
|
$request->setData($data); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
13 |
|
return $request; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|