Completed
Pull Request — master (#19)
by Yuan
02:10
created

Lift::getResponseJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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