Completed
Push — master ( 576b56...533c2b )
by Dmitry
14:42
created

BitPayMerchant   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 63
Duplicated Lines 38.1 %

Coupling/Cohesion

Components 2
Dependencies 11

Test Coverage

Coverage 96.77%

Importance

Changes 0
Metric Value
wmc 4
lcom 2
cbo 11
dl 24
loc 63
ccs 30
cts 31
cp 0.9677
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A createGateway() 0 9 1
A completePurchase() 0 14 1
A requestPurchase() 24 24 2

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
 * Generalization over Omnipay and Payum
4
 *
5
 * @link      https://github.com/hiqdev/php-merchant
6
 * @package   php-merchant
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2015-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\php\merchant\merchants\bitpay;
12
13
use hiqdev\php\merchant\exceptions\MerchantException;
14
use hiqdev\php\merchant\InvoiceInterface;
15
use hiqdev\php\merchant\merchants\AbstractMerchant;
16
use hiqdev\php\merchant\response\CompletePurchaseResponse;
17
use hiqdev\php\merchant\response\RedirectPurchaseResponse;
18
use Omnipay\BitPay\Gateway;
19
20
/**
21
 * Class BitPayAdapter.
22
 *
23
 * @author Dmytro Naumenko <[email protected]>
24
 */
25
class BitPayMerchant extends AbstractMerchant
26
{
27
    /**
28
     * @return Gateway
29
     */
30 3
    protected function createGateway()
31
    {
32 3
        return $this->gatewayFactory->build('BitPay', [
33 3
            'token' => $this->credentials->getKey1(),
34 3
            'privateKey'  => $this->credentials->getKey2(),
35 3
            'publicKey' => $this->credentials->getKey3(),
36 3
            'testMode' => $this->getCredentials()->isTestMode(),
37
        ]);
38
    }
39
40
    /**
41
     * @param InvoiceInterface $invoice
42
     * @return RedirectPurchaseResponse
43
     */
44 1 View Code Duplication
    public function requestPurchase(InvoiceInterface $invoice)
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...
45
    {
46
        /**
47
         * @var \Omnipay\BitPay\Message\PurchaseResponse
48
         */
49 1
        $response = $this->gateway->purchase([
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Omnipay\Common\GatewayInterface as the method purchase() does only exist in the following implementations of said interface: Omnipay\BitPay\Gateway, Omnipay\CoinGate\Gateway, Omnipay\FreeKassa\Gateway, Omnipay\Ikajo\Gateway, Omnipay\InterKassa\Gateway, Omnipay\OKPAY\Gateway, Omnipay\Paxum\Gateway, Omnipay\PayPal\Gateway, Omnipay\RoboKassa\Gateway, Omnipay\TwoCheckoutPlus\Gateway, Omnipay\TwoCheckoutPlus\TokenGateway, Omnipay\WebMoney\Gateway, Omnipay\YandexKassa\Gateway, Omnipay\YandexMoney\P2pGateway, Omnipay\ePayService\Gateway, Omnipay\ePayments\Gateway.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
50 1
            'transactionId' => $invoice->getId(),
51 1
            'description' => $invoice->getDescription(),
52 1
            'amount' => $this->moneyFormatter->format($invoice->getAmount()),
53 1
            'currency' => $invoice->getCurrency()->getCode(),
54 1
            'returnUrl' => $invoice->getReturnUrl(),
55 1
            'notifyUrl' => $invoice->getNotifyUrl(),
56 1
            'cancelUrl' => $invoice->getCancelUrl(),
57 1
        ])->send();
58
59 1
        if ($response->getRedirectUrl() === null) {
60
            throw new MerchantException('Failed to request purchase');
61
        }
62
63 1
        $response = new RedirectPurchaseResponse($response->getRedirectUrl(), $response->getRedirectData());
64 1
        $response->setMethod('GET');
65
66 1
        return $response;
67
    }
68
69
    /**
70
     * @param array $data
71
     * @return CompletePurchaseResponse
72
     */
73 1
    public function completePurchase($data)
74
    {
75
        /** @var \Omnipay\BitPay\Message\CompletePurchaseResponse $response */
76 1
        $response = $this->gateway->completePurchase($data)->send();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Omnipay\Common\GatewayInterface as the method completePurchase() does only exist in the following implementations of said interface: Omnipay\BitPay\Gateway, Omnipay\CoinGate\Gateway, Omnipay\FreeKassa\Gateway, Omnipay\Ikajo\Gateway, Omnipay\InterKassa\Gateway, Omnipay\OKPAY\Gateway, Omnipay\Paxum\Gateway, Omnipay\PayPal\Gateway, Omnipay\RoboKassa\Gateway, Omnipay\TwoCheckoutPlus\Gateway, Omnipay\WebMoney\Gateway, Omnipay\YandexKassa\Gateway, Omnipay\YandexMoney\P2pGateway, Omnipay\ePayService\Gateway, Omnipay\ePayments\Gateway.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
77
78 1
        return (new CompletePurchaseResponse())
79 1
            ->setIsSuccessful($response->isSuccessful())
0 ignored issues
show
Documentation introduced by
$response->isSuccessful() is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
80 1
            ->setAmount($this->moneyParser->parse($response->getAmount(), $response->getCurrency()))
81 1
            ->setFee($this->moneyParser->parse($response->getFee(), $response->getCurrency()))
82 1
            ->setTransactionReference($response->getTransactionReference())
83 1
            ->setTransactionId($response->getTransactionId())
84 1
            ->setPayer($response->getPayer())
85 1
            ->setTime(new \DateTime($response->getTime()));
86
    }
87
}
88