Glpi\Api\Rest\Client: lines coverage

73% of 64

Lines
Method Lines Line %
Glpi\Api\Rest\Client::__construct() 3 100%
Glpi\Api\Rest\Client::setAppToken() 2 0%
Glpi\Api\Rest\Client::initSessionByCredentials() 6 67%
Glpi\Api\Rest\Client::initSessionByUserToken() 6 0%
Glpi\Api\Rest\Client::killSession() 5 100%
Glpi\Api\Rest\Client::request() 19 68%
Glpi\Api\Rest\Client::getFullSession() 2 100%
Glpi\Api\Rest\Client::getGlpiConfig() 2 100%
Glpi\Api\Rest\Client::addTokens() 6 83%
Glpi\Api\Rest\Client::recoveryPassword() 4 100%
Glpi\Api\Rest\Client::resetPassword() 9 100%
#
1
<?php
2
/**
3
 * --------------------------------------------------------------------
4
 *
5
 * LICENSE
6
 *
7
 * This file is part of the GLPI API Client Library for PHP,
8
 * a subproject of GLPI. GLPI is a free IT Asset Management.
9
 *
10
 * GLPI is free software: you can redistribute it and/or
11
 * modify it under the terms of the GNU General Public License
12
 * as published by the Free Software Foundation; either version 3
13
 * of the License, or (at your option) any later version.
14
 *
15
 * GLPI is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 * --------------------------------------------------------------------
20
 * @author    Domingo Oropeza - <doropeza@teclib.com>
21
 * @copyright (C) 2017 Teclib' and contributors.
22
 * @license   GPLv3 https://www.gnu.org/licenses/gpl-3.0.html
23
 * @link      https://github.com/glpi-project/php-library-glpi
24
 * @link      http://www.glpi-project.org/
25
 * --------------------------------------------------------------------
26
 */
27

                    
28
namespace Glpi\Api\Rest;
29

                    
30
use GuzzleHttp\Client as HttpClient;
31
use Exception;
32
use Glpi\Api\Rest\Exception\InsufficientArgumentsException;
33
use GuzzleHttp\Exception\ClientException;
34
use GuzzleHttp\Exception\RequestException;
35

                    
36
/**
37
 * Class Client
38
 * @package Glpi\Api\Rest
39
 */
40
class Client {
41

                    
42
   /** @var HttpClient instance of the HTTP client */
43
   private $httpClient = null;
44

                    
45
   /** @var string URL to the GLPI API rest */
46
   private $url;
47

                    
48
   /** @var $appToken string an application token to use for requests */
49
   private $appToken = null;
50

                    
51
   /** @var string Session token obtained after initSession() */
52
   private $sessionToken = null;
53

                    
54
   /**
55
    * Client constructor.
56
    * @param string $url
57
    * @param HttpClient $httpClient
58
    */
59
   public function __construct($url, HttpClient $httpClient) {100%
60
      $this->httpClient = $httpClient;
61
      $this->url = trim($url, '/') . '/';
62
   }
63

                    
64
   /**
65
    * Set an application token to be used for each request
66
    *
67
    * @param string $appToken
68
    */
69
   public function setAppToken($appToken = null) {0%
70
      $this->appToken = $appToken;
71
   }
72

                    
73
   /**
74
    * Initialize a session with user credentials
75
    * @param string $user
76
    * @param string $password
77
    * @throws Exception
78
    * @return boolean
79
    */
80
   public function initSessionByCredentials($user, $password) {67%
81
      $response = $this->request('get', 'initSession', ['auth' => [$user, $password]]);
82
      if ($response->getStatusCode() != 200
83
         || !$this->sessionToken = json_decode($response->getBody()->getContents(), true)['session_token']) {
84
         $body = json_decode($response->getBody()->getContents());
85
         throw new Exception(ErrorHandler::getMessage($body[0]));
86
      }
87
      return true;
88
   }
89

                    
90
   /**
91
    * initialize a session with a user token
92
    *
93
    * @param string $userToken
94
    *
95
    * @throws Exception
96
    *
97
    * @return boolean True if success
98
    */
99
   public function initSessionByUserToken($userToken) {0%
100
      $response = $this->request('get', 'initSession', ['headers' => ['Authorization' => "user_token $userToken"]]);
101
      if ($response->getStatusCode() != 200
102
         || !$this->sessionToken = json_decode($response->getBody()->getContents(), true)['session_token']) {
103
         $body = json_decode($response->getBody()->getContents());
104
         throw new Exception(ErrorHandler::getMessage($body[0]));
105
      }
106
      return true;
107
   }
108

                    
109
   /**
110
    * Kill client session.
111
    * @return bool
112
    * @throws Exception
113
    */
114
   public function killSession() {100%
115
      $response = $this->request('get', 'killSession');
116
      if ($response->getStatusCode() != 200) {
117
         $body = json_decode($response->getBody()->getContents());
118
         throw new Exception(ErrorHandler::getMessage($body[0]));
119
      }
120
      return true;
121
   }
122

                    
123
   /**
124
    * Prepare and send a request to the GLPI Api.
125
    *
126
    * @param $method
127
    * @param $uri
128
    * @param array $options
129
    * @return mixed|null|\Psr\Http\Message\ResponseInterface
130
    * @throws Exception
131
    */
132
   public function request($method, $uri, array $options = []) {68%
133
      $apiToken = $this->addTokens();
134
      try {
135
         $options['headers']['Content-Type'] = "application/json";
136
         $sessionHeaders = [];
137
         if ($apiToken) {
138
            if (key_exists('Session-Token', $apiToken) && $apiToken['Session-Token']) {
139
               $sessionHeaders['Session-Token'] = $apiToken['Session-Token'];
140
            }
141
            if (key_exists('App-Token', $apiToken) && $apiToken['App-Token']) {
142
               $sessionHeaders['App-Token'] = $apiToken['App-Token'];
143
            }
144
         }
145
         $options = array_merge_recursive($options, ['headers' => $sessionHeaders]);
146
         $response = $this->httpClient->request($method, $this->url . $uri, $options);
147
         return $response;
148
      } catch (ClientException $e) {
149
         $response = $e->getResponse();
150
         /*$body = $response->getBody()->getContents();
151
         $reasonPhrase = $response->getReasonPhrase() . (($body) ? ' ' . $body : '');*/
152
         return $response;
153
      } catch (RequestException $e) {
154
         $hasResponse = $e->hasResponse();
155
         $statusCode = ($hasResponse) ? $e->getResponse()->getStatusCode() : '500';
156
         $contents = ($hasResponse) ? $e->getResponse()->getReasonPhrase() : 'Request Error';
157
         throw new Exception($contents, $statusCode);
158
      }
159
   }
160

                    
161
   /**
162
    * Return the current php $_SESSION.
163
    * @return array
164
    */
165
   public function getFullSession() {100%
166
      $response = $this->request('get', 'getFullSession');
167
      return ['statusCode' => $response->getStatusCode(), 'body' => $response->getBody()->getContents()];
168
   }
169

                    
170
   /**
171
    * Return the current $CFG_GLPI.
172
    * @return array
173
    */
174
   public function getGlpiConfig() {100%
175
      $response = $this->request('get', 'getGlpiConfig');
176
      return ['statusCode' => $response->getStatusCode(), 'body' => $response->getBody()->getContents()];
177
   }
178

                    
179
   /**
180
    * generate headers containing session and app tokens for Http client object
181
    *
182
    * @return string[]
183
    */
184
   private function addTokens() {83%
185
      $headers = [];
186
      if ($this->appToken !== null) {
187
         $headers['App-Token'] = $this->appToken;
188
      }
189
      if ($this->sessionToken !== null) {
190
         $headers['Session-Token'] = $this->sessionToken;
191
      }
192

                    
193
      return $headers;
194
   }
195

                    
196
   /**
197
    * Allows to request password recovery.
198
    * This endpoint works under the following conditions:
199
    *  - GLPI has notifications enabled
200
    *  - The email address of the user belongs to a user account.
201
    *
202
    * @param string $email
203
    * @return array
204
    */
205
   public function recoveryPassword($email) {100%
206
      $options['body'] = json_encode($params['email'] = $email);
207
      $response = $this->request('put', 'lostPassword', $options);
208
      return [
209
         'statusCode' => $response->getStatusCode(),
210
         'body' => $response->getBody()->getContents(),
211
      ];
212
   }
213

                    
214
   /**
215
    * Allows to request a password reset.
216
    * This endpoint works under the following conditions:
217
    *  - GLPI has notifications enabled
218
    *  - The email address of the user belongs to a user account.
219
    *
220
    * @param $email
221
    * @param string $recoveryToken
222
    * @param string $newPassword
223
    * @return array
224
    */
225
   public function resetPassword($email, $recoveryToken, $newPassword) {100%
226
      if (($recoveryToken && !$newPassword) || (!$recoveryToken && $newPassword)) {
227
         throw new InsufficientArgumentsException(ErrorHandler::getMessage('ERROR_APILIB_ARGUMENTS'));
228
      }
229
      $options['body'] = json_encode([
230
         'email' => $email,
231
         'password_forget_token' => $recoveryToken,
232
         'password' => $newPassword,
233
      ]);
234
      $response = $this->request('put', 'lostPassword', $options);
235
      return [
236
         'statusCode' => $response->getStatusCode(),
237
         'body' => $response->getBody()->getContents(),
238
      ];
239
   }
240
}
Powered by atoum
Back to top