Api   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 253
Duplicated Lines 11.86 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 20
c 6
b 0
f 0
lcom 1
cbo 8
dl 30
loc 253
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 3
A directPayment() 0 4 1
A reservePayment() 0 4 1
A payment() 0 23 1
A continuePayment() 0 15 1
A query() 15 17 1
A cancel() 15 17 1
B curlTransaccion() 0 24 4
C checkResponseCode() 0 39 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * The MIT License (MIT)
5
 * Copyright (c) 2016 Angel Cruz <[email protected]>.
6
 *
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the “Software”), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 *
14
 * The above copyright notice and this permission notice shall be included in
15
 * all copies or substantial portions of the Software.
16
 *
17
 * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
 * THE SOFTWARE.
24
 *
25
 * @author Angel Cruz <[email protected]>
26
 * @license MIT License
27
 * @copyright 2016 Angel Cruz
28
 */
29
30
namespace Instapago;
31
32
use GuzzleHttp\Client as Client;
33
34
/**
35
 * Clase para la pasarela de pagos Instapago.
36
 */
37
class Api
38
{
39
	protected $keyId;
40
	protected $publicKeyId;
41
42
  /**
43
   * Crear un nuevo objeto de Instapago.
44
   *
45
   * @param string $keyId       llave privada
46
   * @param string $publicKeyId llave publica
47
   *                            Requeridas.
48
   */
49
  public function __construct($keyId, $publicKeyId)
50
  {
51
	  if (empty($keyId) || empty($publicKeyId)) {
52
		  throw new Exceptions\InstapagoException('Los parámetros "keyId" y "publicKeyId" son requeridos para procesar la petición.');
53
	  }
54
	  $this->publicKeyId = $publicKeyId;
55
	  $this->keyId = $keyId;
56
  }
57
58
  /**
59
   * Crear un pago directo.
60
   *
61
   * @param array<string> $fields Los campos necesarios
62
   *                              para procesar el pago.
63
   *
64
   * @throws Exceptions\InstapagoException
65
   *
66
   * @return array<string> Respuesta de Instapago
67
   */
68
  public function directPayment($fields)
69
  {
70
	  return $this->payment('2', $fields);
71
  }
72
73
  /**
74
   * Crear un pago diferido o reservado.
75
   *
76
   * @param array<string> $fields Los campos necesarios
77
   *                              para procesar el pago.
78
   *
79
   * @throws Exceptions\InstapagoException
80
   *
81
   * @return array<string> Respuesta de Instapago
82
   */
83
  public function reservePayment($fields)
84
  {
85
	  return $this->payment('1', $fields);
86
  }
87
88
  /**
89
   * Crear un pago.
90
   *
91
   * @param string        $type   tipo de pago ('1' o '0')
92
   * @param array<string> $fields Los campos necesarios
93
   *                              para procesar el pago.
94
   *
95
   * @throws Exceptions\InstapagoException
96
   *
97
   * @return array<string> Respuesta de Instapago
98
   */
99
  private function payment($type, $fields)
100
  {
101
	  (new Validator())->payment()->validate($fields);
102
103
	  $fields = [
104
	  'KeyID'          => $this->keyId,
105
	  'PublicKeyId'    => $this->publicKeyId,
106
	  'amount'         => $fields['amount'],
107
	  'description'    => $fields['description'],
108
	  'cardHolder'     => $fields['card_holder'],
109
	  'cardHolderId'   => $fields['card_holder_id'],
110
	  'cardNumber'     => $fields['card_number'],
111
	  'cvc'            => $fields['cvc'],
112
	  'expirationDate' => $fields['expiration'],
113
	  'statusId'       => $type,
114
	  'IP'             => $fields['ip'],
115
	];
116
117
	  $obj = $this->curlTransaccion('payment', $fields, 'POST');
118
	  $result = $this->checkResponseCode($obj);
119
120
	  return $result;
121
  }
122
123
  /**
124
   * Completar Pago
125
   * Este método funciona para procesar un bloqueo o pre-autorización
126
   * para así procesarla y hacer el cobro respectivo.
127
   *
128
   * @param array<string> $fields Los campos necesarios
129
   *                              para procesar el pago.
130
   *
131
   * @throws Exceptions\InstapagoException
132
   *
133
   * @return array<string> Respuesta de Instapago
134
   */
135
  public function continuePayment($fields)
136
  {
137
	  (new Validator())->release()->validate($fields);
138
	  $fields = [
139
	  'KeyID'        => $this->keyId, //required
140
	  'PublicKeyId'  => $this->publicKeyId, //required
141
	  'id'           => $fields['id'], //required
142
	  'amount'       => $fields['amount'], //required
143
	];
144
145
	  $obj = $this->curlTransaccion('complete', $fields, 'POST');
146
	  $result = $this->checkResponseCode($obj);
147
148
	  return $result;
149
  }
150
151
  /**
152
   * Información/Consulta de Pago
153
   * Este método funciona para procesar un bloqueo o pre-autorización
154
   * para así procesarla y hacer el cobro respectivo.
155
   *
156
   * @param string $id_pago ID del pago a consultar
157
   *
158
   * @throws Exceptions\InstapagoException
159
   *
160
   * @return array<string> Respuesta de Instapago
161
   */
162 View Code Duplication
  public function query($id_pago)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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
  {
164
	  (new Validator())->query()->validate([
165
	  'id' => $id_pago,
166
	]);
167
168
	  $fields = [
169
	  'KeyID'        => $this->keyId, //required
170
	  'PublicKeyId'  => $this->publicKeyId, //required
171
	  'id'           => $id_pago, //required
172
	];
173
174
	  $obj = $this->curlTransaccion('payment', $fields, 'GET');
175
	  $result = $this->checkResponseCode($obj);
176
177
	  return $result;
178
  }
179
180
  /**
181
   * Cancelar Pago
182
   * Este método funciona para cancelar un pago previamente procesado.
183
   *
184
   * @param string $id_pago ID del pago a cancelar
185
   *
186
   * @throws Exceptions\InstapagoException
187
   *
188
   * @return array<string> Respuesta de Instapago
189
   */
190 View Code Duplication
  public function cancel($id_pago)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
191
  {
192
	  (new Validator())->query()->validate([
193
	  'id' => $id_pago,
194
	]);
195
196
	  $fields = [
197
	  'KeyID'        => $this->keyId, //required
198
	  'PublicKeyId'  => $this->publicKeyId, //required
199
	  'id'           => $id_pago, //required
200
	];
201
202
	  $obj = $this->curlTransaccion('payment', $fields, 'DELETE');
203
	  $result = $this->checkResponseCode($obj);
204
205
	  return $result;
206
  }
207
208
  /**
209
   * Realiza Transaccion
210
   * Efectúa y retornar una respuesta a un metodo de pago.
211
   *
212
   * @param $url string endpoint a consultar
213
   * @param $fields array datos para la consulta
214
   * @param $method string verbo http de la consulta
215
   *
216
   * @return array resultados de la transaccion
217
   */
218
  public function curlTransaccion($url, $fields, $method)
219
  {
220
	  $client = new Client([
221
	   'base_uri' => 'https://api.instapago.com/',
222
	]);
223
224
	  $args = [];
225
	  if ( ! in_array($method, ['GET', 'POST', 'DELETE'])) {
226
		  throw new Exception('Not implemented yet', 1);
227
	  }
228
	  $key = ($method == 'GET') ? 'query' : 'form_params';
229
230
	  $args[$key] = $fields;
231
232
	  try {
233
		  $request = $client->request($method, $url, $args);
234
		  $body = $request->getBody()->getContents();
235
		  $obj = json_decode($body, true);
236
237
		  return $obj;
238
	  } catch (\GuzzleHttp\Exception\ConnectException $e) {
239
		  throw new Exceptions\TimeoutException('Cannot connect to api.instapago.com');
240
	  }
241
  }
242
243
  /**
244
   * Verifica y retornar el resultado de la transaccion.
245
   *
246
   * @param $obj datos de la consulta
247
   *
248
   * @return array datos de transaccion
249
   */
250
  public function checkResponseCode($obj)
251
  {
252
	  $code = $obj['code'];
253
254
	  if ($code == 400) {
255
		  throw new Exceptions\InvalidInputException(
256
		'Error al validar los datos enviados.'
257
	  );
258
	  }
259
	  if ($code == 401) {
260
		  throw new Exceptions\AuthException(
261
		'Error de autenticación, ha ocurrido un error'
262
		.' con las llaves utilizadas.');
263
	  } elseif ($code == 403) {
264
		  throw new Exceptions\BankRejectException(
265
		'Pago Rechazado por el banco.'
266
	  );
267
	  } elseif ($code == 500) {
268
		  throw new Exceptions\InstapagoException(
269
		'Ha Ocurrido un error interno dentro del servidor.'
270
	  );
271
	  } elseif ($code == 503) {
272
		  throw new Exceptions\InstapagoException(
273
		'Ha Ocurrido un error al procesar los parámetros de entrada.'
274
		.' Revise los datos enviados y vuelva a intentarlo.'
275
	  );
276
	  } elseif ($code == 201) {
277
		  return [
278
		'code'              => $code,
279
		'msg_banco'         => $obj['message'],
280
		'voucher'           => html_entity_decode($obj['voucher']),
281
		'id_pago'           => $obj['id'],
282
		'reference'         => $obj['reference'],
283
		'original_response' => $obj,
284
	  ];
285
	  }
286
287
	  throw new \Exception('Not implemented yet');
288
  }
289
}
290