CurlFormatter::formatForCurl()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Nixilla\Api\LoggerBundle\Twig;
4
5
use Twig\Extension\AbstractExtension;
6
use Twig\TwigFilter;
7 1
8
class CurlFormatter extends AbstractExtension
9 1
{
10
    public function getName()
11
    {
12 1
        return 'nixilla_api_logger';
13
    }
14
15 1
    public function getFilters()
16
    {
17
        return array(
18
            new TwigFilter('format_curl_command', array($this, 'formatForCurl'))
19 1
        );
20
    }
21 1
22 1
    public function formatForCurl(array $singleCall)
23 1
    {
24 1
        return sprintf(
25 1
            'curl -v -X %s%s %s%s%s',
26 1
            $singleCall['method'],
27 1
            $this->generateHeaders($singleCall['request_headers']),
28
            $singleCall['host'],
29
            $singleCall['path'],
30
            $this->formatParams($singleCall)
31 1
        );
32
    }
33 1
34
    private function generateHeaders($request_headers)
35 1
    {
36
        $output = '';
37 1
38
        foreach($request_headers as $key => $value)
39
        {
40 1
            $output .= sprintf(' -H "%s: %s"', $key, is_array($value) ? $value[0] : $value);
41
        }
42
43 1
        return $output;
44
    }
45 1
46
    private function formatParams($singleCall)
47 1
    {
48
        if($singleCall['method'] != 'GET')
49 1
        {
50
            foreach($singleCall['request_headers'] as $key => $value)
51 1
            {
52
                if($key == 'Content-Type' && (is_array($value) ? $value[0] : $value) ==  'application/json')
53
                {
54
                    return sprintf(" --data '%s'", json_encode($singleCall['params']));
55 1
                }
56
            }
57
58
            return sprintf(" --data '%s'", http_build_query($singleCall['params']));
59 1
        }
60
        else
61
        {
62
            return '';
63
        }
64
    }
65
}
66