Completed
Push — master ( 6054f8...3b037a )
by Matthias
24:24
created

Api::exec()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 1
eloc 6
nc 1
nop 1
1
<?php
2
3
namespace Cauditor;
4
5
/**
6
 * @author Matthias Mullie <[email protected]>
7
 * @copyright Copyright (c) 2016, Matthias Mullie. All rights reserved.
8
 * @license LICENSE MIT
9
 */
10
class Api
11
{
12
    /**
13
     * @var string
14
     */
15
    protected $api;
16
17
    /**
18
     * @param string $api
19
     */
20
    public function __construct($api)
21
    {
22
        $this->api = $api;
23
    }
24
25
    /**
26
     * Read data from cauditor API.
27
     *
28
     * @param string $uri
29
     *
30
     * @return string|bool API response (on success) or false (on failure)
31
     */
32
    public function get($uri)
33
    {
34
        $options = array(
35
            CURLOPT_URL => $this->api . $uri,
36
            CURLOPT_FOLLOWLOCATION => 1,
37
            CURLOPT_RETURNTRANSFER => 1,
38
        );
39
40
        return $this->exec($options);
41
    }
42
43
    /**
44
     * Submit the data to cauditor API.
45
     *
46
     * @param string $uri
47
     * @param array  $data
48
     *
49
     * @return string|bool API response (on success) or false (on failure)
50
     */
51
    public function put($uri, array $data)
52
    {
53
        // PUT requests need an fopen wrapper, so we'll create a temporary one
54
        // for the data to submit...
55
        $json = json_encode($data);
56
        $file = fopen('php://temp', 'w+');
57
        fwrite($file, $json, strlen($json));
58
        fseek($file, 0);
59
60
        $options = array(
61
            CURLOPT_URL => $this->api . $uri,
62
            CURLOPT_FOLLOWLOCATION => 1,
63
            CURLOPT_RETURNTRANSFER => 1,
64
            CURLOPT_PUT => 1,
65
            CURLOPT_INFILE => $file,
66
            CURLOPT_INFILESIZE => strlen($json),
67
        );
68
69
        $result = $this->exec($options);
70
71
        fclose($file);
72
73
        return $result;
74
    }
75
76
    /**
77
     * @param array $options array of CURLOPT_* options
78
     *
79
     * @return string|bool API response (on success) or false (on failure)
80
     */
81
    protected function exec($options)
82
    {
83
        $curl = curl_init();
84
        curl_setopt_array($curl, $options);
85
        $result = curl_exec($curl);
86
        curl_close($curl);
87
88
        return $result;
89
    }
90
}
91