Passed
Push — master ( 2b7bb3...0db2dd )
by Clint A
06:52
created

AlmaApi::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Service;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\GuzzleException;
7
use Psr\Log\LoggerInterface;
8
9
class AlmaApi
10
{
11
    private $logger;
12
13
    public function __construct(LoggerInterface $logger)
14
    {
15
        $this->logger = $logger;
16
    }
17
18
    /**
19
     * Wrapper for requests to Alma API
20
     *
21
     * @param $urlPath
22
     * @param $method
23
     * @param $requestParams
24
     * @param $templateParamNames
25
     * @param $templateParamValues
26
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
27
     * @throws GuzzleException
28
     */
29
    protected function executeApiRequest($urlPath, $method, $requestParams, $templateParamNames, $templateParamValues)
30
    {
31
        $client = new Client(['base_uri' => getenv('API_URL')]);
32
33
        $url = str_replace($templateParamNames, $templateParamValues, $urlPath);
34
        $defaultRequestParams = [
35
            'headers' => [
36
                'Authorization' => 'apikey ' . getenv('API_KEY'),
37
            ]
38
        ];
39
40
        try {
41
            $response = $client->request($method, $url, array_merge_recursive($requestParams, $defaultRequestParams));
42
        } catch(\Exception $e) {
43
            $this->logger->emergency("@web-irt-dev Critical Error: Unable to reach the Alma API! :fire:");
44
            throw $e;
45
        }
46
47
        return $response;
48
    }
49
50
    /**
51
     * Get the users list of fees from Alma
52
     *
53
     * @param $userId
54
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
55
     * @throws GuzzleException
56
     */
57
    public function getUserFees($userId)
58
    {
59
        $method = 'GET';
60
        $urlPath = '/almaws/v1/users/{user_id}/fees';
61
        $templateParamNames = array('{user_id}');
62
        $templateParamValues = array(urlencode($userId));
63
        $query = [
64
            'user_id_type' => 'all_unique',
65
            'status' => 'ACTIVE'
66
        ];
67
        $requestParams = compact('query');
68
69
        return $this->executeApiRequest($urlPath, $method, $requestParams, $templateParamNames, $templateParamValues);
70
    }
71
72
    /**
73
     * Get the user from alma by the user id. Returns 400 status code if user does not exist.
74
     *
75
     * @param $userId
76
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
77
     * @throws GuzzleException
78
     */
79
    public function getUserById($userId)
80
    {
81
        $method = 'GET';
82
        $urlPath = '/almaws/v1/users/{user_id}';
83
        $templateParamNames = array('{user_id}');
84
        $templateParamValues = array(urlencode($userId));
85
        $query = [
86
            'user_id_type' => 'all_unique',
87
            'view' => 'full',
88
            'expand' => 'none'
89
        ];
90
        $requestParams = compact('query');
91
92
        return $this->executeApiRequest($urlPath, $method, $requestParams, $templateParamNames, $templateParamValues);
93
    }
94
95
    /**
96
     * Use the Alma api to search for the user by primary_id.
97
     * This is how we will check that a the provided user id is found in Alma as a primary_id.
98
     *
99
     * @param $userId
100
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
101
     * @throws GuzzleException
102
     */
103
    public function findUserById($userId)
104
    {
105
        $method = 'GET';
106
        $urlPath = '/almaws/v1/users';
107
        $templateParamNames = array();
108
        $templateParamValues = array();
109
        $query = [
110
            'limit' => '10',
111
            'offset' => '0',
112
            'q' => 'primary_id~' . $userId,
113
            'order_by' => 'last_name first_name, primary_id'
114
        ];
115
        $requestParams = compact('query');
116
117
        return $this->executeApiRequest($urlPath, $method, $requestParams, $templateParamNames, $templateParamValues);
118
    }
119
120
    /**
121
     * @param string $userId The alphanumeric userId of the logged in user
122
     * @param string $feeId The Alma specific fee id to be updated
123
     * @param $amount
124
     * @param string $method
125
     * @param null $externalTransactionId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $externalTransactionId is correct as it would always require null to be passed?
Loading history...
126
     * @param null $comment
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $comment is correct as it would always require null to be passed?
Loading history...
127
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
128
     * @throws GuzzleException
129
     */
130
    public function payUserFee($userId, $feeId, $amount, $method = 'ONLINE', $externalTransactionId = null, $comment = null)
131
    {
132
        $queryParams = [
133
            'op' => 'pay',
134
            'amount' => $amount,
135
            'method' => $method,
136
            'external_transaction_id' => $externalTransactionId,
137
            'comment' => $comment,
138
        ];
139
        /**
140
         * " If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed."
141
         * - http://php.net/array_filter
142
         */
143
        $queryParams = array_filter($queryParams);
144
145
        return $this->updateUserFee($userId, $feeId, $queryParams);
146
    }
147
148
    /**
149
     * @param string $userId The alphanumeric userId of the logged in user
150
     * @param string $feeId The Alma specific fee id to be updated
151
     * @param array $query The parameters for the query.
152
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
153
     * @throws GuzzleException
154
     */
155
    protected function updateUserFee($userId, $feeId, $query)
156
    {
157
        $method = 'POST';
158
        $urlPath = '/almaws/v1/users/{user_id}/fees/{fee_id}';
159
        $templateParamNames = array('{user_id}', '{fee_id}');
160
        $templateParamValues = array(urlencode($userId), urlencode($feeId));
161
        $requestParams = compact('query');
162
163
        return $this->executeApiRequest($urlPath, $method, $requestParams, $templateParamNames, $templateParamValues);
164
    }
165
166
    /**
167
     * @param string $userId The alphanumeric userId of the logged in user
168
     * @param mixed $body A plain PHP object representing a fee.
169
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
170
     * @throws GuzzleException
171
     */
172
    public function createUserFee($userId, $body)
173
    {
174
        $method = 'POST';
175
        $urlPath = '/almaws/v1/users/{user_id}/fees';
176
        $templateParamNames = array('{user_id}');
177
        $templateParamValues = array(urlencode($userId));
178
179
        $headers = [
180
            'Content-Type' => 'application/json'
181
        ];
182
        $body = json_encode($body);
183
        $requestParams = compact('body', 'headers');
184
185
        return $this->executeApiRequest($urlPath, $method, $requestParams, $templateParamNames, $templateParamValues);
186
    }
187
188
    /**
189
     * @param string $userId The alphanumeric userId of the logged in user
190
     * @param string $userPassword The alphanumeric userPassword of the logged in user
191
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
192
     * @throws GuzzleException
193
     */
194
    public function authenticateUser($userId, $userPassword)
195
    {
196
        $method = 'POST';
197
        $urlPath = '/almaws/v1/users/{user_id}';
198
        $templateParamNames = array('{user_id}');
199
        $templateParamValues = array(urlencode($userId));
200
        $query = [
201
            'user_id_type' => 'all_unique',
202
            'op' => 'auth'
203
        ];
204
205
        $headers = [
206
            'Exl-User-Pw' => $userPassword
207
        ];
208
        $requestParams = compact('query', 'headers');
209
210
        return $this->executeApiRequest($urlPath, $method, $requestParams, $templateParamNames, $templateParamValues);
211
    }
212
}
213