DrupalRestClient   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 173
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 15
c 2
b 1
f 0
lcom 1
cbo 4
dl 0
loc 173
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __destruct() 0 4 1
A setParameters() 0 9 1
A call() 0 12 1
A getClient() 0 10 2
A generateCsrfToken() 0 19 2
A remoteCall() 0 21 2
A login() 0 15 2
A logout() 0 12 3
1
<?php
2
3
namespace Actualys\Bundle\DrupalCommerceConnectorBundle\Webservice\Transport;
4
5
use Actualys\Bundle\DrupalCommerceConnectorBundle\Webservice\Exception\RestConnectionException;
6
use Guzzle\Http\Client;
7
use Guzzle\Http\Exception\BadResponseException;
8
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;
9
use Guzzle\Plugin\Cookie\CookiePlugin;
10
11
class DrupalRestClient
12
{
13
    /** @const  string */
14
    const REST_URL_USER_LOGIN = 'user/login';
15
16
    /** @const  string */
17
    const REST_URL_USER_LOGOUT = 'user/logout';
18
19
    /** @const  string */
20
    const REST_URL_USER_TOKEN = 'user/token';
21
22
    /** @var  Client */
23
    protected $client;
24
25
    /** @var  array */
26
    protected $parameters;
27
28
    /** @var  bool */
29
    protected $connected;
30
31
    /**
32
     * @throws RestConnectionException
33
     */
34
    public function __construct()
35
    {
36
        $this->client     = null;
37
        $this->parameters = array();
38
        $this->connected  = false;
39
    }
40
41
    /**
42
     *
43
     */
44
    public function __destruct()
45
    {
46
       $this->logout();
47
    }
48
49
    /**
50
     * @param  array $parameters
51
     *
52
     * @return $this
53
     */
54
    public function setParameters(array $parameters)
55
    {
56
        // Close any previous opened connection.
57
        $this->logout();
58
59
        $this->parameters = $parameters;
60
61
        return $this;
62
    }
63
64
    /**
65
     * @param  string $method
66
     * @param  array  $data
67
     *
68
     * @return mixed
69
     */
70
    public function call($method, $data = array())
71
    {
72
        $this->login();
73
74
        $response = $this->remoteCall(
75
          $this->parameters['endpoint'].'/'.$this->parameters['resource_path'].'/'.$method,
76
          array('X-CSRF-Token' => $this->generateCsrfToken()),
77
          $data
78
        );
79
80
        return $response;
81
    }
82
83
    /**
84
     * @return \Guzzle\Http\Client
85
     */
86
    protected function getClient()
87
    {
88
        if (is_null($this->client)) {
89
            $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
90
            $this->client = new Client($this->parameters['base_url']);
91
            $this->client->addSubscriber($cookiePlugin);
92
        }
93
94
        return $this->client;
95
    }
96
97
    /**
98
     * @return string
99
     */
100
    protected function generateCsrfToken()
101
    {
102
        $request = $this->getClient()->post(
103
          $this->parameters['endpoint'].'/'.self::REST_URL_USER_TOKEN,
104
          array(
105
            'Accept'       => 'application/json',
106
            'Content-Type' => 'application/json',
107
          ),
108
          json_encode(array())
109
        )->send();
110
111
        $response = json_decode($request->getBody(true));
112
113
        if (empty($response)) {
114
            throw new BadResponseException('Error while retrieving CSRF Token.');
115
        }
116
117
        return $response->token;
118
    }
119
120
    /**
121
     * @param string $uri
122
     * @param array  $headers
123
     * @param array  $data
124
     *
125
     * @return mixed
126
     */
127
    protected function remoteCall($uri, $headers = array(), $data = array())
128
    {
129
        $headers += array(
130
          'Accept'       => 'application/json',
131
          'Content-Type' => 'application/json',
132
        );
133
134
        $request = $this->getClient()->post(
135
          $uri,
136
          $headers,
137
          json_encode($data)
138
        )->send();
139
140
        $response = json_decode($request->getBody(true));
141
142
        if ($response === false) {
143
            throw new BadResponseException('Bad response.');
144
        }
145
146
        return $response;
147
    }
148
149
    /**
150
     * @throws RestConnectionException
151
     */
152
    protected function login()
153
    {
154
        if (!$this->connected) {
155
            $this->remoteCall(
156
              $this->parameters['endpoint'].'/'.self::REST_URL_USER_LOGIN,
157
              array('X-CSRF-Token' => $this->generateCsrfToken()),
158
              array(
159
                'username' => $this->parameters['user'],
160
                'password' => $this->parameters['pwd'],
161
              )
162
            );
163
164
            $this->connected = true;
165
        }
166
    }
167
168
    /**
169
     *
170
     */
171
    protected function logout()
172
    {
173
        if ($this->client && $this->connected) {
174
            $this->remoteCall(
175
              $this->parameters['endpoint'].'/'.self::REST_URL_USER_LOGOUT,
176
              array('X-CSRF-Token' => $this->generateCsrfToken())
177
            );
178
        }
179
180
        $this->client    = null;
181
        $this->connected = false;
182
    }
183
}
184