-
app/Http/Actions/CalculateResultAction.php
Open in GitHubclass CalculateResultAction { protected $request; public function __construct($request) { $this->request = $request; } public function action() { $number1 = $this->request->input1; $number2 = $this->request->input2; $operand = $this->request->operand; // addition, subtraction, multiplication, division return $this->{$operand}($number1, $number2); } private function addition($number1, $number2) : float { return (float)($number1 + $number2); } private function subtraction($number1, $number2) : float { return (float)($number1 - $number2); } private function multiplication($number1, $number2) : float { return (float)($number1 * $number2); } private function division($number1, $number2) { return $number2 != 0 ? round($number1 / $number2, 5) : 'Division by Zero'; } }
-
app/Http/Controllers/CalculatorController.php
Open in GitHubuse App\Http\Actions\CalculateResultAction; use App\Http\Requests\CalculatorRequest; use Exception; use Illuminate\Http\JsonResponse; class CalculatorController extends Controller { // public function calculate(CalculatorRequest $request): JsonResponse { try { $result = (new CalculateResultAction($request))->action(); $status = 200; $error = null; $message = 'Success!'; } catch (Exception $e) { $result = null; $status = 500; $error = $e->getMessage; $message = 'Something went wrong!'; } return response()->json([ 'result' => $result, 'error' => $error, 'message' => $message ], $status); } }