Passed
Push — master ( 7f9295...bd7035 )
by Oss
01:56
created

BpmOnline   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 147
Duplicated Lines 0 %

Test Coverage

Coverage 8.33%

Importance

Changes 0
Metric Value
wmc 9
eloc 66
dl 0
loc 147
ccs 5
cts 60
cp 0.0833
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A authentication() 0 30 4
A createRequest() 0 14 1
A getResponse() 0 39 3
A __construct() 0 5 1
1
<?php
2
/**
3
 * @category    Brownie/BpmOnline
4
 * @author      Brownie <[email protected]>
5
 * @license     https://opensource.org/licenses/MIT
6
 */
7
8
namespace Brownie\BpmOnline;
9
10
use Brownie\BpmOnline\Exception\AuthenticationException;
11
use Brownie\BpmOnline\Exception\HttpCodeException;
12
use Brownie\HttpClient\Header\Header;
13
use Brownie\HttpClient\HTTPClient;
14
use Brownie\BpmOnline\DataService\Contract;
15
use Brownie\HttpClient\Request;
16
use Brownie\Util\StorageArray;
17
use Brownie\HttpClient\Exception\ClientException;
18
use Brownie\HttpClient\Exception\ValidateException;
19
use Brownie\BpmOnline\DataService\Response;
20
21
/**
22
 * API access to a single marketing management platform 'CRM-system bpm’online'
23
 *
24
 * @method HTTPClient   getHttpClient()             HTTP client.
25
 * @method Config       getConfig()                 Bpm'online config.
26
 * @method array        getAuthentication()         Returns authentication data.
27
 * @method BpmOnline    setAuthentication($data)    Sets authentication data.
28
 * @method int          getConfigurationNumber()    Returns configuration number.
29
 * @method string       getDataFormat()             Returns data format.
30
 */
31
class BpmOnline extends StorageArray
32
{
33
34
    /**
35
     * List of supported fields.
36
     *
37
     * @var array
38
     */
39
    protected $fields = [
40
        'httpClient' => null,
41
        'config' => null,
42
        'configurationNumber' => 0,
43
        'dataFormat' => 'json',
44
        'authentication' => null,
45
    ];
46
47
    /**
48
     * Sets the input values.
49
     *
50
     * @param HTTPClient    $httpClient     HTTP client.
51
     * @param Config        $config         Bpm'online config.
52
     */
53 1
    public function __construct(HTTPClient $httpClient, Config $config)
54
    {
55 1
        parent::__construct([
56 1
            'httpClient' => $httpClient,
57 1
            'config' => $config,
58
        ]);
59 1
    }
60
61
    /**
62
     * Creates a request to DataService.
63
     *
64
     * @param string    $url        Request URL.
65
     * @param string    $rawBody    Raw body.
66
     *
67
     * @return Request
68
     */
69
    private function createRequest($url, $rawBody)
70
    {
71
        return $this
72
            ->getHttpClient()
73
            ->createRequest()
74
            ->setMethod(Request::HTTP_METHOD_POST)
75
            ->setUrl($url)
76
            ->setBodyFormat(Request::FORMAT_APPLICATION_JSON)
77
            ->addHeader(new Header([
78
                'name' => 'Content-Type',
79
                'value' => Request::FORMAT_APPLICATION_JSON,
80
            ]))
81
            ->setBody($rawBody)
82
            ->setTimeOut($this->getConfig()->getApiConnectTimeOut());
83
    }
84
85
    /**
86
     * Authenticates in the DataService bpm'online.
87
     *
88
     * @throws AuthenticationException
89
     * @throws HttpCodeException
90
     * @throws ClientException
91
     * @throws ValidateException
92
     */
93
    private function authentication()
94
    {
95
        $request = $this
96
            ->createRequest(
97
                $this->getConfig()->getApiUrlScheme() . '://' .
98
                $this->getConfig()->getUserDomain() . '.' .
99
                $this->getConfig()->getApiDomain() .
100
                '/ServiceModel/AuthService.svc/Login',
101
                json_encode([
102
                    'UserName' => $this->getConfig()->getUserName(),
103
                    'UserPassword' => $this->getConfig()->getUserPassword(),
104
                ])
105
            );
106
107
        $response = $this->getHttpClient()->request($request);
108
109
        if (200 != $response->getHttpCode()) {
110
            throw new HttpCodeException('Invalid response code: ' . $response->getHttpCode());
111
        }
112
113
        $jsonResponse = json_decode($response->getBody(), true);
114
115
        if ((JSON_ERROR_NONE != json_last_error()) || (0 != $jsonResponse['Code']))
116
        {
117
            throw new AuthenticationException('Authentication failed.');
118
        }
119
120
        $this->setAuthentication([
121
            '.aspxauth' => $response->getHttpCookieList()->get('.aspxauth'),
122
            'bpmcsrf' => $response->getHttpCookieList()->get('bpmcsrf'),
123
        ]);
124
    }
125
126
    /**
127
     * Returns the response from the execution of the contract.
128
     *
129
     * @param Contract  $contract    DataService contract.
130
     *
131
     * @return Response
132
     *
133
     * @throws AuthenticationException
134
     * @throws ClientException
135
     * @throws Exception\ValidateException
136
     * @throws HttpCodeException
137
     * @throws ValidateException
138
     */
139
    public function getResponse(Contract $contract)
140
    {
141
        $contract->validate();
142
        if (empty($this->getAuthentication())) {
143
            $this->authentication();
144
        }
145
146
        $request = $this
147
            ->createRequest(
148
                $this->getConfig()->getApiUrlScheme() . '://' .
149
                $this->getConfig()->getUserDomain() . '.' . $this->getConfig()->getApiDomain() .
150
                '/' . $this->getConfigurationNumber() . '/dataservice/' . $this->getDataFormat() .
151
                '/reply/' . $contract->getContractType(),
152
                json_encode($contract->toArray())
153
            )
154
            ->addCookie($this->getAuthentication()['.aspxauth'])
155
            ->addCookie($this->getAuthentication()['bpmcsrf'])
156
            ->addHeader(
157
                $this
158
                    ->getHttpClient()
159
                    ->createHeader('Authorization', 'Cookie')
160
            )
161
            ->addHeader(
162
                $this
163
                    ->getHttpClient()
164
                    ->createHeader('BPMCSRF', $this->getAuthentication()['bpmcsrf']->getValue())
165
            );
166
167
        $response = $this->getHttpClient()->request($request);
168
        $contractResponse = $contract->getResponse($response->getBody());
169
170
        if (200 != $response->getHttpCode()) {
171
            throw new HttpCodeException(
172
                'Invalid response code: ' . $response->getHttpCode() . ', ' .
173
                $contractResponse->getErrorMessage()
174
            );
175
        }
176
177
        return $contractResponse;
178
    }
179
}
180