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 |
||
| 19 | final class PaymentBuilder implements PaymentBuilderInterface |
||
| 20 | { |
||
| 21 | const CARD = 'IZETTLE_CARD'; |
||
| 22 | const CASH = 'IZETTLE_CASH'; |
||
| 23 | const INVOICE = 'IZETTLE_INVOICE'; |
||
| 24 | const MOBILE = 'MOBILE_PAY'; |
||
| 25 | const SWISH = 'SWISH'; |
||
| 26 | const VIPPS = 'VIPPS'; |
||
| 27 | |||
| 28 | 3 | public function buildFromArray(array $payments, Currency $currency): array |
|
| 29 | { |
||
| 30 | 3 | $data = []; |
|
| 31 | 3 | foreach ($payments as $payment) { |
|
| 32 | 3 | $data[] = $this->build($payment, $currency); |
|
| 33 | } |
||
| 34 | |||
| 35 | 3 | return $data; |
|
| 36 | } |
||
| 37 | |||
| 38 | 11 | public function build(array $payment, Currency $currency): AbstractPayment |
|
| 39 | { |
||
| 40 | 11 | switch ($payment['type']) { |
|
| 41 | 11 | case self::CARD: |
|
| 42 | 4 | return $this->parseCardPayment($payment, $currency); |
|
| 43 | 8 | case self::CASH: |
|
| 44 | 3 | return $this->parseCashPayment($payment, $currency); |
|
| 45 | 5 | case self::INVOICE: |
|
| 46 | 1 | return $this->parseInvoicePayment($payment, $currency); |
|
| 47 | 4 | case self::MOBILE: |
|
| 48 | 1 | return $this->parseMobilePayment($payment, $currency); |
|
| 49 | 3 | case self::SWISH: |
|
| 50 | 1 | return $this->parseSwichPayment($payment, $currency); |
|
| 51 | 2 | case self::VIPPS: |
|
| 52 | 1 | return $this->parseVippsPayment($payment, $currency); |
|
| 53 | default: |
||
| 54 | 1 | throw new PaymentTypeNotConfiguredException('Payment type \'' . $payment['type'] . '\' not configured'); |
|
| 55 | } |
||
| 56 | } |
||
| 57 | |||
| 58 | 4 | private function parseCardPayment($payment, Currency $currency): CardPayment |
|
| 73 | |||
| 74 | 3 | private function parseCashPayment($payment, Currency $currency): CashPayment |
|
| 82 | |||
| 83 | 1 | View Code Duplication | private function parseInvoicePayment($payment, Currency $currency): InvoicePayment |
| 90 | |||
| 91 | 1 | View Code Duplication | private function parseMobilePayment($payment, Currency $currency): MobilePayment |
| 98 | |||
| 99 | 1 | View Code Duplication | private function parseSwichPayment($payment, Currency $currency): SwishPayment |
| 106 | |||
| 107 | 1 | View Code Duplication | private function parseVippsPayment($payment, Currency $currency): VippsPayment |
| 114 | |||
| 115 | 4 | private function getFromKey($key, array $data) |
|
| 123 | } |
||
| 124 |