I'm using PHP/Laravel and I have two controllers.
- Controllers/PaymentController
- Controllers/PaymentExpressControler
They both create an request which is exactly the same, but it has some differences.
Let's say, they both use createRequest(Request $Request)
which is a POST request to a third-party api.
I'm wondering how can I reduce the code, because it's clearly duplicated.
I was thinking of two options, a trait or a class.
- Controllers/Payment/(NameOfThirdParty).php which is a class with createRequest
How would this sound like?
My current createRequest
protected function createRequest(Request $request)
{
$this->cartCollection();
$availableMethods = ['mb', 'mbw', 'cc', 'dd'];
$tkey = uniqid(Auth::id(), true);
if (in_array($request->type, $availableMethods)) {
$payment_body = [
"method" => $request->type,
"value" => (float)\Cart::getTotal(),
"currency" => "EUR",
"key" => $tkey,
"type" => "sale",
"customer" =>
[
"name" => Auth::user()->name,
"email" => Auth::user()->email,
"phone" => isset($request->telm) ? $request->telm : "",
],
"capture" =>
[
"descriptive" => "Order",
"transaction_key" => $tkey,
],
];
if ($request->type == 'dd') {
$sdd_mandate = ['sdd_mandate' => [
"iban" => $request->iban,
"account_holder" => Auth::user()->name,
"name" => Auth::user()->name,
"email" => Auth::user()->email,
"phone" => isset($request->telm) ? $request->telm : "0000000",
"country_code" => "EU",
]];
$payment_body = array_merge($payment_body, $sdd_mandate);
}
$response = Http::withHeaders([
'AccountId' => config('payment.accountId'),
'ApiKey' => config('payment.apiKey'),
'Content-Type' => 'application/json',
])->post('REMOVED API LINK', $payment_body);
$this->addToPreOrdersTable($tkey);
return $response->collect();
}
}
}
protected function addToPreOrdersTable(string $hash)
{
$this->cartCollection();
OrderService::createPreOrder($this->contents, $hash, 'buy');
}
addToPreOrdersTable Is also in both controllers.
protected function index(Request $request)
{
if (isset($request->type)) {
$result = $this->createRequest($request);
$status = $result['status'];
if ($status == 'ok') {
$type = $result['method']['type'];
switch ($type) {
case 'cc':
return redirect($result['method']['url']);
case 'mb':
return view('payment', ['type' => 'mb', 'data' => $result['method']]);
case 'mbw':
return view('payment', ['type' => 'mbw']);
case 'dd':
return view('payment', ['type' => 'dd', 'data' => $result['method']]);
}
}
return back()->withInput()->withErrors(['Error' => 'An error has occured.']);
}
return view('payment');
}