Client::getQueryAction()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 11

Duplication

Lines 4
Ratio 36.36 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 2
dl 4
loc 11
rs 9.9
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
/**
4
 * @package MerchantSafeUnipay\SDK
5
 * @author Mehmet Korkmaz <[email protected]>
6
 * @license https://opensource.org/licenses/mit-license.php MIT
7
 *
8
 * Documentation can be found at https://merchantsafeunipay.com/msu/api/v2/doc
9
 */
10
11
namespace MerchantSafeUnipay\SDK;
12
13
use GuzzleHttp\Client as GuzzleClient;
14
use function MerchantSafeUnipay\convertSnakeCase;
15
use MerchantSafeUnipay\SDK\Environment;
16
use Psr\Http\Message\ResponseInterface;
17
use Psr\Log\LoggerInterface;
18
use MerchantSafeUnipay\SDK\Action\ActionInterface;
19
use Psr7\Http\Message\RequestInterface;
20
use MerchantSafeUnipay\SDK\Exception\InvalidArgumentException;
21
use MerchantSafeUnipay\SDK\Exception\BadMethodCallException;
22
use MerchantSafeUnipay\SDK\Exception\RequestException;
23
24
class Client
25
{
26
    /**
27
     *
28
     */
29
    const MSU_API_VERSION = 2;
30
31
    /**
32
     * @var array
33
     */
34
    private static $validActions = [
35
36
        'session',
37
        'financialTransactions',
38
        'approveActions',
39
        'rejectActions',
40
        'dealer',
41
        'dealerPst',
42
        'dealerType',
43
        'eWallet',
44
        'merchant',
45
        'merchantUser',
46
        'messageContent',
47
        'payByLinkPayment',
48
        'paymentPolicy',
49
        'paymentSystem',
50
        'paymentType',
51
        'recurringPayment',
52
        'recurringPlan',
53
        'recurringPlanCard'
54
    ];
55
56
    private static $validQueryActions = [
57
        'Transaction',
58
        'DealerTransaction',
59
        'SubDealerTransaction',
60
        'Installment',
61
        'Card',
62
        'CardExpiry',
63
        'Customer',
64
        'Session',
65
        'PayByLinkPayment',
66
        'Bin',
67
        'Campaign',
68
        'OnlineCampaign',
69
        'RecurringPlan',
70
        'PaymentSystems',
71
        'MerchantPaymentSystems',
72
        'MerchantProfile',
73
        'PaymentSystemData',
74
        'Points',
75
        'PaymentPolicy',
76
        'SplitPayment',
77
        'Merchant',
78
        'MerchantContent',
79
        'MerchantStatusHistory',
80
        'MerchantUser',
81
        'UserRolePermission',
82
        'Dealer',
83
        'DealerType',
84
        'DealerPst',
85
        'DealerStatusHistory',
86
        'MerchantUserDealers',
87
        'Groups',
88
        'ExecutiveReport',
89
        'TransactionRule'
90
    ];
91
92
    /**
93
     * @var Environment
94
     */
95
    private $environment;
96
    /**
97
     * @var GuzzleClient
98
     */
99
    private $guzzleClient;
100
101
    private $logger;
102
103
    private static $headers = [
104
        'User-Agent' => 'MerchantSafeUnipayPhpSDK/1.0',
105
        'Accept'     => 'application/json'
106
    ];
107
108
    /**
109
     * Client constructor.
110
     * @param Environment $environment
111
     * @param GuzzleClient $guzzleClient
112
     * @param LoggerInterface $logger
113
     */
114
    public function __construct(Environment $environment, GuzzleClient $guzzleClient, LoggerInterface $logger)
115
    {
116
        $this->environment = $environment;
117
        $this->guzzleClient = $guzzleClient;
118
        $this->logger = $logger;
119
    }
120
121
    /**
122
     * @param $name
123
     * @param $arguments
124
     * @throws BadMethodCallException
125
     * @throws RequestException
126
     * @throws InvalidArgumentException
127
     * @return array
128
     */
129
    public function __call(string $name, array $arguments)
130
    {
131
        return $this->requestAction($this->getCallAction($name, $arguments));
132
    }
133
134
    /**
135
     * @param $name
136
     * @param $arguments
137
     * @throws BadMethodCallException
138
     * @throws RequestException
139
     * @throws InvalidArgumentException
140
     * @return array
141
     */
142
    public function query(string $name, array $arguments)
143
    {
144
        return $this->requestAction($this->getQueryAction($name, $arguments));
145
    }
146
147
    private function getCallAction(string $name, array $arguments)
148
    {
149
        $namespace = '\\MerchantSafeUnipay\\SDK\\Action';
150
        $actionClass =  $namespace . '\\'. convertSnakeCase($name);
151 View Code Duplication
        if (!in_array($name, self::$validActions, true) || !class_exists($actionClass)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
152
            $message = sprintf('%s is not valid MerchantSafeUnipay API action.', $name);
153
            throw new BadMethodCallException($message);
154
        }
155
        return $this->actionFactory($name, $arguments, $namespace);
156
    }
157
    private function getQueryAction(string $name, array $arguments)
158
    {
159
        $name = str_replace(' ', '', ucwords(str_replace('_', '', $name)));
160
        $namespace = '\\MerchantSafeUnipay\\SDK\\Action\\Query';
161
        $actionClass =  $namespace . '\\'. convertSnakeCase($name);
162 View Code Duplication
        if (!in_array($name, self::$validQueryActions, true) || !class_exists($actionClass)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
163
            $message = sprintf('%s is not valid MerchantSafeUnipay API query action.', $name);
164
            throw new BadMethodCallException($message);
165
        }
166
        return $this->actionFactory($name, ['getQuery', $arguments], $namespace);
167
    }
168
169
    /**
170
     * @param string $name
171
     * @param array $arguments
172
     * @param string $namespace
173
     * @return ActionInterface
174
     * @throws BadMethodCallException
175
     * @throws InvalidArgumentException
176
     */
177
    private function actionFactory(string $name, array $arguments, string $namespace)
178
    {
179
        $actionClass =  $namespace . '\\'. convertSnakeCase($name);
180
        $actionName = $arguments[0];
181
        $actionMethod = convertSnakeCase($actionName, 'f');
182
        $actionObject = new $actionClass($this->environment->getMerchantData());
183
        if (!method_exists($actionObject, $actionMethod)) {
184
            $message = sprintf(
185
                '%s/%s is not valid MerchantSafeUnipay API action.',
186
                ucfirst($name),
187
                ucfirst($actionName)
188
            );
189
            throw new BadMethodCallException($message);
190
        }
191
        try {
192
            $actionObject->$actionMethod($arguments[1]);
193
            return $actionObject;
194
        } catch (TypeError $e) {
0 ignored issues
show
Bug introduced by
The class MerchantSafeUnipay\SDK\TypeError does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
195
            $message = 'This action needs arguments, no argument provided.';
196
            throw new InvalidArgumentException($message);
197
        }
198
    }
199
200
    private function requestAction(ActionInterface $action)
201
    {
202
        $headers = array_merge(self::$headers, $action->getHeaders());
203
        $response = $this->httpRequest($action->getAction(), $headers, $action->getQueryParams());
204
205
        return [
206
            'status' => $response->getStatusCode(),
207
            'reason' => $response->getReasonPhrase(),
208
            'headers' => $response->getHeaders(),
209
            'data' => json_decode((string) $response->getBody(), true)
210
        ];
211
    }
212
213
    /**
214
     * @param string $actionName
215
     * @param array $headers
216
     * @param array  $queryParams
217
     * @throws RequestException
218
     * @return ResponseInterface
219
     */
220
    private function httpRequest(string $actionName, array $headers, array $queryParams)
221
    {
222
        $uri = $this->environment->getUrl();
223
        $queryParams['ACTION'] = $actionName;
224
        $options = [
225
            'headers' => $headers,
226
            'form_params' => $queryParams
227
        ];
228
        try {
229
            return $this->guzzleClient->post($uri, $options);
230
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class MerchantSafeUnipay\SDK\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
231
            $message =   $e->getMessage();
232
        }
233
        $message = sprintf('MerchantSafe Unipay API Request Error:% s', $message);
234
        throw new RequestException($message);
235
    }
236
}
237