Last active
January 22, 2020 17:33
-
-
Save jaouadballat/d0ecfb3907480ff088863a98a48952d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? php | |
public function validate($startDate, $endDate) { | |
$rules = [ | |
'startDate' => 'date_format:Y-m-d', | |
'endDate' => 'date_format:Y-m-d', | |
]; | |
$validator = Validator::make(['startDate' => $startDate, 'endDate' => $endDate], $rules); | |
if ($validator->fails()) { | |
return response()->json($validator->getErrors(), 422); | |
} | |
} | |
public function getAuthenticatedUser() { | |
return auth()->user(); | |
} | |
public function formatDate($date) { | |
$dateFormat = new Carbon($date); | |
return $dateFormat->format('Y-m-d'); | |
} | |
public function getDaysRange($min, $max) { | |
$userId = $this->getAuthenticatedUser()->id; | |
return Day::where('date', '>=', $min) | |
->where('date', '<=', $max) | |
->where('user_id', $userId) | |
->orderBy('date', 'ASC') | |
->get(); | |
} | |
public function findMealById($dayId) { | |
$userId = $this->getAuthenticatedUser()->id; | |
Meal::where('day_id', $dayId)->where('user_id', $userId)->get(); | |
} | |
public function getDayRange2( | |
$startDate, | |
$endDate | |
) { | |
$this->validate($startDate, $endDate); | |
$min = $this->date_format($startDate); | |
$max = $this->date_format($endDate); | |
$days = $this->getDaysRangeByUser($min, $max); | |
foreach ($days as &$day) { | |
$day->meals = $this->findMealById($day->id); | |
} | |
$max = $endDate->toImmutable(); | |
$min = $startDate->toImmutable(); | |
$transformedDays = []; | |
while ($min <= $max) { | |
foreach ($days as $day) { | |
if ($day->date === $this->date_format($min)) { | |
$transformedDays[] = $day->toArray(); | |
$min = $min->add('day', 1); | |
continue; | |
} | |
} | |
$transformedDays[] = [ | |
'date' => $this->date_format($min), | |
'calorie_limit' => 1500, | |
'total_calories' => 0, | |
'meals' => [] | |
]; | |
$min = $min->add('day', 1); | |
} | |
return response()->json($transformedDays); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For validation I Will use a custom validation request instead of doing it on the same file as the function getDayRange2, so for that I Will create a new request using Laravel
So as you can see I can override the public function response(array $errors) method and return a modified response without Validator explicitly.
And also instead of returning transformedDays I will use Laravel collection Resources, so for that, I will create a new class Day: