Files
lara-bermite/app/Models/Rainfall.php
2023-12-25 14:25:05 +01:00

87 lines
2.5 KiB
PHP

<?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Rainfall extends Model
{
use HasFactory;
const MONTHS = [
1 => 'Janvier',
2 => 'Février',
3 => 'Mars',
4 => 'Avril',
5 => 'Mai',
6 => 'Juin',
7 => 'Juillet',
8 => 'Août',
9 => 'Septembre',
10 => 'Octobre',
11 => 'Novembre',
12 => 'Décembre',
];
protected $guarded = [];
protected $casts = [
'date' => 'date',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public static function getDateKey(string $date, string $period)
{
$date = new Carbon($date);
if ($period === 'year') {
return $date->year;
} elseif ($period === 'month') {
return $date->year * 100 + $date->month;
} elseif ($period === 'week') {
return $date->year * 100 + $date->week;
}
return $date->format('Y-m-d');
}
public static function getDateKeyData(string $date, array $data): array
{
$date = new Carbon($date);
$start = new Carbon($data['start']);
$endDate = new Carbon($data['end']);
$startDate = $date->format('Y-m-d 00:00:00');
if ($data['period'] === 'year') {
$days = $start->year === $endDate->year ? $start->diffInDays($endDate)
: (($date->year === $endDate->year || $start->year === $date->year)
? $date->diffInDays($date->year === $endDate->year ? $endDate : $start->endOfYear()) + 1
: $date->endOfYear()->day);
$label = $date->year;
} elseif ($data['period'] === 'month') {
$days = ($date->month === $endDate->month || $date->month === $start->month)
? $date->diffInDays($date->month === $endDate->month ? $endDate : $start->endOfMonth()) + 1
: $date->endOfMonth()->day;
$label = Rainfall::MONTHS[$date->month].' '.$date->year;
} elseif ($data['period'] === 'week') {
$days = $date->week === $endDate->week ? $date->diffInDays($endDate) + 1 : 7;
$label = 'semaine '.$date->week;
} else {
$days = 1;
$label = $date->format('d/m/Y');
}
return [
'start' => $startDate,
'days' => $days,
'label' => $label,
];
}
}