Resource::throwException()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
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
     * Check if an integer is valid and positive
114
     *
115
     * @param  string      $name
116
     * @param  integer     $integer
117
     * @param  boolean     $positive
118
     * @throws Exception
119
     * @return boolean
120
     */
121
    protected function checkInteger($name, $integer, $positive = true)
122
    {
123
        $error = false;
124
125
        if (!is_integer($integer)) {
126
            $error = gettype($integer);
127
        }
128
129
        if ($positive && $integer <= 0) {
130
            $error = $integer;
131
        }
132
133
        if ($error) {
134
            $type = $positive ? 'a positive' : 'an';
135
            $this->throwException('Invalid ' . $name . ' specified: ' . $error . '. ' . ucfirst($name) . ' must be ' . $type . ' integer.');
136
        }
137
138
        return true;
139
    }
140
141
    /**
142
     * Convert most date/times to a timestamp
143
     *
144
     * @param  mixed  $date
145
     * @param  string $format
146
     * @return int
147
     */
148
    protected function getDate($date, $format = 'U')
149
    {
150
        // If date isn't a timestamp convert it to a timestamp
151
        if (!is_int($date)) {
152
            $date = strtotime($date);
153
        }
154
155
        return date($format, $date);
156
    }
157
158
    /**
159
     * Log a critical message and throw an exception
160
     *
161
     * @param  string      $message
162
     * @throws Exception
163
     * @return void
164
     */
165
    protected function throwException($message)
166
    {
167
        // Add critical log before throwing exception
168
        $this->addLog('critical', get_class($this) . ': ' . $message);
169
        throw new Exception($message);
170
    }
171
172
    /**
173
     * Send a request to the API endpoint and return json response
174
     *
175
     * @param  string                               $uri
176
     * @param  string                               $method
177
     * @throws GuzzleHttp\Exception\ClientException Exception thrown by Guzzle
178
     * @return string
179
     */
180
    protected function request($uri, $method = 'GET')
181
    {
182
        $guzzle = new GuzzleClient(['base_uri' => $this->apiUrl]);
183
        $params = ['headers' => ['X-Api-Key' => $this->apiKey]];
184
185
        if (count($this->data)) {
186
            $params['form_params'] = $this->data;
187
        }
188
189
        $this->addLog('debug', "Calling {$this->apiUrl}$uri using $method", $params);
190
191
        return $guzzle->request($method, $uri, $params)->getBody();
192
    }
193
}
194