Optimize in_array function without using isset? - php

How to optimize in_array in my function?
I tried isset but it doesn't work.
public function index() {
$this->checkPermission();
$banks = BankAccount::all();
$clients = Role::whereRoleSlug('client')
->firstOrFail()
->users;
$projects = Project::whereProjectStatus('active')->get();
$adminBanks = BankAccount::where('bank_user_id', '=', null)->get();
$roles = Role::whereIn('role_slug', ['administrator', 'accountant'])
->pluck('role_id')
->toArray();
$cash = 0;
$payments = Payment::wherePaymentBy('cash')->get();
/*->filter(function ($payment) {
return in_array($payment->activity->activityBy->id, $roles)
});*/
foreach ($payments as $index => $payment) {
if(in_array($payment->activity->activityBy->role_id, $roles)) {
if(in_array(strtolower($payment->payment_purpose), ['employee_transfer', 'employee_refund', 'vendor_payment', 'vendor_refund', 'loan_payment', 'salary', 'office_deposit'])) {
$cash -= $payment->payment_amount;
}
else {
$cash += $payment->payment_amount;
}
}
}
// foreach ($payments as $index => $payment) {
// if (isset($payment->activity->activityBy->role_id, $roles)) {
// if (isset($payment['employee_transfer'], $payment['employee_refund'], $payment['vendor_payment'], $payment['vendor_refund'], $payment['loan_payment'], $payment['salary'], $payment['office_deposit'])) {
// $cash -= $payment->payment_amount;
//// dd($roles);
// } else {
// $cash += $payment->payment_amount;
// }
// }
// }
return view('admin.accounting.banks.index')
->with([
'adminBanks' => $adminBanks,
'banks' => $banks,
'clients' => $clients,
'projects' => $projects,
'cash' => $cash
]);
}
public function bankDetails($id) {
if(!Auth::user()->isAdmin() && !Auth::user()->isAccountant()) {
return redirectBackWithNotification('error', 'You are not authorised!');
}
if($id == 'cash') {
$projects = Project::select(['bsoft_projects.project_id', 'bsoft_projects.project_name'])->get();
return view('admin.accounting.banks.show')
->with([
'projects' => $projects
]);
}
$bank = BankAccount::findOrFail($id);
if(!$bank->user) {
$payments = Payment::where('payment_from_bank_account', '=', $bank->bank_id)
->orWhere('payment_to_bank_account', '=', $bank->bank_id)
->get();
$balance = $bank->bank_balance;
}
else {
$payments = Payment::where('payment_from_bank_account', '=', $bank->bank_id)
->orWhere('payment_to_bank_account', '=', $bank->bank_id)
->orWhere('payment_to_user', '=', $bank->user->id)
->orWhere('payment_from_user', '=', $bank->user->id)
->get();
$balance = 0;
$exp = 0;
$inc = 0;
foreach ($payments as $payment) {
if($payment->payment_from_user == $bank->user->id) {
$exp += $payment->payment_amount;
}
elseif ($payment->payment_to_user == $bank->user->id) {
$inc += $payment->payment_amount;
}
}
$balance = $inc - $exp;
}
return view('admin.accounting.banks.show')
->with([
'bank' => $bank,
'payments' => $payments,
'balance' => $balance
]);
}
public function rechargeFromCustomer(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'user_id' => ['required', 'numeric'],
'bank_id' => ['nullable', 'numeric'],
'project_id' => ['required', 'numeric'],
'type' => ['required', 'string'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
$payment = createNewPayment([
'type' => 'credit',
'to_user' => null,
'from_user' => $request->post('user_id'),
'to_bank_account' => (strtolower($request->post('type')) === 'bank' || strtolower($request->post('type')) === 'check')
? $request->post('bank_id') : null,
'from_bank_account' => null,
'amount' => $request->post('amount'),
'project' => $request->post('project_id'),
'purpose' => 'project_money',
'by' => $request->post('type'),
'date' => $request->post('date'),
'image' => null,
'note' => $request->post('note')
]);
if(!$payment) {
return redirectBackWithNotification();
}
if(strtolower($request->post('type')) === 'bank' || $request->post('type') == 'check') {
$offBank = BankAccount::findOrFail($request->post('bank_id'));
$offBank->bank_balance = $offBank->bank_balance + (float) $request->post('amount');
$offBank->save();
}
return redirectBackWithNotification('success', 'Client Money Successfully Received!');
}
public function storeAccount(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'user_id' => ['nullable', 'numeric'],
'name' => ['required', 'string'],
'number' => ['required', 'string'],
'bank' => ['required', 'string'],
'branch' => ['required', 'string'],
'balance' => ['required', 'numeric'],
'accountFor' => ['required', 'string'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
$bank = new BankAccount();
$bank->bank_user_id = ($request->post('user_id')) ? $request->post('user_id') : null;
$bank->bank_account_name = $request->post('name');
$bank->bank_account_no = $request->post('number');
$bank->bank_name = $request->post('bank');
$bank->bank_branch = $request->post('branch');
$bank->bank_balance = $request->post('balance');
if(!$bank->save()) {
return redirectBackWithNotification();
}
addActivity('bank', $bank->bank_id, 'Bank Account Added');
return redirectBackWithNotification('success', 'Bank Account Successfully Added!');
}
public function transferToEmployee(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'employee_id' => ['required', 'string'],
'bank_id' => ['nullable', 'numeric'],
'project_id' => ['required', 'numeric'],
'type' => ['required', 'string'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
if(strtolower($request->post('type')) !== 'cash' && $request->post('bank_id') === null) {
return redirectBackWithNotification('error', 'Bank Account must be selected!');
}
$employee_id = $request->post('employee_id');
$employee_bank_id = null;
if(strpos($request->post('employee_id'), '#') !== false) {
$employee_id = Str::before($request->post('employee_id'), '#');
$employee_bank_id = Str::after($request->post('employee_id'), '#');
}
$paymentData = [
'type' => null,
'to_user' => $employee_id,
'from_user' => Auth::id(),
'to_bank_account' => $employee_bank_id,
'from_bank_account' => (strtolower($request->post('type')) !== 'cash') ? $request->post('bank_id') : null,
'amount' => $request->post('amount'),
'project' => $request->post('project_id'),
'purpose' => 'employee_transfer',
'by' => strtolower($request->post('type')),
'date' => $request->post('date'),
'image' => null,
'note' =>$request->post('note')
];
if(!createNewPayment($paymentData)) {
return redirectBackWithNotification();
}
if(strtolower($request->post('type')) === 'bank' || $request->post('payment_by') == 'check') {
$officeBank = BankAccount::findOrFail($request->post('bank_id'));
$officeBank->bank_balance = $officeBank->bank_balance - (float) $request->post('amount');
$officeBank->save();
$employeeBank = BankAccount::findOrFail($employee_bank_id);
$employeeBank->bank_balance = $employeeBank->bank_balance + (float) $request->post('amount');
$employeeBank->save();
}
return redirectBackWithNotification('success', 'Transfer successfully made!');
}
public function transferToOffice(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'employee_id' => ['required', 'string'],
'bank_id' => ['nullable', 'numeric'],
'project_id' => ['required', 'numeric'],
'type' => ['required', 'string'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
if(strtolower($request->post('type')) !== 'bank' && $request->post('bank_id') === null) {
return redirectBackWithNotification('error', 'Bank Account must be selected!');
}
$employee_id = $request->post('employee_id');
$employee_bank_id = null;
if(strpos($request->post('employee_id'), '#') !== false) {
$employee_id = Str::before($request->post('employee_id'), '#');
$employee_bank_id = Str::after($request->post('employee_id'), '#');
}
else {
$employee_bank_id = $this->createAutoGeneratedAccount($employee_id)->bank_id;
}
$paymentData = [
'type' => null,
'to_user' => $employee_id,
'from_user' => null,
'to_bank_account' => $employee_bank_id,
'from_bank_account' => (strtolower($request->post('type')) === 'bank') ? $request->post('bank_id') : null,
'amount' => $request->post('amount') - ($request->post('amount') * 2),
'project' => $request->post('project_id'),
'purpose' => 'employee_refund',
'by' => strtolower($request->post('type')),
'date' => $request->post('date'),
'image' => null,
'note' =>$request->post('note')
];
if(!createNewPayment($paymentData)) {
return redirectBackWithNotification();
}
if(strtolower($request->post('type')) === 'bank' || $request->post('payment_by') == 'check') {
$officeBank = BankAccount::findOrFail($request->post('bank_id'));
$officeBank->bank_balance = $officeBank->bank_balance + (float) $request->post('amount');
$officeBank->save();
}
$employeeBank = BankAccount::findOrFail($employee_bank_id);
$employeeBank->bank_balance = $employeeBank->bank_balance - (float) $request->post('amount');
$employeeBank->save();
return redirectBackWithNotification('success', 'Money successfully refunded!');
}
public function withdrawFromBank(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'bank_id' => ['nullable', 'numeric'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
$paymentData = [
'type' => null,
'to_user' => null,
'from_user' => null,
'to_bank_account' => null,
'from_bank_account' => $request->post('bank_id'),
'amount' => $request->post('amount'),
'project' => null,
'purpose' => 'office_withdraw',
'by' => 'cash',
'date' => $request->post('date'),
'image' => null,
'note' =>$request->post('note')
];
if(!createNewPayment($paymentData)) {
return redirectBackWithNotification();
}
$officeBank = BankAccount::findOrFail($request->post('bank_id'));
$officeBank->bank_balance = $officeBank->bank_balance - (float) $request->post('amount');
$officeBank->save();
return redirectBackWithNotification('success', 'Money successfully Withdrawn!');
}
public function depositToBank(Request $request) {
$this->checkPermission();
$validator = Validator::make($request->all(), [
'bank_id' => ['nullable', 'numeric'],
'amount' => ['required', 'numeric'],
'date' => ['required', 'date'],
]);
if($validator->fails()) {
return redirectBackWithValidationError($validator);
}
$paymentData = [
'type' => null,
'to_user' => null,
'from_user' => null,
'to_bank_account' => $request->post('bank_id'),
'from_bank_account' => null,
'amount' => $request->post('amount'),
'project' => null,
'purpose' => 'office_deposit',
'by' => 'cash',
'date' => $request->post('date'),
'image' => null,
'note' =>$request->post('note')
];
if(!createNewPayment($paymentData)) {
return redirectBackWithNotification();
}
$officeBank = BankAccount::findOrFail($request->post('bank_id'));
$officeBank->bank_balance = $officeBank->bank_balance + (float) $request->post('amount');
$officeBank->save();
return redirectBackWithNotification('success', 'Money successfully Deposited!');
}
public function income() {
$this->checkPermission();
$projects = Project::select(['bsoft_projects.project_id', 'bsoft_projects.project_name'])->get();
return view('admin.accounting.income')
->with([
'projects' => $projects
]);
}
public function expense() {
$this->checkPermission();
$projects = Project::select(['bsoft_projects.project_id', 'bsoft_projects.project_name'])->get();
return view('admin.accounting.expense')
->with([
'projects' => $projects
]);
}
public function getUsers(Request $request) {
$this->checkPermission();
$users = Role::whereRoleSlug($request->post('type'))->firstOrFail()
->users;
return view('admin.accounting.banks.ajax-users')
->with([
'users' => $users
]);
}
public function getClientProjects(Request $request) {
$this->checkPermission();
$projects = User::findOrFail($request->post('client_id'))->clientProjects()
->where('project_status', '=', 'active')->get();
return view('admin.accounting.banks.ajax-projects')
->with([
'projects' => $projects
]);
}
public function getManagers(Request $request) {
$this->checkPermission();
$roles = Role::whereIn('role_slug', ['manager'])
->pluck('role_id')
->toArray();
$users = Project::findOrFail($request->post('project_id'))->employees()
->whereIn('role_id', $roles)
->get();
return view('admin.accounting.banks.ajax-employees')
->with([
'users' => $users
]);
}
/**
* #return bool|\Illuminate\Http\RedirectResponse
*/
protected function checkPermission() {
$role = Auth::user()->role->role_slug;
if($role == 'administrator' || $role == 'accountant') {
return true;
}
return redirectBackWithNotification('error', 'Sorry! You Are Not Authorised!.');
}
protected function createAutoGeneratedAccount(int $id) {
$employee = User::findOrFail($id);
$bank = new BankAccount();
$bank->bank_account_name = 'Auto Generated Bank Account!';
$bank->bank_user_id = $employee->id;
$bank->save();
return $bank;
}
It take about 4/5m to load, i try in localhost but it say 60s timeout error.i want to load this page within 30s. i can't optimize in_array in in_array($payment->activity->activityBy->role_id, $roles) and
in_array(strtolower($payment->payment_purpose), ['employee_transfer', 'employee_refund', 'vendor_payment', 'vendor_refund', 'loan_payment', 'salary', 'office_deposit'])
Mainly those two if occur loading time error.
can i optimize in_array in $payment and what is the problem in role_id in $roles? and why it take so many time to load my page?
And is there any way to Optimize bankDetails function because it take also 3/4m to load All, Loan and by Project details information?

If you are searching for a key in an array I would recommend you using array_key_exists which checks if the given key or index exists in the array (checks in keys, not in values) and returns true, or false because in_array you have checks if a value exists in an array (checks the values, not the keys) and returns true, or false.
What is the difference between in_array() and array_key_exists()?

You could try moving some more of the filtering to the database and decreasing the need to load the relationships for all the models:
$payments = Payment::wherePaymentBy('cash')
->whereHas('activity.activityBy', function ($query) use ($roles) {
$query->whereIn('role_id', $roles);
})->get();
Then you can remove if(in_array($payment->activity->activityBy->role_id, $roles)). This should also remove a N+1 problem of dynamically loading the relationships for all those models (lazy loading) and their relationships and their relationships. Also removing any overhead of having to hydrate many unneeded models.
Assuming that is a chain of relationships you are working down to get to role_id.
Laravel 5.8 Docs - Eloquent - Relationships - Querying Relationship Existence whereHas

Related

Laravel store and update form

I would like to update a form, I mentioned that the form is already saved in the database(function store). I want to edit the form and update it in the database(function update).
I only want to UPDATE the "tags", this is giving me an error because it is in another table.
I would need your help because I can't do it, I tried different methods but didn't succeed.
public function store(Request $request)
{
// process the listing creation form
$validationArray = [
'title' => 'required',
'company' => 'required',
'logo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:9048',
'location' => 'required',
'service' => 'required',
'apply_link' => 'required|url',
'content' => 'required',
'payment_method_id' => 'required'
];
if (!Auth::check()) {
$validationArray = array_merge($validationArray, [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:5',
'name' => 'required',
'phone' => 'required|numeric|min:10|starts_with:0'
]);
}
$request->validate($validationArray);
// is a user signed in ? if not, create one and authenticate
$user = Auth::user();
if (!$user) {
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone' => $request->phone
]);
$user->createAsStripeCustomer();
Auth::login($user);
}
// process the payment and create the listing
try {
$amount = 9900; // $99.00 USD in cents
if ($request->filled('is_highlighted')) {
$amount += 1000;
}
$user->charge($amount, $request->payment_method_id);
$md = new \ParsedownExtra();
$listing = $user->listings()
->create([
'title' => $request->title,
'slug' => Str::slug($request->title) . '-' . rand(1111, 9999),
'company' => $request->company,
'logo' => basename($request->file('logo')->store('public')),
'location' => $request->location,
'apply_link' => $request->apply_link,
'content' => $md->text($request->input('content')),
'is_highlighted' => $request->filled('is_highlighted'),
'is_active' => true
]);
**foreach (explode(',', $request->tags) as $requestTag) {
$tag = Tag::firstOrCreate([
'slug' => Str::slug(trim($requestTag))
], [
'name' => ucwords(trim($requestTag))
]);
$tag->listings()->attach($listing->id);
}**
foreach (explode(',', $request->service) as $requestService) {
$service = Service::firstOrCreate([
'service_name' => ucwords(trim($requestService))
]);
$service->listings()->attach($listing->id);
}
return redirect()->route('user.dashboard')->with('success', 'Anuntul tau a fost publicat!');
} catch (\Exception $e) {
return redirect()->back()
->withErrors(['error' => $e->getMessage()]);
}
} $tag->listings()->attach($listing->id);
}
public function edit($id)
{
$listing = Listing::findOrFail($id);
if (Auth::check() && Auth::user()->id == $listing->user_id) {
$listing = DB::table('listings')
->where('id', $id)
->first();
return view('listings.edit', compact('listing'));
} else {
return (redirect('/dashboard'));
}
}
public function update(Request $request, $id)
{
//working in progress...
$this->validate($request,[
'title' => 'required',
'company' => 'required',
'logo' => 'file|max:2048|required|mimes:jpeg,jpg,png',
'location' => 'required',
'apply_link' => 'required|url',
'content' => 'required'
// 'payment_method_id' => 'required'
]);
$data = Listing::find($id);
$data->title = $request->title;
$data->company = $request->company;
$data->logo = basename($request->file('logo')->store('public'));
$data->location = $request->location;
$data->apply_link = $request->apply_link;
$data['tags'] = explode(',', $request->tags); // <-this one
$data->content= $request->content;
// $data['is_highlighted'] = $request->is_highlighted;
$data['user_id'] = Auth::user()->id;
$data->save();
// DB::table('listings')->where('id', $id)->update($data);
return redirect()->back()->with('success', 'success');
}

Call to a member function validate() on array

I need your help for a project Im doing at the moment.
I am using Laravel for programming and Im getting this error: 'Call to a member function validate() on array'
This is my store method
public function store()
{
$data = $this->check();
switch ($data) {
case (0):
return redirect()->back()->with('error', 'Dieses Produkt ist nicht vorhanden');
case (1):
return redirect()->back()->with('error', 'Das Produkt mit dieser Liefer-Nummer ist bereits vorhanden');
default:
Product::create($data)->save();
return redirect('/');
}
}
this is the check method
public function check()
{
$i = 0;
foreach(Validation::all() as $valid)
{
$validation[$i] = [
'id' => $valid->id,
'Produkt' => $valid->Produkt,
'PHmax' => $valid->PHmax,
'PHmin' => $valid->PHmin,
'Wassermax' => $valid->Wassermax,
'Wassermin' => $valid->Wassermin,
'Dichtemax' => $valid->Dichtemax,
'Dichtemin' => $valid->Dichtemin,
];
$i = $i + 1;
}
$data = [
'LieferNr' => request()->LieferNr,
'Produkt' => request()->Produkt,
'PH' => request()->PH,
'Wasser' => request()->Wasser,
'Dichte' => request()->Dichte,
'Bearbeiter' => request()->Bearbeiter,
];
$bigdata = Product::all();
foreach(Validation::all() as $valid){
foreach($bigdata as $bigdata){
if($data['LieferNr'] == $bigdata->LieferNr){
return 1;
}
}
if(in_array($data['Produkt'], $validation[0]) || in_array($data['Produkt'], $validation[1] ))
{
$PHmax = $valid->PHmax;
$PHmin = $valid->PHmin;
$Wassermax = $valid->Wassermax;
$Wassermin = $valid->Wassermin;
$Dichtemax = $valid->Dichtemax;
$Dichtemin = $valid->Dichtemin;
return $data->validate([
'LieferNr' => ['required', 'min:5', 'max:5'],
'Produkt' => ['required'],
'PH' => ['required', 'numeric', "min:$PHmin", "max:$PHmax"],
'Wasser' => "required|numeric|min:$Wassermin|max:$Wassermax",
'Dichte' => "required|numeric|min:$Dichtemin|max:$Dichtemax",
'Bearbeiter' => ['required'],
]);
}
else
{
return 0;
}
}
}
The error occurs when i do $data->validate(...)
I am quite new to Laravel and i would be happy if you can help me :)
I see your problem
It is because you are calling validate on array $data
return $data->validate([
'LieferNr' => ['required', 'min:5', 'max:5'],
'Produkt' => ['required'],
'PH' => ['required', 'numeric', "min:$PHmin", "max:$PHmax"],
'Wasser' => "required|numeric|min:$Wassermin|max:$Wassermax",
'Dichte' => "required|numeric|min:$Dichtemin|max:$Dichtemax",
'Bearbeiter' => ['required'],
]);
Instead, do following
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($data, [
'LieferNr' => ['required', 'min:5', 'max:5'],
'Produkt' => ['required'],
'PH' => ['required', 'numeric', "min:$PHmin", "max:$PHmax"],
'Wasser' => "required|numeric|min:$Wassermin|max:$Wassermax",
'Dichte' => "required|numeric|min:$Dichtemin|max:$Dichtemax",
'Bearbeiter' => ['required'],
]);
if($validator->fails()){
return 0;
}

Laravel POST API -> cURL error 28 in a working api

hope you are all doing well,
on my project, I faced an issue with posting data to an internal API, and keep getting cURL error 28 which means "Operation timed out after 30006 milliseconds with 0 bytes received"
BUT when I test the same API with the same values in POSTMAN it works fine, [Screenshot] -> https://tppr.me/hensp
And here is more details from laravel reports
https://flareapp.io/share/47q1Olz7#share
And my code is attached below.
Thanks in advance
public function addToCart($productId, array $options = [], $quantity = 1)
{
$this->product = Product::findOrFail($productId);
if (!Session::has('cart-token'))
Session::put('cart-token', Str::random(100));
$response = Http::post(env('APP_API_URL') . '/cart/store', [
'productId' => $this->product->id,
'quantity' => $quantity,
'options' => $options,
'cartToken' => Session::get('cart-token')
]);
$this->dispatchBrowserEvent('alert', [
'type' => $response['status'] ? 'success' : 'error',
'message' => $response['message']
]);
}
and the env variable is
APP_URL=127.0.0.1:8000
API_VERSION=1
APP_API_URL="${APP_URL}/api/v${API_VERSION}"
API controllers
public function addToCart(Request $request)
{
App::setLocale('en');
$request->validate([
'productId' => 'required|integer|exists:products,id',
'options' => 'array',
'options.*' => 'distinct|integer',
'quantity' => 'required|integer',
'cartToken' => 'nullable|string|max:191'
]);
$this->product = Product::findOrFail($request['productId']);
if ($request['quantity'] < 0)
$this->condition = true;
else
$condition = $this->conditions($request['options'] ?? [], $request['quantity']);
if ($this->conditionStatus) {
try {
$query = CartModel::where('cart_token', $request['cartToken'])
->where('product_id', $this->product->id)
->whereJsonContains('option_ids', $request['options'] ?? [])
->firstOrFail();
$query->update([
'quantity' => $query->quantity + $request['quantity']
]);
} catch (\Exception $e) {
$query = CartModel::create([
'cart_token' => $request['cartToken'],
'product_id' => $this->product->id,
'option_ids' => $request['options'] ?? [],
'quantity' => $request['quantity']
]);
}
return response()->json([
'status' => true,
'code' => 101,
'cart_token' => $query->cart_token,
'message' => trans('frontend/alert.cart.added_to_cart', ['product' => $this->product->detail->handleMultipleLanuage('title')])
]);
}
return response()->json($condition, 422);
}
public function conditions(array $options = [], $quantity)
{
$productOptions = ProductOption::where('product_id', $this->product->id)->get();
if ($productOptions) {
if (count($productOptions) != count($options))
return [
'status' => false,
'code' => 107,
'message' => trans('frontend/alert.cart.select_option')
];
$userCart = CartModel::where('option_ids', $options)->sum('quantity');
$productOptionLists = ProductOptionList::whereIn('id', $options)->get();
foreach ($productOptionLists as $listItem) {
if ($listItem->quantity == 0)
return response()->json([
'status' => false,
'code' => 102,
'message' => trans('frontend/alert.cart.out_of_stock', ['product' => $this->product->detail->handleMultipleLanuage('title')])
]);
if ($listItem->quantity < $userCart + $quantity)
return [
'status' => false,
'code' => 103,
'message' => trans('frontend/alert.cart.maximum_units')
];
}
}
if ($this->product->stock->quantity == 0 && $this->product->stock->quantity < $quantity)
return response()->json([
'status' => false,
'code' => 102,
'message' => trans('frontend/alert.cart.out_of_stock', ['product' => $this->product->detail->handleMultipleLanuage('title')])
]);
if ($this->product->stock->quantity < CartModel::where('product_id', $this->product->id)->sum('quantity') + $quantity)
return [
'success' => false,
'code' => 103,
'message' => trans('frontend/alert.cart.maximum_units')
];
$this->conditionStatus = true;
}

Laravel Mock Guzzle Http Client error during run php unit

I am developing a system using Laravel 7.28.4
In the system I have created a SMSService to be able to send SMS message, below is the SMSService code
https://codeshare.io/aYjDRM
below is the code which the unit test read for the testing
<?php
namespace App\Services;
use App\Models\Booking;
use App\Traits\EmailTrait;
use App\Services\SMSService;
class BookingService extends BaseService
{
use EmailTrait;
public function update($input, $id)
{
$booking = Booking::find($id);
try {
$booking->update($input);
$sms_service = new SMSService;
$booking = Booking::whereId($id)->first();
$booking->update(['status' => config('staticdata.booking_status.success')]);
$this->sendBookingSuccessEmail($booking->applicantDetail->email, $booking->applicantDetail->first_name, $booking->reference_number);
$sms_service->sendBookingSuccessSMS($booking->applicantDetail->mobile_no, $booking->reference_number);
} catch (Exception $e) {
\Log::error($e);
return $this->formatGeneralResponse(
$e->getMessage(),
config('staticdata.status_codes.error'),
config('staticdata.http_codes.internal_server_error')
);
}
return $this->formatGeneralResponse(
config('staticdata.messages.update_success'),
config('staticdata.status_codes.ok'),
config('staticdata.http_codes.success')
);
}
}
external sources : https://codeshare.io/aVLAeR
during running unit test i am using Mockery to replicate the service behaviour
below is the code that i run for the unit test
<?php
namespace Tests\Api;
use App\Models\ApplicantDetails;
use App\Models\Booking;
use App\Models\Branch;
use App\Models\Province;
use App\Models\User;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Tests\TestCase;
use Laravel\Passport\Passport;
class BookingApiTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$user = factory(\App\Models\User::class)->create();
Passport::actingAs(
$user,
['frontend']
);
$response_data = [
'status' => [
'code' => '200',
'description' => 'asd'
]
];
$client = \Mockery::mock('overload:GuzzleHttp\Client');
$client->shouldReceive('post')
->andReturn($client)
->shouldReceive('getStatusCode')
->andReturn(200)
->shouldReceive('getBody')
->andReturn($client)
->shouldReceive('getContents')
->andReturn(json_encode($response_data));
}
public function createARandomDateBetweenRange($start, $end, $filter = null)
{
$period = CarbonPeriod::between($start, $end);
if ($filter) {
$period = $period->filter($filter);
}
return $period;
}
public function testMakeBookingSuccess()
{
$isWeekday = function ($date) {
return $date->isWeekday();
};
$period = $this->createARandomDateBetweenRange(Carbon::now()->format('Y-m-d'), '2021-12-31', $isWeekday);
$period = $period->toArray();
$book_date = $period[0]->format('Y-m-d');
$data = [
'sso_token' => '2345678976543456756543',
'sso_id' => factory(ApplicantDetails::class)->create()->sso_id,
'province' => factory(Province::class)->create()->id,
'branch' => factory(Branch::class)->create()->id,
'book_date' => $book_date,
'meridiem' => 'am'
];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertJsonStructure(
[
'status_code',
'message' => [
'encrypted_order_no',
'result',
'reference_number',
'booking_id'
]
]
);
}
public function testMakeBookingFailedOnWeekend()
{
$isWeekend = function ($date) {
return $date->isWeekend();
};
$period = $this->createARandomDateBetweenRange(Carbon::now()->format('Y-m-d'), '2021-12-31', $isWeekend);
$period = $period->toArray();
$book_date = $period[0]->format('Y-m-d');
$data = [
'sso_token' => '2345678976543456756543',
'sso_id' => factory(ApplicantDetails::class)->create()->sso_id,
'province' => factory(Province::class)->create()->id,
'branch' => factory(Branch::class)->create()->id,
'book_date' => $book_date,
'meridiem' => 'am'
];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'errors' => [
'book_date' => ['date cannot be in weekend']
]
]
);
}
public function testMakeBookingValidationFailed()
{
$data = [];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'detail' => config('staticdata.messages.validation_failed'),
'field' => [
'branch' => 'The branch field is required.',
'meridiem' => 'The meridiem field is required.',
'province' => 'The province field is required.',
'book_date' => 'The book date field is required.',
'sso_id' => 'The sso id field is required.',
]
]
);
}
public function testMakeBookingSlotFullFailed()
{
$isWeekday = function ($date) {
return $date->isWeekday();
};
$period = $this->createARandomDateBetweenRange(Carbon::now()->format('Y-m-d'), '2021-12-31', $isWeekday);
$period = $period->toArray();
$book_date = $period[0]->format('Y-m-d');
$branch_id = factory(Branch::class)->create(
[
'slot_am' => 3,
'slot_pm' => 3,
]
)->id;
// am start
factory(Booking::class, 3)->create(
[
'branch' => $branch_id,
'book_date' => $book_date,
'meridiem' => 'am',
]
);
$data = [
'sso_token' => '2345678976543456756543',
'sso_id' => factory(ApplicantDetails::class)->create()->sso_id,
'province' => factory(Province::class)->create()->id,
'branch' => $branch_id,
'book_date' => $book_date,
'meridiem' => 'am'
];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'errors' => [
'book_date' => ['Unable to book as the selected slot already full'],
]
]
);
// pm start
factory(Booking::class, 3)->create(
[
'branch' => $branch_id,
'book_date' => $book_date,
'meridiem' => 'pm',
]
);
$data = [
'sso_token' => '2345678976543456756543',
'sso_id' => factory(ApplicantDetails::class)->create()->sso_id,
'province' => factory(Province::class)->create()->id,
'branch' => $branch_id,
'book_date' => $book_date,
'meridiem' => 'pm'
];
$response = $this->post(route('api.ph-portal.booking.book'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'errors' => [
'book_date' => ['Unable to book as the selected slot already full'],
]
]
);
}
public function testListBookingPortalSuccess()
{
$branch = factory(Branch::class)->create();
$data['sso_id'] = $branch->sso_id;
$response = $this->post(route('api.ph-portal.booking.list'), $data);
$response->assertJsonStructure(
[
'status_code',
'data'
]
);
}
public function testListBookingPortalNoDataFound()
{
factory(Branch::class)->create();
$data['sso_id'] = "#s3randomStringxde2sx" . rand(1, 100);
$response = $this->post(route('api.ph-portal.booking.list'), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.ok'),
'data' => []
]
);
}
public function testListBookingSuccess()
{
$response = $this->get(route('api.booking.list'));
$response->assertJsonStructure(
[
'status_code',
'data',
]
);
factory(Booking::class)->create()->toArray();
$data = [
'per_page' => "5"
];
$response = $this->get(route('api.booking.list', $data));
$response->assertJsonStructure(
[
'status_code',
'data' => [
'current_page',
'data'
]
]
);
}
public function testViewBookingDetailsSuccess()
{
$booking = factory(Booking::class)->create(['sso_id' => '534534534589p345-5934543058405345']);
$response = $this->get(route('api.booking.details', $booking->id));
$response->assertJsonStructure(
[
'status_code',
'data' => [
'id',
'sso_id',
'user_id',
'province',
'branch',
'book_date',
'created_at',
'updated_at',
'meridiem',
'status',
'reference_number',
'applicant_detail',
'province_data',
'branch_data',
'transaction'
]
]
);
}
public function testViewBookingDetailsNoDataFound()
{
$response = $this->get(route('api.booking.details', 99999999999999999));
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.ok'),
'data' => null
]
);
}
public function testViewBookingDetailsPortalSuccess()
{
$booking = factory(Booking::class)->create();
$response = $this->get(
route(
'api.ph-portal.booking.details',
[
'sso_id' => $booking->sso_id,
'id' => $booking->id
]
)
);
$response->assertJsonStructure(
[
'status_code',
'data' => [
'id',
'sso_id',
'user_id',
'book_date',
'meridiem',
'status',
'reference_number',
'applicant_detail',
]
]
);
}
public function testViewBookingDetailsPortalValidationFailed()
{
$booking = factory(Booking::class)->create();
$response = $this->get(
route(
'api.ph-portal.booking.details',
[
'sso_id' => 999999999999999,
'id' => $booking->id
]
)
);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'detail' => config('staticdata.messages.validation_failed'),
'field' => [
'sso_id' => 'The selected sso id is invalid.'
]
]
);
}
public function testBookingUpdateSuccess()
{
$booking = factory(Booking::class)->create();
$response_data = [
'umid' => 1,
'clientMessageId' => null,
'destination' => '+61212323',
'encoding' => 'GSM7',
'status' => [
'code' => '200',
'description' => 'asd'
]
];
$client = \Mockery::mock('overload:GuzzleHttp\Client');
$client->shouldReceive('post')
->andReturn($client)
->shouldReceive('getStatusCode')
->andReturn(200)
->shouldReceive('getBody')
->andReturn($client)
->shouldReceive('getContents')
->andReturn(json_encode($response_data));
$data = [
'branch' => factory(Branch::class)->create()->id,
'book_date' => '2020-12-01',
'meridiem' => 'am',
];
$response = $this->post(route('api.booking.update', $booking->id), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.ok'),
'message' => config('staticdata.messages.update_success')
]
);
}
public function testBookingUpdateValidationFailed()
{
$response = $this->post(route('api.booking.update', 9999999));
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'detail' => config('staticdata.messages.validation_failed'),
'field' => [
'id' => 'The selected id is invalid.',
'branch' => 'The branch field is required.'
]
]
);
$booking = factory(Booking::class)->create();
$data = [
'branch' => factory(Branch::class)->create()->id,
'book_date' => '2020-12-01',
];
$response = $this->post(route('api.booking.update', $booking->id), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.validation_failed'),
'detail' => config('staticdata.messages.validation_failed'),
'field' => [
'meridiem' => 'The meridiem field is required when book date is present.'
]
]
);
}
public function testRequestNewBookingDateSuccess()
{
$booking = factory(Booking::class)->create();
$response = $this->post(route('api.ph-portal.booking.request_new_bookdate', $booking->id), $data);
$response->assertExactJson(
[
'status_code' => config('staticdata.status_codes.ok'),
'message' => config('staticdata.messages.process_success')
]
);
}
}
external sources : https://codeshare.io/Gk6eDA
the unit test are able to run using this command
php artisan test --filter BookingApiTest
but error below appear during the unit test and i am unable to track on why this happen.
✕ booking update success
Tests: 1 failed, 11 passed, 5 pending
ErrorException
Undefined index: umid
at C:\laragon\www\nbi-backend\app\Services\SMSService.php:13
9| {
10| public function saveSMSData($data)
11| {
12| $data = [
> 13| 'umid' => $data['umid'],
14| 'client_message_id' => $data['clientMessageId'],
15| 'destination' => $data['destination'],
16| 'encoding' => $data['encoding'],
17| 'code' => $data['status']['code'],
1 C:\laragon\www\nbi-backend\app\Services\SMSService.php:13
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined index: umid", "C:\laragon\www\nbi-backend\app\Services\SMSService.php", [])
2 C:\laragon\www\nbi-backend\app\Services\SMSService.php:50
App\Services\SMSService::saveSMSData([])
i have tried using
php artisan tinker
then write the command as below
$sms = new SMSService
$sms->sendBookingSuccessSMS('601123456767','TEST123');
but the result came out as
null
kindly help on how to fix this issue or how to trace of how the problem occur
Thank you.
Some additional code info
config staticdata file
https://codeshare.io/5N8lgm
.env file
https://codeshare.io/aVLAB4
composer.json file
https://codeshare.io/G84Eev

Codeigniter 4 - Form Validation

I'm using the validation form of CodeIgniter 4, I already check if the post is coming, but I'm receiving FALSE every time, just take a look in my code.
function login(){
helper(['form', 'url']);
$validation = \Config\Services::validation();
$validation->setRules([
'email' => ['label' => 'E-mail', 'rules' => 'required'],
'password' => ['label' => 'Senha', 'rules' => 'required|min_length[6]']
]);
var_dump($this->validate($validation) ? true : false);exit;
}
I tried too,
$rules = [
'email' => ['label' => 'E-mail', 'rules' => 'required'],
'password' => ['label' => 'Senha', 'rules' => 'required|min_length[6]']
];
var_dump($this->validate($rules) ? true : false);exit;
look at my codes
<?php
namespace Modules\Common\Controllers;
use Modules\Common\Config\Services;
use Modules\Common\Entities\AdvertisementEntity;
use CodeIgniter\HTTP\ResponseInterface;
use Modules\Shared\Controllers\ApiController;
class Advertisement extends ApiController
{
/**
* index function
* #method : GET
*/
public function index()
{
$advertisementEntity = new AdvertisementEntity();
$this->urlQueryParam->dataMap($advertisementEntity->getDataMap());
$advertisementService = Services::advertisementService();
$findAllData = $advertisementService->index($this->urlQueryParam);
return $this->respond([
'data' => $findAllData['data'],
'pager' => $findAllData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/**
* show function
* #method : GET with params ID
*/
public function show($id = null)
{
$advertisementService = Services::advertisementService();
$findOneData = $advertisementService->show($id);
return $this->respond([
'data' => $findOneData['data'],
'pager' => $findOneData['pager']
], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/**
* create function
* #method : POST
*/
public function create()
{
$rules = [
'name' => 'required|min_length[3]|max_length[255]',
'link' => 'required',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
};
$advertisementEntity = new AdvertisementEntity((array)$this->request->getVar());
$advertisementEntity->enableStatus()->createdAt();
$advertisementService = Services::advertisementService();
$advertisementService->create($advertisementEntity);
return $this->respond([
'insertId' => $advertisementService->getInsertID()
], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));
}
/**
* update function
* #method : PUT or PATCH
*/
public function update($id = null)
{
if ($this->request) {
//get request from Vue Js
$json = $this->request->getJSON();
if (!isset($id)) {
$id = $json->id;
}
$rules = [
'name' => 'required|min_length[3]|max_length[255]',
'link' => 'required',
];
if (!$this->validate($rules)) {
return $this->respond([
'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$advertisementEntity = new AdvertisementEntity((array)$this->request->getVar());
$advertisementEntity->updatedAt();
$advertisementService = Services::advertisementService();
$advertisementService->update($id, $advertisementEntity);
}
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.update'));
}
/**
* edit function
* #method : DELETE with params ID
*/
public function delete($id = null)
{
$advertisementService = Services::advertisementService();
$advertisementService->delete($id);
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.remove'));
}
}

Categories