Completed
Pull Request — master (#158)
by Fabien
10:04
created

Formatter::formatResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Http\HttplugBundle\Collector;
4
5
use Exception;
6
use Http\Client\Exception\HttpException;
7
use Http\Client\Exception\TransferException;
8
use Http\Message\Formatter as MessageFormatter;
9
use Http\Message\Formatter\CurlCommandFormatter;
10
use Psr\Http\Message\RequestInterface;
11
use Psr\Http\Message\ResponseInterface;
12
13
/**
14
 * This class is a decorator for any Http\Message\Formatter with the the ability to format exceptions and requests as
15
 * cURL commands.
16
 *
17
 * @author Fabien Bourigault <[email protected]>
18
 *
19
 * @internal
20
 */
21
class Formatter implements MessageFormatter
22
{
23
    /**
24
     * @var MessageFormatter
25
     */
26
    private $formatter;
27
28
    /**
29 6
     * @var CurlCommandFormatter
30
     */
31 6
    private $curlFormatter;
32 6
33
    /**
34
     * @param MessageFormatter     $formatter
35
     * @param CurlCommandFormatter $curlFormatter
36
     */
37
    public function __construct(MessageFormatter $formatter, CurlCommandFormatter $curlFormatter)
38
    {
39
        $this->formatter = $formatter;
40
        $this->curlFormatter = $curlFormatter;
41 3
    }
42
43 3
    /**
44 1
     * Formats an exception.
45
     *
46
     * @param Exception $exception
47 2
     *
48 1
     * @return string
49
     */
50
    public function formatException(Exception $exception)
51 1
    {
52
        if ($exception instanceof HttpException) {
53
            return $this->formatter->formatResponse($exception->getResponse());
54
        }
55
56
        if ($exception instanceof TransferException) {
57 1
            return sprintf('Transfer error: %s', $exception->getMessage());
58
        }
59 1
60
        return sprintf('Unexpected exception of type "%s": %s', get_class($exception), $exception->getMessage());
61
    }
62
63
    /**
64
     * {@inheritdoc}
65 1
     */
66
    public function formatRequest(RequestInterface $request)
67 1
    {
68
        return $this->formatter->formatRequest($request);
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function formatResponse(ResponseInterface $response)
75
    {
76
        return $this->formatter->formatResponse($response);
77
    }
78
79
    /**
80
     * Format a RequestInterface as a cURL command.
81
     *
82
     * @param RequestInterface $request
83
     *
84
     * @return string
85
     */
86
    public function formatAsCurlCommand(RequestInterface $request)
87
    {
88
        return $this->curlFormatter->formatRequest($request);
89
    }
90
}
91