Completed
Push — master ( a8cb62...764ba2 )
by François
03:52
created

SimpleClient::request()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 26
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 26
rs 8.5806
cc 4
eloc 19
nc 8
nop 3
1
<?php
2
3
/*
4
 * This file is part of the Bouncer package.
5
 *
6
 * (c) François Hodierne <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Bouncer\Http;
13
14
class SimpleClient
15
{
16
17
    protected $apiKey;
18
19
    protected $timeout = 2;
20
21
    public function __construct($apiKey = null)
22
    {
23
        $this->apiKey = $apiKey;
24
    }
25
26
    public function request($method, $url, $data = null)
27
    {
28
        $options = array(
29
            'http' => array(
30
                'timeout' => $this->timeout,
31
                'method'  => $method,
32
                'header'  => "User-Agent: Bouncer Http\r\n"
33
            )
34
        );
35
        if ($this->apiKey) {
36
            $options['http']['header'] .= "Api-Key: {$this->apiKey}\r\n";
37
        }
38
        if ($data) {
39
            $content = json_encode($data);
40
            $length = strlen($content);
41
            $options['http']['header'] .= "Content-Type: application/json\r\n";
42
            $options['http']['header'] .= "Content-Length: {$length}\r\n";
43
            $options['http']['content'] = $content;
44
        }
45
        $context = stream_context_create($options);
46
        $result = @file_get_contents($url, false, $context);
47
        if ($result) {
48
            $response = json_decode($result, true);
49
            return $response;
50
        }
51
    }
52
53
    public function get($url)
54
    {
55
        return self::request('GET', $url);
56
    }
57
58
    public function post($url, $data = null)
59
    {
60
        return self::request('POST', $url, $data);
61
    }
62
63
}
64