FormHandler   B
last analyzed

Complexity

Total Complexity 45

Size/Duplication

Total Lines 200
Duplicated Lines 18 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 45
c 1
b 0
f 0
lcom 1
cbo 3
dl 36
loc 200
ccs 0
cts 124
cp 0
rs 8.3673

4 Methods

Rating   Name   Duplication   Size   Complexity  
B getChecksum() 0 32 5
D setParameter() 36 98 34
A __construct() 0 4 1
B getParameters() 0 19 5

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like FormHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FormHandler, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace Bpost\BpostApiClient;
3
4
use Bpost\BpostApiClient\Exception\BpostLogicException\BpostInvalidLengthException;
5
use Bpost\BpostApiClient\Exception\BpostLogicException\BpostInvalidValueException;
6
7
/**
8
 * bPost Form handler class
9
 *
10
 * @author Tijs Verkoyen <[email protected]>
11
 */
12
class FormHandler
13
{
14
    /**
15
     * bPost instance
16
     *
17
     * @var Bpost
18
     */
19
    private $bpost;
20
21
    /**
22
     * The parameters
23
     *
24
     * @var array
25
     */
26
    private $parameters = array();
27
28
    /**
29
     * Create bPostFormHandler instance
30
     *
31
     * @param string $accountId
32
     * @param string $passPhrase
33
     * @param string $apiUrl
34
     */
35
    public function __construct($accountId, $passPhrase, $apiUrl = Bpost::API_URL)
36
    {
37
        $this->bpost = new Bpost($accountId, $passPhrase, $apiUrl);
38
    }
39
40
    /**
41
     * Calculate the hash
42
     *
43
     * @return string
44
     */
45
    private function getChecksum()
46
    {
47
        $keysToHash = array(
48
            'accountId',
49
            'action',
50
            'costCenter',
51
            'customerCountry',
52
            'deliveryMethodOverrides',
53
            'extraSecure',
54
            'orderReference',
55
            'orderWeight',
56
        );
57
        $base = 'accountId=' . $this->bpost->getAccountId() . '&';
58
59
        foreach ($keysToHash as $key) {
60
            if (isset($this->parameters[$key])) {
61
                 if (! is_array($this->parameters[$key])) {
62
                    $base .= $key.'='.$this->parameters[$key].'&';
63
                } else {
64
                    foreach ($this->parameters[$key] as $entry) {
65
                        $base .= $key.'='.$entry.'&';
66
                    }
67
                }
68
            }
69
        }
70
71
        // add passphrase
72
        $base .= $this->bpost->getPassPhrase();
73
74
        // return the hash
75
        return hash('sha256', $base);
76
    }
77
78
    /**
79
     * Get the parameters
80
     *
81
     * @param  bool  $form
82
     * @param  bool  $includeChecksum
83
     * @return array
84
     */
85
    public function getParameters($form = false, $includeChecksum = true)
86
    {
87
        $return = $this->parameters;
88
89
        if ($form && isset($return['orderLine'])) {
90
            foreach ($return['orderLine'] as $key => $value) {
91
                $return['orderLine[' . $key . ']'] = $value;
92
            }
93
94
            unset($return['orderLine']);
95
        }
96
97
        if ($includeChecksum) {
98
            $return['accountId'] = $this->bpost->getAccountId();
99
            $return['checksum'] = $this->getChecksum();
100
        }
101
102
        return $return;
103
    }
104
105
    /**
106
     * Set a parameter
107
     *
108
     * @param string $key
109
     * @param mixed  $value
110
     * @throws BpostInvalidValueException
111
     * @throws BpostInvalidLengthException
112
     */
113
    public function setParameter($key, $value)
114
    {
115
        switch ((string) $key) {
116
            // limited values
117
            case 'action':
118
            case 'lang':
119
                $allowedValues['action'] = array('START', 'CONFIRM');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$allowedValues was never initialized. Although not strictly required by PHP, it is generally a good practice to add $allowedValues = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
120
                $allowedValues['lang'] = array('NL', 'FR', 'EN', 'DE', 'Default');
121
122
                if (!in_array($value, $allowedValues[$key])) {
123
                    throw new BpostInvalidValueException($key, $value, $allowedValues[$key]);
124
                }
125
                $this->parameters[$key] = $value;
126
                break;
127
128
            // maximum 2 chars
129 View Code Duplication
            case 'customerCountry':
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...
130
                if (mb_strlen($value) > 2) {
131
                    throw new BpostInvalidLengthException($key, mb_strlen($value), 2);
132
                }
133
                $this->parameters[$key] = (string) $value;
134
                break;
135
136
            // maximum 8 chars
137
            case 'customerStreetNumber':
138 View Code Duplication
            case 'customerBox':
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...
139
                if (mb_strlen($value) > 8) {
140
                    throw new BpostInvalidLengthException($key, mb_strlen($value), 8);
141
                }
142
                $this->parameters[$key] = (string) $value;
143
                break;
144
145
            // maximum 20 chars
146 View Code Duplication
            case 'customerPhoneNumber':
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...
147
                if (mb_strlen($value) > 20) {
148
                    throw new BpostInvalidLengthException($key, mb_strlen($value), 20);
149
                }
150
                $this->parameters[$key] = (string) $value;
151
                break;
152
153
            // maximum 32 chars
154 View Code Duplication
            case 'customerPostalCode':
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...
155
                if (mb_strlen($value) > 32) {
156
                    throw new BpostInvalidLengthException($key, mb_strlen($value), 32);
157
                }
158
                $this->parameters[$key] = (string) $value;
159
                break;
160
161
            // maximum 40 chars
162
            case 'customerFirstName':
163
            case 'customerLastName':
164
            case 'customerCompany':
165
            case 'customerStreet':
166 View Code Duplication
            case 'customerCity':
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...
167
                if (mb_strlen($value) > 40) {
168
                    throw new BpostInvalidLengthException($key, mb_strlen($value), 40);
169
                }
170
                $this->parameters[$key] = (string) $value;
171
                break;
172
173
            // maximum 50 chars
174
            case 'orderReference':
175
            case 'costCenter':
176 View Code Duplication
            case 'customerEmail':
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...
177
                if (mb_strlen($value) > 50) {
178
                    throw new BpostInvalidLengthException($key, mb_strlen($value), 50);
179
                }
180
                $this->parameters[$key] = (string) $value;
181
                break;
182
183
            // integers
184
            case 'orderTotalPrice':
185
            case 'orderWeight':
186
                $this->parameters[$key] = (int) $value;
187
                break;
188
189
            // array
190
            case 'orderLine':
191
                if (!isset($this->parameters[$key])) {
192
                    $this->parameters[$key] = array();
193
                }
194
                $this->parameters[$key][] = $value;
195
                break;
196
197
            // unknown
198
            case 'deliveryMethodOverrides':
199
            case 'extra':
200
            case 'extraSecure':
201
            case 'confirmUrl':
202
            case 'cancelUrl':
203
            case 'errorUrl':
204
            default:
205
                if (is_array($value)) {
206
                    sort($value);
207
                }
208
                $this->parameters[$key] = $value;
209
        }
210
    }
211
}
212