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

Lift::getAccountAndSiteIdHandler()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 14
cts 14
cp 1
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 17
nc 1
nop 2
crap 2
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 117
    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 117
        if (!isset($config['base_uri']) && isset($config['base_url'])) {
52
            $config['base_uri'] = $config['base_url'];
53
        }
54
55
        // Setting up the headers.
56 117
        $config['headers']['Content-Type'] = 'application/json';
57
58
        // Create both unauthenticated and authenticated handler stacks.
59 117
        $handlerStack = isset($config['handler']) ? $config['handler'] : HandlerStack::create();
60 117
        $accountAndSiteIdHandler = $this->getAccountAndSiteIdHandler($account_id, $site_id);
61 117
        $handlerStack->push($accountAndSiteIdHandler, 'acquia_lift_account_and_site_ids');
62
63
        // Both stacks are cloned so they are both completely internal now.
64 117
        $unauthenticatedHandlerStack = clone $handlerStack;
65 117
        $authenticatedHandlerStack = clone $handlerStack;
66
67
        // Set an authentication handler accordingly.
68 117
        if (isset($config['auth_middleware'])) {
69 117
            if ($config['auth_middleware'] !== false) {
70 117
                $authenticatedHandlerStack->push($config['auth_middleware'], 'acquia_lift_hmac_auth');
71 78
            }
72 78
        } else {
73
            // A key consists of your UUID and a MIME base64 encoded shared secret.
74
            $authKey = new Key($public_key, $secret_key);
75
            $middleware = new HmacAuthMiddleware($authKey, 'Decision');
76
            $authenticatedHandlerStack->push($middleware, 'acquia_lift_hmac_auth');
77
        }
78
79
        // Create both unauthenticated and authenticated handlers.
80 117
        $config['handler'] = $unauthenticatedHandlerStack;
81 117
        $this->unauthenticatedClient = new Client($config);
82 117
        $config['handler'] = $authenticatedHandlerStack;
83 117
        $this->authenticatedClient = new Client($config);
84 117
    }
85
86
    /**
87
     * Get a handler that adds lift account id and site id.
88
     *
89
     * @param string $account_id The Lift Web Account Identifier. Eg.: MYACCOUNT
90
     * @param string $site_id    The Lift Web Site Identifier. Eg.: my-drupal-site
91
     * @return function The handler that adds Lift account id and site id
92
     */
93
    private function getAccountAndSiteIdHandler($account_id, $site_id)
94
    {
95
        // We cannot keep references in such functions.
96
        return function (callable $handler) use ($account_id, $site_id) {
97 99
            return function (
98
              RequestInterface $request,
99
              array $options
100
            ) use ($handler, $account_id, $site_id) {
101 99
                $auth_query = "account_id={$account_id}&site_id={$site_id}";
102 99
                $uri = $request->getUri();
103 99
                $query = $uri->getQuery();
104 99
                if (empty($query)) {
105 90
                    $query = $auth_query;
106 60
                } else {
107 9
                    $query = $query.'&'.$auth_query;
108
                }
109 99
                $uri = $uri->withQuery($query);
110 99
                $uri->withQuery($query);
111
112 99
                $request = $request->withUri($uri);
113
114 99
                return $handler($request, $options);
115 99
            };
116 117
        };
117
    }
118
119
    /**
120
     * Pings the service to ensure that it is available.
121
     *
122
     * @return mixed the value encoded in the JSON.
123
     */
124 3
    public function ping()
125
    {
126 3
        $request = new Request('GET', '/ping');
127 3
        $response = $this->authenticatedClient->send($request);
128 3
        $body = (string) $response->getBody();
129
130 3
        return json_decode($body, true);
131
    }
132
133
    /**
134
     * Get the Slot Manager.
135
     *
136
     * @return \Acquia\LiftClient\Manager\SlotManager
137
     */
138 24
    public function getSlotManager()
139
    {
140 24
        return new SlotManager($this->authenticatedClient);
141
    }
142
143
    /**
144
     * Get the Slot Manager.
145
     *
146
     * @return \Acquia\LiftClient\Manager\GoalManager
147
     */
148 27
    public function getGoalManager()
149
    {
150 27
        return new GoalManager($this->authenticatedClient);
151
    }
152
153
    /**
154
     * Get the Segment Manager.
155
     *
156
     * @return \Acquia\LiftClient\Manager\SegmentManager
157
     */
158 6
    public function getSegmentManager()
159
    {
160 6
        return new SegmentManager($this->authenticatedClient);
161
    }
162
163
    /**
164
     * Get the Rules Manager.
165
     *
166
     * @return \Acquia\LiftClient\Manager\RuleManager
167
     */
168 36
    public function getRuleManager()
169
    {
170 36
        return new RuleManager($this->authenticatedClient);
171
    }
172
173
    /**
174
     * Get the Capture Manager.
175
     *
176
     * @return \Acquia\LiftClient\Manager\CaptureManager
177
     */
178 12
    public function getCaptureManager()
179
    {
180 12
        return new CaptureManager($this->unauthenticatedClient);
181
    }
182
183
    /**
184
     * Get the Decide Manager.
185
     *
186
     * @return \Acquia\LiftClient\Manager\DecideManager
187
     */
188 9
    public function getDecideManager()
189
    {
190 9
        return new DecideManager($this->unauthenticatedClient);
191
    }
192
193
}
194