Completed
Push — master ( 8a5482...34c135 )
by Robert
13:32 queued 11:17
created

HttpPlugHttpAdapterClient::createBody()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
ccs 17
cts 17
cp 1
rs 8.5125
cc 5
eloc 14
nc 5
nop 4
crap 5
1
<?php
2
3
namespace Rs\VersionEye\Http;
4
5
use Http\Client\Common\HttpMethodsClient;
6
use Http\Client\Exception\HttpException as PlugException;
7
use Http\Client\HttpClient as PlugClient;
8
use Http\Discovery\MessageFactoryDiscovery;
9
use Http\Discovery\StreamFactoryDiscovery;
10
use Http\Message\MultipartStream\MultipartStreamBuilder;
11
use Psr\Http\Message\RequestInterface;
12
13
/**
14
 * HttpPlugHttpAdapterClient.
15
 *
16
 * @author Robert Schönthal <[email protected]>
17
 */
18
class HttpPlugHttpAdapterClient implements HttpClient
19
{
20
    /**
21
     * @var HttpMethodsClient
22
     */
23
    private $adapter;
24
25
    private $url;
26
27
    /**
28
     * @param PlugClient $adapter
29
     * @param string     $url
30
     */
31 13
    public function __construct(PlugClient $adapter, $url)
32
    {
33 13
        $this->adapter = $adapter;
0 ignored issues
show
Documentation Bug introduced by
$adapter is of type object<Http\Client\HttpClient>, but the property $adapter was declared to be of type object<Http\Client\Common\HttpMethodsClient>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
34 13
        $this->url     = $url;
35 13
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 5
    public function request($method, $path, array $params = [])
41
    {
42 5
        list($params, $files) = $this->splitParams($params);
43 5
        $url                  = $this->url . $path;
44
45
        try {
46 5
            $request  = $this->createBody($params, $files, $method, $url);
47 5
            $response = $request ? $this->adapter->sendRequest($request) : $this->adapter->send($method, $url);
48
49 4
            return json_decode($response->getBody(), true);
50 1
        } catch (PlugException $e) {
51 1
            throw $this->buildRequestError($e);
52
        }
53
    }
54
55
    /**
56
     * splits arguments into parameters and files (if any).
57
     *
58
     * @param array $params
59
     *
60
     * @return array
61
     */
62 5
    private function splitParams(array $params)
63
    {
64 5
        $parameters = [];
65 5
        $files      = [];
66
67 5
        foreach ($params as $name => $value) {
68 2
            if (is_readable($value)) { //file
69 1
                $files[$name] = $value;
70 1
            } else {
71 2
                $parameters[$name] = $value;
72
            }
73 5
        }
74
75 5
        return [$parameters, $files];
76
    }
77
78
    /**
79
     * builds the error exception.
80
     *
81
     * @param PlugException $e
82
     *
83
     * @return CommunicationException
84
     */
85 1
    private function buildRequestError(PlugException $e)
86
    {
87 1
        $data    = $e->getResponse() ? json_decode($e->getResponse()->getBody(), true) : ['error' => $e->getMessage()];
88 1
        $message = isset($data['error']) ? $data['error'] : 'Server Error';
89 1
        $status  = $e->getResponse() ? $e->getResponse()->getStatusCode() : 500;
90
91 1
        return new CommunicationException(sprintf('%s : %s', $status, $message));
92
    }
93
94
    /**
95
     * @param array  $params
96
     * @param array  $files
97
     * @param string $method
98
     * @param string $url
99
     *
100
     * @return null|RequestInterface
101
     */
102 5
    private function createBody(array $params, array $files, $method, $url)
103
    {
104 5
        if (!count($params) && !count($files)) {
105 3
            return;
106
        }
107
108 2
        $streamFactory = StreamFactoryDiscovery::find();
109 2
        $builder       = new MultipartStreamBuilder($streamFactory);
110
111 2
        foreach ($params as $k => $v) {
112 2
            $builder->addResource($k, $v);
113 2
        }
114
115 2
        foreach ($files as $k => $file) {
116 1
            $builder->addResource($k, fopen($file, 'r'), ['filename' => $file]);
117 2
        }
118
119 2
        return MessageFactoryDiscovery::find()->createRequest(
120 2
            $method,
121 2
            $url,
122 2
            ['Content-Type' => 'multipart/form-data; boundary=' . $builder->getBoundary()],
123 2
            $builder->build()
124 2
        );
125
    }
126
}
127