Passed
Push — master ( d59b53...8a6658 )
by Alexandre
09:22
created

DataRequestModifier   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 22
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
A modify() 0 13 4
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 DataRequestModifier 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 45
        if (is_array($data)) {
39 18
            if (preg_match(Headers::CONTENT_TYPE_PATTERN_JSON, $headers[Headers::CONTENT_TYPE])) {
40 3
                $request->setData(json_encode($data));
41 15
            } else if (!isset($headers[Headers::CONTENT_TYPE])) {
42 6
                $headers[Headers::CONTENT_TYPE] = Headers::CONTENT_TYPE_FORM_URL_ENCODED;
43 6
                $request->setData(http_build_query($data, '', '&'));
44
            }
45
        }
46 45
        return $request;
47
    }
48
}