Completed
Push — master ( a109a6...b70d56 )
by Scott
02:12
created

Resource::request()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 2
1
<?php
2
3
namespace Sjdaws\NewRelicApi;
4
5
use Exception;
6
use GuzzleHttp\Client as GuzzleClient;
7
use Monolog\Logger;
8
9
abstract class Resource
10
{
11
    /**
12
     * The API key used to access the New Relic API, should be an admin or REST api key
13
     * @see https://docs.newrelic.com/docs/apis/rest-api-v2/requirements/api-keys
14
     *
15
     * @param string
16
     */
17
    protected $apiKey;
18
19
    /**
20
     * The endpoint requests will be sent to
21
     * @see https://docs.newrelic.com/docs/apis/rest-api-v2/requirements/new-relic-rest-api-v2-getting-started#appid
22
     *
23
     * @param string
24
     */
25
    private $apiUrl = 'https://api.newrelic.com/v2/';
26
27
    /**
28
     * Payload to be sent with the request
29
     *
30
     * @param array
31
     */
32
    private $data = [];
33
34
    /**
35
     * Monolog instance to be used for logging messages
36
     *
37
     * @param Logger
38
     */
39
    protected $logger;
40
41
    /**
42
     * Create a new resource instance
43
     *
44
     * @param string $apiKey
45
     * @param Logger $logger
46
     */
47
    public function __construct($apiKey, Logger $logger = null)
48
    {
49
        $this->apiKey = $apiKey;
50
        $this->logger = $logger;
51
    }
52
53
    /**
54
     * Add some data to the payload to be sent with the request
55
     *
56
     * @param  string $name
57
     * @param  mixed  $value
58
     * @return void
59
     */
60
    public function addData($name, $value)
61
    {
62
        $this->data[$name] = $value;
63
    }
64
65
    /**
66
     * Log a message
67
     *
68
     * @param  string $type
69
     * @param  string $message
70
     * @param  array  $data
71
     * @return void
72
     */
73
    protected function addLog($type, $message, array $data = [])
74
    {
75
        $type = mb_strtolower($type);
76
77
        // If we don't have a logger instance return to prevent fatal error
78
        if (!$this->logger instanceof Logger) {
79
            return;
80
        }
81
82
        // Make sure the type is valid
83
        if (!in_array($type, ['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency'])) {
84
            return;
85
        }
86
87
        $this->logger->$type($message, $data);
88
    }
89
90
    /**
91
     * Check a string is valid and within a set length
92
     *
93
     * @param  string      $name
94
     * @param  string      $string
95
     * @param  integer     $length
96
     * @throws Exception
97
     * @return boolean
98
     */
99
    protected function checkString($name, $string, $length = 0)
100
    {
101
        if (!is_string($string)) {
102
            $this->throwException('Invalid ' . $name . ' used: ' . gettype($string) . '. Must be a string.');
103
        }
104
105
        if ($length > 0 && mb_strlen($string) > $length) {
106
            $this->throwException(ucfirst($name) . ' is too long: ' . mb_strlen($string) . ' characters. ' . ucfirst($name) . ' can not be longer than ' . $length . ' characters.');
107
        }
108
109
        return true;
110
    }
111
112
    /**
113
     * Convert most date/times to a timestamp
114
     *
115
     * @param  mixed  $date
116
     * @param  string $format
117
     * @return int
118
     */
119
    protected function getDate($date, $format = 'U')
120
    {
121
        // If date isn't a timestamp convert it to a timestamp
122
        if (!is_int($date)) {
123
            $date = strtotime($date);
124
        }
125
126
        return date($format, $date);
127
    }
128
129
    /**
130
     * Log a critical message and throw an exception
131
     *
132
     * @param  string      $message
133
     * @throws Exception
134
     * @return void
135
     */
136
    protected function throwException($message)
137
    {
138
        // Add critical log before throwing exception
139
        $this->addLog('critical', get_class($this) . ': ' . $message);
140
        throw new Exception($message);
141
    }
142
143
    /**
144
     * Send a request to the API endpoint and return json response
145
     *
146
     * @param  string                               $uri
147
     * @param  string                               $method
148
     * @throws GuzzleHttp\Exception\ClientException Exception thrown by Guzzle
149
     * @return string
150
     */
151
    protected function request($uri, $method = 'GET')
152
    {
153
        $guzzle = new GuzzleClient(['base_uri' => $this->apiUrl]);
154
        $params = ['headers' => ['X-Api-Key' => $this->apiKey]];
155
156
        if (count($this->data)) {
157
            $params['form_params'] = $this->data;
158
        }
159
160
        $this->addLog('debug', "Calling {$this->apiUrl}$uri using $method", $params);
161
162
        return $guzzle->request($method, $uri, $params)->getBody();
163
    }
164
}
165