Skip to content

Instantly share code, notes, and snippets.

@jaouadballat
Last active January 22, 2020 17:33
Show Gist options
  • Save jaouadballat/d0ecfb3907480ff088863a98a48952d5 to your computer and use it in GitHub Desktop.
Save jaouadballat/d0ecfb3907480ff088863a98a48952d5 to your computer and use it in GitHub Desktop.
<? 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);
}
@jaouadballat
Copy link
Author

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

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;

class CustomRequest extends FormRequest
{

    public function rules()
    {
        $rules = [
            'startDate' => 'date_format:Y-m-d',
            'endDate' => 'date_format:Y-m-d',
        ];

        return $rules;
    }

    public function response(array $errors)
    {
        return new JsonResponse(['error' => $errors], 422);
    }
}

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:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Day extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'calorie_limit' => $this->calorie_limit,
            'email' => $this->email,
            'total_calories' => $this->total_calories,
            'meals' => [] // here I will use an relationship between Meal and Day -> PostResource::collection($this->meals)
        ];
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment