AbstractHttpClient::setOptions()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Nexylan packages.
5
 *
6
 * (c) Nexylan SAS <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Nexy\PayboxDirect\HttpClient;
13
14
use Nexy\PayboxDirect\Exception\PayboxException;
15
use Nexy\PayboxDirect\Paybox;
16
use Nexy\PayboxDirect\Response\ResponseInterface;
17
18
/**
19
 * @author Sullivan Senechal <[email protected]>
20
 *
21
 * @see http://www1.paybox.com/espace-integrateur-documentation/les-solutions-paybox-direct-et-paybox-direct-plus/
22
 */
23
abstract class AbstractHttpClient
24
{
25
    /**
26
     * @var int
27
     */
28
    protected $timeout;
29
30
    /**
31
     * @var int
32
     */
33
    protected $baseUrl = Paybox::API_URL_TEST;
34
35
    /**
36
     * @var string[]
37
     */
38
    private $baseParameters;
39
40
    /**
41
     * @var int
42
     */
43
    private $defaultCurrency;
44
45
    /**
46
     * @var int|null
47
     */
48
    private $defaultActivity = null;
49
50
    /**
51
     * @var int
52
     */
53
    private $questionNumber;
54
55
    /**
56
     * Constructor.
57
     */
58
    final public function __construct()
59
    {
60
        try {
61
            $this->questionNumber = random_int(0, time());
62
        } catch (\Exception $exception) {
63
            $this->questionNumber = rand(0, time());
64
        }
65
    }
66
67
    /**
68
     * @param array $options
69
     */
70
    final public function setOptions($options)
71
    {
72
        $this->timeout = $options['timeout'];
73
        $this->baseUrl = true === $options['production'] ? Paybox::API_URL_PRODUCTION : Paybox::API_URL_TEST;
74
        $this->baseParameters = [
0 ignored issues
show
Documentation Bug introduced by
It seems like array('VERSION' => $opti...$options['paybox_key']) of type array<string,?,{"VERSION...IFIANT":"?","CLE":"?"}> is incompatible with the declared type array<integer,string> of property $baseParameters.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
75
            'VERSION' => $options['paybox_version'],
76
            'SITE' => $options['paybox_site'],
77
            'RANG' => $options['paybox_rank'],
78
            'IDENTIFIANT' => $options['paybox_identifier'],
79
            'CLE' => $options['paybox_key'],
80
        ];
81
        $this->defaultCurrency = $options['paybox_default_currency'];
82
        if (array_key_exists('paybox_default_activity', $options)) {
83
            $this->defaultActivity = $options['paybox_default_activity'];
84
        }
85
    }
86
87
    /**
88
     * Calls PayBox Direct platform with given operation type and parameters.
89
     *
90
     * @param int      $type          Request type
91
     * @param string[] $parameters    Request parameters
92
     * @param string   $responseClass
93
     *
94
     * @return ResponseInterface The response content
95
     *
96
     * @throws PayboxException
97
     */
98
    final public function call($type, array $parameters, $responseClass)
99
    {
100
        if (!in_array(ResponseInterface::class, class_implements($responseClass))) {
101
            throw new \InvalidArgumentException('The response class must implement '.ResponseInterface::class.'.');
102
        }
103
104
        $bodyParams = array_merge($parameters, $this->baseParameters);
105
        $bodyParams['TYPE'] = $type;
106
        $bodyParams['NUMQUESTION'] = $this->questionNumber;
107
        $bodyParams['DATEQ'] = null !== $parameters['DATEQ'] ? $parameters['DATEQ'] : date('dmYHis');
108
        // Restore default_currency from parameters if given
109
        if (array_key_exists('DEVISE', $parameters)) {
110
            $bodyParams['DEVISE'] = null !== $parameters['DEVISE'] ? $parameters['DEVISE'] : $this->defaultCurrency;
111
        }
112
        if (!array_key_exists('ACTIVITE', $parameters) && $this->defaultActivity) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->defaultActivity of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
113
            $bodyParams['ACTIVITE'] = $this->defaultActivity;
114
        }
115
116
        // `ACTIVITE` must be a string of 3 numbers to get it working with Paybox API.
117
        if (array_key_exists('ACTIVITE', $bodyParams)) {
118
            $bodyParams['ACTIVITE'] = str_pad($bodyParams['ACTIVITE'], 3, '0', STR_PAD_LEFT);
119
        }
120
121
        $response = $this->request($bodyParams);
122
123
        // Generate results array
124
        $results = [];
125
        foreach (explode('&', $response) as $element) {
126
            list($key, $value) = explode('=', $element);
127
            $value = utf8_encode(trim($value));
128
            $results[$key] = $value;
129
        }
130
131
        $this->questionNumber = (int) $results['NUMQUESTION'] + 1;
132
133
        /** @var ResponseInterface $response */
134
        $response = new $responseClass($results);
135
136
        if (!$response->isSuccessful()) {
137
            throw new PayboxException($response);
138
        }
139
140
        return $response;
141
    }
142
143
    /**
144
     * Init and setup http client with PayboxDirectPlus SDK options.
145
     */
146
    abstract public function init();
147
148
    /**
149
     * Sends a request to the server, receive a response and returns it as a string.
150
     *
151
     * @param string[] $parameters Request parameters
152
     *
153
     * @return string The response content
154
     */
155
    abstract protected function request($parameters);
156
}
157