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 |
||
| 23 | class PaystackAdapter implements AdapterInterface |
||
| 24 | { |
||
| 25 | |||
| 26 | use Pluggable, Payable; |
||
| 27 | |||
| 28 | /** |
||
| 29 | * @var string |
||
| 30 | */ |
||
| 31 | const API_LINK = 'https://api.paystack.co'; |
||
| 32 | |||
| 33 | /** |
||
| 34 | * @var \GuzzleHttp\Client |
||
| 35 | */ |
||
| 36 | protected $httpClient; |
||
| 37 | |||
| 38 | /** |
||
| 39 | * The Api link for paystack |
||
| 40 | * @var string |
||
| 41 | */ |
||
| 42 | protected $baseUrl; |
||
| 43 | |||
| 44 | /** |
||
| 45 | * PaystackAdapter constructor. |
||
| 46 | * @param \GuzzleHttp\Client|null $client |
||
| 47 | */ |
||
| 48 | 13 | public function __construct(Client $client = null) |
|
| 49 | { |
||
| 50 | 13 | $this->baseUrl = self::API_LINK; |
|
| 51 | 13 | $this->httpClient = $client ?? $this->setHttpClient(env("PAYSTACK_SECRET_KEY")); |
|
|
|
|||
| 52 | 13 | $this->registerPlugins(); |
|
| 53 | 13 | } |
|
| 54 | |||
| 55 | 13 | protected function registerPlugins() |
|
| 56 | { |
||
| 57 | 13 | $this->addPlugin(new GetPaymentData($this->baseUrl)) |
|
| 58 | 13 | ->addPlugin(new ChargeWithToken($this->baseUrl)); |
|
| 59 | 13 | } |
|
| 60 | |||
| 61 | /** |
||
| 62 | * @param array $data |
||
| 63 | * @return string The authorization url to render the secure payment gateway. |
||
| 64 | */ |
||
| 65 | 3 | public function charge(array $data) |
|
| 66 | { |
||
| 67 | |||
| 68 | 3 | $response = $this->decodeResponse( |
|
| 69 | 3 | $this->authorizeTransaction("/transaction/initialize", $data), |
|
| 70 | 2 | true |
|
| 71 | ); |
||
| 72 | |||
| 73 | 2 | return $response['data']['authorization_url']; |
|
| 74 | } |
||
| 75 | |||
| 76 | /** |
||
| 77 | * @param \Psr\Http\Message\ResponseInterface $response |
||
| 78 | * @param bool $associative |
||
| 79 | * @return mixed |
||
| 80 | */ |
||
| 81 | 2 | protected function decodeResponse(ResponseInterface $response, $associative = false) |
|
| 82 | { |
||
| 83 | 2 | return json_decode($response->getBody(), $associative); |
|
| 84 | } |
||
| 85 | |||
| 86 | /** |
||
| 87 | * @return \GuzzleHttp\Client |
||
| 88 | */ |
||
| 89 | 8 | public function getHttpClient(): Client |
|
| 90 | { |
||
| 91 | 8 | return $this->httpClient; |
|
| 92 | } |
||
| 93 | |||
| 94 | /** |
||
| 95 | * @codeCoverageIgnore |
||
| 96 | * @param string $token |
||
| 97 | * @return \GuzzleHttp\Client |
||
| 98 | */ |
||
| 99 | View Code Duplication | protected function setHttpClient(string $token) : Client |
|
| 110 | } |
||
| 111 |