Completed
Push — master ( 764ba2...8d4dc4 )
by François
03:10
created

SimpleClient::setApiKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
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
        if ($apiKey) {
24
            $this->setApiKey($apiKey);
25
        }
26
    }
27
28
    public function setApiKey($apiKey)
29
    {
30
        $this->apiKey = $apiKey;
31
    }
32
33
    public function request($method, $url, $data = null)
34
    {
35
        $options = array(
36
            'http' => array(
37
                'timeout' => $this->timeout,
38
                'method'  => $method,
39
                'header'  => "User-Agent: Bouncer Http\r\n"
40
            )
41
        );
42
        if ($this->apiKey) {
43
            $options['http']['header'] .= "Api-Key: {$this->apiKey}\r\n";
44
        }
45
        if ($data) {
46
            $content = json_encode($data);
47
            $length = strlen($content);
48
            $options['http']['header'] .= "Content-Type: application/json\r\n";
49
            $options['http']['header'] .= "Content-Length: {$length}\r\n";
50
            $options['http']['content'] = $content;
51
        }
52
        $context = stream_context_create($options);
53
        $result = @file_get_contents($url, false, $context);
54
        if ($result) {
55
            $response = json_decode($result, true);
56
            return $response;
57
        }
58
    }
59
60
    public function get($url)
61
    {
62
        return self::request('GET', $url);
63
    }
64
65
    public function post($url, $data = null)
66
    {
67
        return self::request('POST', $url, $data);
68
    }
69
70
}
71