Completed
Pull Request — master (#14)
by Nick
05:32
created

Lift::__construct()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 41
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7.3329

Importance

Changes 0
Metric Value
dl 0
loc 41
ccs 14
cts 21
cp 0.6667
rs 8.439
c 0
b 0
f 0
cc 6
eloc 22
nc 12
nop 5
crap 7.3329
1
<?php
2
3
namespace Acquia\LiftClient;
4
5
use Acquia\LiftClient\Manager\CaptureManager;
6
use Acquia\LiftClient\Manager\RuleManager;
7
use Acquia\LiftClient\Manager\SegmentManager;
8
use Acquia\LiftClient\Manager\SlotManager;
9
use Acquia\LiftClient\Manager\GoalManager;
10
use NickVeenhof\Hmac\Guzzle\HmacAuthMiddleware;
11
use NickVeenhof\Hmac\Key;
12
use GuzzleHttp\Client;
13
use GuzzleHttp\HandlerStack;
14
use GuzzleHttp\Psr7\Request;
15
use Psr\Http\Message\RequestInterface;
16
17
class Lift extends Client
18
{
19
    /**
20
     * @var \NickVeenhof\Hmac\KeyInterface A sample key
21
     */
22
    protected $authKey;
23
24
    /**
25
     * @var string The account we are using
26
     */
27
    protected $accountId;
28
29
    /**
30
     * @var string The site identifier we are using
31
     */
32
    protected $siteId;
33
34
    /**
35
     * Overrides \GuzzleHttp\Client::__construct().
36
     *
37
     * @param string $account_id The Lift Web Account Identifier. Eg.: MYACCOUNT
38
     * @param string $site_id    The Lift Web Site Identifier. Eg.: my-drupal-site
39
     * @param string $public_key The Lift Web Public Key. Not all API keys have
40
     *                           the same permissions so be mindful which key
41
     *                           you are using
42
     * @param string $secret_key The Lift Web Secret Key belonging to the Public
43
     *                           Key
44
     * @param array  $config
45
     */
46 60
    public function __construct(
47
      $account_id,
48
      $site_id,
49
      $public_key,
50
      $secret_key,
51
      array $config = []
52
    ) {
53
        // "base_url" parameter changed to "base_uri" in Guzzle6, so the following line
54
        // is there to make sure it does not disrupt previous configuration.
55 60
        if (!isset($config['base_uri']) && isset($config['base_url'])) {
56
            $config['base_uri'] = $config['base_url'];
57
        }
58
59
        // Setting up the headers.
60 60
        $config['headers']['Content-Type'] = 'application/json';
61
62
        // A key consists of your UUID and a MIME base64 encoded shared secret.
63 60
        $this->authKey = new Key($public_key, $secret_key);
64
65 60
        $this->accountId = $account_id;
66 60
        $this->siteId = $site_id;
67
68
        // Set our default HandlerStack if nothing is provided
69 60
        if (!isset($config['handler'])) {
70
            $config['handler'] = HandlerStack::create();
71
        }
72
73
        // Add our Account and Site identifiers.
74 60
        $config['handler']->push($this->addLiftAccountAndSiteId());
75
76 60
        if (isset($config['auth_middleware'])) {
77 60
            if ($config['auth_middleware'] !== false) {
78 20
                $config['handler']->push($config['auth_middleware']);
79
            }
80 40
        } else {
81
            $middleware = new HmacAuthMiddleware($this->authKey, 'Decision');
82
            $config['handler']->push($middleware);
83
        }
84
85 60
        parent::__construct($config);
86 60
    }
87
88 60
    public function addLiftAccountAndSiteId()
89
    {
90
        // We cannot keep references in such functions.
91 60
        $account_id = $this->accountId;
92 60
        $site_id = $this->siteId;
93
94
        return function (callable $handler) use ($account_id, $site_id) {
95 60
            return function (
96
              RequestInterface $request,
97
              array $options
98
            ) use ($handler, $account_id, $site_id) {
99 60
                $auth_query = "account_id={$account_id}&site_id={$site_id}";
100 60
                $uri = $request->getUri();
101 60
                $query = $uri->getQuery();
102 60
                if (empty($query)) {
103 60
                    $query = $auth_query;
104 40
                } else {
105
                    $query = $query.'&'.$auth_query;
106
                }
107 60
                $uri = $uri->withQuery($query);
108 60
                $uri->withQuery($query);
109
110 60
                $request = $request->withUri($uri);
111
112 60
                return $handler($request, $options);
113 60
            };
114 60
        };
115
    }
116
117
    /**
118
     * Pings the service to ensure that it is available.
119
     *
120
     * @return \Psr\Http\Message\ResponseInterface
121
     *
122
     * @throws \GuzzleHttp\Exception\RequestException
123
     */
124 3
    public function ping()
125
    {
126
        // Now make the request.
127 3
        $request = new Request('GET', '/ping');
128
129 3
        return $this->getResponseJson($request);
130
    }
131
132
    /**
133
     * Get the Slot Manager.
134
     *
135
     * @return \Acquia\LiftClient\Manager\SlotManager
136
     */
137 24
    public function getSlotManager()
138
    {
139 24
        return new SlotManager($this);
140
    }
141
142
    /**
143
     * Get the Slot Manager.
144
     *
145
     * @return \Acquia\LiftClient\Manager\GoalManager
146
     */
147 27
    public function getGoalManager()
148
    {
149 27
        return new GoalManager($this);
150
    }
151
152
    /**
153
     * Get the Segment Manager.
154
     *
155
     * @return \Acquia\LiftClient\Manager\SegmentManager
156
     */
157 6
    public function getSegmentManager()
158
    {
159 6
        return new SegmentManager($this);
160
    }
161
162
    /**
163
     * Get the Rules Manager.
164
     *
165
     * @return \Acquia\LiftClient\Manager\RuleManager
166
     */
167
    public function getRuleManager()
168
    {
169
        return new RuleManager($this);
170
    }
171
172
    /**
173
     * Get the Capture Manager.
174
     *
175
     * @return \Acquia\LiftClient\Manager\CaptureManager
176
     */
177
    public function getCaptureManager()
178
    {
179
        return new CaptureManager($this);
180
    }
181
182
    /**
183
     * Make the given Request and return as JSON Decoded PHP object.
184
     *
185
     * @param RequestInterface $request
186
     *
187
     * @return mixed the value encoded in <i>json</i> in appropriate
188
     *               PHP type. Values true, false and
189
     *               null (case-insensitive) are returned as <b>TRUE</b>, <b>FALSE</b>
190
     *               and <b>NULL</b> respectively. <b>NULL</b> is returned if the
191
     *               <i>json</i> cannot be decoded or if the encoded
192
     *               data is deeper than the recursion limit
193
     *
194
     * @throws \GuzzleHttp\Exception\RequestException
195
     */
196 48
    public function getResponseJson(RequestInterface $request)
197
    {
198 48
        $response = $this->send($request);
199 27
        $body = (string) $response->getBody();
200
201 27
        return json_decode($body, true);
202
    }
203
}
204