Completed
Pull Request — master (#19)
by
unknown
01:39
created

Api   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 243
Duplicated Lines 12.35 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 22
c 1
b 0
f 0
lcom 1
cbo 8
dl 30
loc 243
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 3
A directPayment() 0 4 1
A reservePayment() 0 4 1
B payment() 0 27 2
A continuePayment() 0 13 1
A query() 15 15 1
A cancel() 15 15 1
B curlTransaccion() 0 29 5
C checkResponseCode() 0 37 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
    if ( empty($keyId) || empty($publicKeyId) ) {
51
      throw new Exceptions\InstapagoException('Los parámetros "keyId" y "publicKeyId" son requeridos para procesar la petición.');
52
    }
53
    $this->publicKeyId = $publicKeyId;
54
    $this->keyId = $keyId;
55
  }
56
57
  /**
58
   * Crear un pago directo.
59
   *
60
   * @param \ArrayObject<string, string> $fields Los campos necesarios 
61
   * para procesar el pago.
62
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
63
   * @throws Exceptions\InstapagoException
64
   */
65
  public function directPayment($fields)
66
  {
67
    return $this->payment('direct', $fields);
68
  }
69
70
  /**
71
   * Crear un pago diferido o reservado.
72
   *
73
   * @param \ArrayObject<string, string> $fields Los campos necesarios 
74
   * para procesar el pago.
75
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
76
   * @throws Exceptions\InstapagoException
77
   */
78
  public function reservePayment($fields)
79
  {
80
    return $this->payment('reserve', $fields);
81
  }
82
83
  /**
84
   * Crear un pago.
85
   *
86
   * @param string $paymentType tipo de pago ('reserve' o 'direct')
87
   * @param \ArrayObject<string, string> $fields Los campos necesarios 
88
   * para procesar el pago.
89
   * @return \ArrayObject<string, string> Respuesta de Instapago
90
   * @throws Exceptions\InstapagoException
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
91
   */
92
93
  private function payment($paymentType, $fields) {
94
    $type = '2';
95
    if ($paymentType == 'reserve') {
96
      $type = '1';
97
    }
98
99
    (new Validator())->payment()->validate($fields);
100
101
    $fields = [
102
      'KeyID'          => $this->keyId, 
103
      'PublicKeyId'    => $this->publicKeyId, 
104
      'amount'         => $fields['amount'], 
105
      'description'    => $fields['description'], 
106
      'cardHolder'     => $fields['card_holder'], 
107
      'cardHolderId'   => $fields['card_holder_id'], 
108
      'cardNumber'     => $fields['card_number'], 
109
      'cvc'            => $fields['cvc'], 
110
      'expirationDate' => $fields['expiration'], 
111
      'statusId'       => $type, 
112
      'IP'             => $fields['ip'], 
113
    ];
114
115
    $obj = $this->curlTransaccion('payment', $fields, 'POST');
116
    $result = $this->checkResponseCode($obj);
117
118
    return $result;
119
  }
120
121
  /**
122
   * Completar Pago
123
   * Este método funciona para procesar un bloqueo o pre-autorización
124
   * para así procesarla y hacer el cobro respectivo.
125
   *
126
   * @param \ArrayObject<string, string> $fields Los campos necesarios 
127
   * para procesar el pago.
128
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
129
   * @throws Exceptions\InstapagoException
130
   */
131
  public function continuePayment($fields){
132
    (new Validator())->release()->validate($fields);
133
    $fields = [
134
      'KeyID'        => $this->keyId, //required
135
      'PublicKeyId'  => $this->publicKeyId, //required
136
      'id'           => $fields['id'], //required
137
      'amount'       => $fields['amount'], //required
138
    ];
139
140
    $obj = $this->curlTransaccion('complete', $fields, 'POST');
141
    $result = $this->checkResponseCode($obj);
142
    return $result;
143
  }
144
145
  /**
146
   * Información/Consulta de Pago
147
   * Este método funciona para procesar un bloqueo o pre-autorización
148
   * para así procesarla y hacer el cobro respectivo.
149
   *
150
   * @param string $id_pago ID del pago a consultar 
151
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
152
   * @throws Exceptions\InstapagoException
153
   */
154 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...
155
    (new Validator())->query()->validate([
156
      'id' => $id_pago
157
    ]);
158
159
    $fields = [
160
      'KeyID'        => $this->keyId, //required
161
      'PublicKeyId'  => $this->publicKeyId, //required
162
      'id'           => $id_pago, //required
163
    ];
164
165
    $obj = $this->curlTransaccion('payment', $fields, 'GET');
166
    $result = $this->checkResponseCode($obj);
167
    return $result;
168
  }
169
170
  /**
171
   * Cancelar Pago
172
   * Este método funciona para cancelar un pago previamente procesado.
173
   *
174
   * @param string $id_pago ID del pago a cancelar
175
   * @return \ArrayObject<string, string> Respuesta de Instapago
0 ignored issues
show
Documentation introduced by
The doc-type \ArrayObject<string, could not be parsed: Expected "|" or "end of type", but got "<" at position 12. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
176
   * @throws Exceptions\InstapagoException
177
   */
178 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...
179
    (new Validator())->query()->validate([
180
      'id' => $id_pago
181
    ]);
182
183
    $fields = [
184
      'KeyID'        => $this->keyId, //required
185
      'PublicKeyId'  => $this->publicKeyId, //required
186
      'id'           => $id_pago, //required
187
    ];
188
189
    $obj = $this->curlTransaccion('payment', $fields, 'DELETE');
190
    $result = $this->checkResponseCode($obj);
191
    return $result;
192
  }
193
194
  /**
195
   * Realiza Transaccion
196
   * Efectúa y retornar una respuesta a un metodo de pago.
197
   *
198
   * @param $url endpoint a consultar
199
   * @param $fields datos para la consulta
200
   * @param $method verbo http de la consulta
201
   *
202
   * @return $obj array resultados de la transaccion
0 ignored issues
show
Documentation introduced by
The doc-type $obj could not be parsed: Unknown type name "$obj" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
203
   */
204
  public function curlTransaccion($url, $fields, $method)
205
  {
206
    $client = new Client([
207
       'base_uri' => 'https://api.instapago.com/',
208
    ]);
209
210
    $args = [];
0 ignored issues
show
Unused Code introduced by
$args is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
211
    
212
    if ($method == 'GET') {
213
      $args = [
214
        'query' => $fields
215
      ];
216
    }else if ($method == 'POST' || $method == 'DELETE') {
217
      $args = [
218
          'form_params' => $fields
219
      ];
220
    }else{
221
      throw new Exception("Not implemented yet", 1);
222
    }
223
    
224
    try {
225
      $request = $client->request($method, $url, $args);
226
      $body = $request->getBody()->getContents();
227
      $obj = json_decode($body);
228
      return $obj;
229
    } catch (\GuzzleHttp\Exception\ConnectException $e) {
230
      throw new Exceptions\TimeoutException("Cannot connect to api.instapago.com");
231
    }
232
  }
233
234
  /**
235
   * Verifica y retornar el resultado de la transaccion.
236
   *
237
   * @param $obj datos de la consulta
238
   *
239
   * @return $result array datos de transaccion
0 ignored issues
show
Documentation introduced by
The doc-type $result could not be parsed: Unknown type name "$result" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
240
   */
241
  public function checkResponseCode($obj)
242
  {
243
    $code = $obj->code;
244
245
    if ($code == 400) {
246
      throw new Exceptions\InvalidInputException(
247
        'Error al validar los datos enviados.'
248
      );
249
    }else if ($code == 401) {
250
      throw new Exceptions\AuthException(
251
        'Error de autenticación, ha ocurrido un error'
252
        . ' con las llaves utilizadas.');
253
    }else if ($code == 403) {
254
      throw new Exceptions\BankRejectException(
255
        'Pago Rechazado por el banco.'
256
      );
257
    }else if ($code == 500) {
258
      throw new Exceptions\InstapagoException(
259
        'Ha Ocurrido un error interno dentro del servidor.'
260
      );
261
    }else if ($code == 503) {
262
      throw new Exceptions\InstapagoException(
263
        'Ha Ocurrido un error al procesar los parámetros de entrada.'
264
        . ' Revise los datos enviados y vuelva a intentarlo.'
265
      );
266
    }else if ($code == 201) {
267
      return [
268
        'code'         => $code,
269
        'msg_banco'    => $obj->message,
270
        'voucher'      => html_entity_decode($obj->voucher),
271
        'id_pago'      => $obj->id,
272
        'reference'    => $obj->reference,
273
      ];
274
    }else {
275
      throw new \Exception('Not implemented yet');
276
    }
277
  }
278
279
}
280