Test Failed
Push — 0.3 ( c5ac0f...1929bf )
by Diego
02:49
created

Larachimp::setLog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php namespace DiegoCaprioli\Larachimp\Services;
2
3
use DiegoCaprioli\Larachimp\Traits\BasicLogging;
4
use \GuzzleHttp\Client;
5
use \Illuminate\Contracts\Logging\Log;
6
use \Illuminate\Support\Collection;
7
8
/**
9
 * Handles the basic interaction with Mailchimp v3 API
10
 */
11
class Larachimp {
12
13
    /**
14
     * Base URI for Mailchimp API v3
15
     *
16
     * @var string
17
     */
18
    protected $baseuri;
19
20
    /**
21
     * @var string
22
     */
23
    protected $apikey;
24
25
    /**
26
     * The connection options
27
     * @var array
28
     */
29
    protected $options;
30
31
    /**
32
     * @var \GuzzleHttp\Client
33
     */
34
    protected $client;   
35
36
    /**
37
     * Make this class use a logger and it's basic methods
38
     */
39
    use BasicLogging;
40
41
    /**
42
     * Creates a new Larachimp instance
43
     * 
44
     * @param Log The logger instance to use
45
     */
46
    public function __construct(Log $log = null)
47
    {
48
        $this->log = $log;
49
    }
50
51
    /**
52
     * Initializes the instance with the proper configuration values
53
     * 
54
     * @param  string $apikey The API key to the Mailchimp API
55
     * @param  string $baseuri The base URI to use for the requests. Make sure it has a trailing/ending "/"
56
     * @param  array $clientOptions The options array in the Guzzle Client expected format          *
57
     * @see http://guzzle3.readthedocs.io/docs.html Guzzle Docs
58
     */
59
    public function initialize($apikey = '', $baseuri = '', $clientOptions = [])
60
    {        
61
        $this->apikey = $apikey;
62
        $this->baseuri = $baseuri;
63
        $this->client = new Client($clientOptions);        
64
        $this->options['headers'] = [
65
            'Authorization' => 'apikey ' . $this->apikey
66
        ];
67
    }
68
69
    /**
70
     * If there's a logger defined, it logs the request made
71
     * 
72
     * @param  string $method
73
     * @param  string $resource
74
     * @param  array $options
75
     */
76
    protected function logRequest($method, $resource, array $options = [])
77
    {   
78
        $this->logInfo('Mailchimp API Request = ' . var_export([
79
            compact('resource', 'method', 'options')
80
        ], true));        
81
    }
82
83
84
    /**
85
     * If there's a logger defined, it logs the response returned
86
     * 
87
     * @param mixed $response
88
     */
89
    protected function logResponse($response)
90
    {
91
        $this->logInfo('Mailchimp API Response = ' . var_export($response, true));
92
    }
93
94
    /**
95
     * Makes a simple API request to Mailchimp. 
96
     * It uses the base URI used when initializing this service class, and 
97
     * concatenates the $resource to form the URL of the request.
98
     * The optional $options array are the standar Guzzle Client request options.
99
     * The request will automatically include an option setting the 'headers' to
100
     * use the Authorization API KEY as configured.
101
     * Finally calls the request method of the Guzzle client using $method, the 
102
     * generated URL of the request, and the $options.
103
     * 
104
     * @param  string $resource The resource
105
     * @param  string $method The request method (GET, POST, PATCH, PUT, DELETE)
106
     * @param  array $options An array of request options, as accepted by Guzzle Client request method
107
     * @return mixed The json_decode'd version of the response body 
108
     * @see http://developer.mailchimp.com/documentation/mailchimp/guides/get-started-with-mailchimp-api-3/ Mailchimp API v3 Reference
109
     * @see http://guzzle3.readthedocs.io/docs.html Guzzle Docs
110
     */
111
    public function request($method, $resource, array $options = [])
112
    {
113
114
        if (empty($this->apikey)) {
115
            throw new \Exception("You must initialize the Larachimp instance by calling the initialize() method before attempting any request.");
116
        }
117
118
        $options = array_merge($this->options, $options);
119
120
        $resource = $this->baseuri . $resource;
121
122
        $this->logRequest($method, $resource , $options);
123
124
        try {
125
            $response = $this->client->request($method, $resource, $options);
126
        } catch (\GuzzleHttp\Exception\ClientException $e) {
127
128
            $this->logError(
129
                "A \GuzzleHttp\Exception\ClientException has been thrown. Request: " .
130
                var_export($e->getRequest(), true) . 
131
                " - Response: " . var_export($e->getResponse()->getBody()->getContents(), true)
132
            );
133
            throw $e;            
134
        }
135
        
136
        $responseContents = $response->getBody()->getContents(); 
137
        $this->logResponse($responseContents);
138
        $decodedResponse = json_decode($responseContents);
139
        
140
        return $decodedResponse;
141
142
    }
143
144
145
146
}