Completed
Push — master ( b7b0a0...5b805f )
by Dmitry
02:45
created

CompletePurchaseResponse   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 167
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 93.62%

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 2
dl 0
loc 167
ccs 44
cts 47
cp 0.9362
rs 10
c 0
b 0
f 0

13 Methods

Rating   Name   Duplication   Size   Complexity  
A getRequest() 0 4 1
A __construct() 0 18 4
A isSuccessful() 0 4 1
A getTransactionId() 0 4 1
A getTransactionReference() 0 4 1
A getTransactionStatus() 0 4 1
A getAmount() 0 4 1
A getTime() 0 7 1
A getCurrency() 0 4 1
A getTestMode() 0 4 1
A getPayer() 0 4 1
A getHash() 0 4 1
A calculateHash() 0 34 5
1
<?php
2
/**
3
 * Paxum driver for PHP merchant library
4
 *
5
 * @link      https://github.com/hiqdev/omnipay-paxum
6
 * @package   omnipay-paxum
7
 * @license   MIT
8
 * @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace Omnipay\Paxum\Message;
12
13
use Omnipay\Common\Exception\InvalidResponseException;
14
use Omnipay\Common\Message\AbstractResponse;
15
use Omnipay\Common\Message\RequestInterface;
16
17
/**
18
 * Paxum Complete Purchase Response.
19
 */
20
class CompletePurchaseResponse extends AbstractResponse
21
{
22
    /**
23
     * @return AbstractRequest|RequestInterface
24
     */
25
    public function getRequest()
26
    {
27
        return parent::getRequest();
28
    }
29
30
    /**
31
     * @param RequestInterface $request
32
     * @param array $data
33
     * @throws InvalidResponseException when the request validation fails
34
     */
35 4
    public function __construct(RequestInterface $request, $data)
36
    {
37 4
        $this->request = $request;
38 4
        $this->data    = $data;
39
40 4
        if ($this->getTransactionStatus() !== 'done') {
41 1
            throw new InvalidResponseException('Transaction not done');
42
        }
43
44 3
        if ($this->getHash() !== $this->calculateHash()) {
45
            // echo "hashes: '" . $this->getHash() . "' - '" . $this->calculateHash() . "'\n";
46
            throw new InvalidResponseException('Invalid hash');
47
        }
48
49 3
        if ($this->request->getTestMode() !== $this->getTestMode()) {
50 1
            throw new InvalidResponseException('Invalid test mode');
51
        }
52 2
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 1
    public function isSuccessful()
58
    {
59 1
        return true;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     * @return string
65
     */
66 1
    public function getTransactionId()
67
    {
68 1
        return $this->data['item_id'];
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     * @return string
74
     */
75 1
    public function getTransactionReference()
76
    {
77 1
        return $this->data['transaction_id'];
78
    }
79
80 4
    public function getTransactionStatus()
81
    {
82 4
        return $this->data['transaction_status'];
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     * @return string
88
     */
89 1
    public function getAmount()
90
    {
91 1
        return $this->data['transaction_amount'];
92
    }
93
94
    /**
95
     * Get payment time.
96
     *
97
     * @return string
98
     */
99 1
    public function getTime()
100
    {
101 1
        $time = new \DateTime($this->data['transaction_date'], new \DateTimeZone('EST'));
102 1
        $time->setTimezone(new \DateTimeZone('UTC'));
103
104 1
        return $time->format('c');
105
    }
106
107
    /**
108
     * Get payment currency.
109
     *
110
     * @return string
111
     */
112 1
    public function getCurrency()
113
    {
114 1
        return $this->data['transaction_currency'];
115
    }
116
117
    /**
118
     * Get test mode.
119
     *
120
     * @return string
121
     */
122 3
    public function getTestMode()
123
    {
124 3
        return $this->data['test'] === '1';
125
    }
126
127
    /**
128
     * Get payer info - name, username and id.
129
     *
130
     * @return string
131
     */
132 1
    public function getPayer()
133
    {
134 1
        return $this->data['buyer_name'] . '/' . $this->data['buyer_username'] . '/' . $this->data['buyer_id'];
135
    }
136
137
    /**
138
     * Get hash from request.
139
     *
140
     * @return string
141
     */
142 3
    public function getHash()
143
    {
144 3
        return $this->data['key'];
145
    }
146
147
    /**
148
     * Calculate hash to validate incoming IPN notifications.
149
     *
150
     * @return string
151
     */
152 3
    public function calculateHash()
153
    {
154
        // this is the documentation way
155 3
        $raw = file_get_contents('php://input');
156 3
        $fields = substr($raw, 0, strpos($raw, '&key='));
157 3
        $secret = $this->request->getSecret();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Omnipay\Common\Message\RequestInterface as the method getSecret() does only exist in the following implementations of said interface: Omnipay\Paxum\Message\AbstractRequest, Omnipay\Paxum\Message\CompletePurchaseRequest, Omnipay\Paxum\Message\PurchaseRequest.

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...
158 3
        $supposed_hash = md5($fields . $secret);
0 ignored issues
show
Unused Code introduced by
$supposed_hash 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...
159
160
        // this is how they actually get it
161 3
        $kvs = '';
162 3
        foreach ($this->data as $k => $v) {
163 3
            if ($k !== 'key' && $k !== 'username') {
164 3
                $kvs .= ($kvs ? '&' : '') . "$k=$v";
165 3
            }
166 3
        }
167 3
        $hash = md5($kvs);
0 ignored issues
show
Unused Code introduced by
$hash 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...
168
169
        /* Testing facility
170
        dlog([
171
            'key'    => $this->getHash(),
172
            'fields' => $fields,
173
            'kvs'    => $kvs,
174
            'secret' => $secret,
175
            'hash'   => $hash,
176
            'h2'     => md5($fields),
177
            'h3'     => md5($fields . $secret),
178
            'kh3'    => md5($kvs),
179
            'kh4'    => md5($kvs . $secret),
180
        ]); */
181
182
        /// tmp fix
183 3
        return $this->getHash();
184
        //return $hash;
185
    }
186
}
187