FileRequestModifier   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 33
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0
wmc 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B modify() 0 24 10
1
<?php
2
/**
3
 * php-guard/curl <https://github.com/php-guard/curl>
4
 * Copyright (C) ${YEAR} 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 45
    public function modify(CurlRequest $request): CurlRequest
35
    {
36 45
        $data = $request->getData();
37 45
        $headers = $request->getHeaders();
38
39 45
        if (is_array($data) && !preg_match(Headers::CONTENT_TYPE_PATTERN_JSON, $headers[Headers::CONTENT_TYPE])) {
40 15
            $hasFile = false;
41 15
            foreach ($data as $key => $value) {
42 15
                if (is_string($value) && 0 === strpos($value, '@') && is_file(substr($value, 1))) {
43 6
                    $hasFile = true;
44 6
                    if (class_exists('CURLFile')) {
45 6
                        $data[$key] = new \CURLFile(substr($value, 1));
46
                    }
47 15
                } else if ($value instanceof \CURLFile) {
48 15
                    $hasFile = true;
49
                }
50
            }
51 15
            if ($hasFile) {
52 9
                $headers[Headers::CONTENT_TYPE] = Headers::CONTENT_TYPE_MULTIPART_FORM_DATA;
53
            }
54 15
            $request->setData($data);
55
        }
56
57 45
        return $request;
58
    }
59
}
60