Skip to content

Commit

Permalink
Create ExtendedCarbon
Browse files Browse the repository at this point in the history
  • Loading branch information
ikhsan3adi committed Jun 29, 2024
1 parent 2a01809 commit 0154141
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 16 deletions.
44 changes: 44 additions & 0 deletions app/ExtendedCarbon.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace App;

use Illuminate\Support\Carbon;

class ExtendedCarbon extends Carbon
{
/**
* Get the year and week formatted as a string in the ISO 8601 week date format.
*
* @return string The formatted year-week string.
* ```
* '2024-W25'
* ```
*/
public function yearWeekString(): string
{
if ($this->week < 10 && !str_contains($this->week, '0')) {
$week = "0$this->week";
}
return "$this->year-W$week";
}

/**
* Get the closest date and time from `$this` in the array of dates.
*
* @param array<Carbon|ExtendedCarbon|string> $dates An array of dates to compare against the target.
* @return ExtendedCarbon|null The closest date and time from the array compared to the target.
*/
public function closestFromDateArray(array $dates)
{
$closest = null;
foreach ($dates as $date) {
$current = ExtendedCarbon::parse($date);
if (is_null($closest)) {
$closest = $current;
continue;
}
$closest = $this->closest($closest, $current) === $current ? $current : $closest;
}
return $closest;
}
}
15 changes: 0 additions & 15 deletions app/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,4 @@ public static function getGoogleMapsUrl($lat, $lng)
{
return "https://maps.google.com/maps?q=$lat,$lng";
}

/**
* Get the year and week formatted as a string in the ISO 8601 week date format.
*
* @param string|int $week The week number to format.
* @param string|int $year The year to format.
* @return string The formatted year-week string.
*/
public static function yearWeekString(string|int $week, string|int $year): string
{
if ($week < 10 && !str_contains($week, '0')) {
$week = "0$week";
}
return "$year-W$week";
}
}
4 changes: 3 additions & 1 deletion app/Models/Attendance.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Models;

use App\ExtendedCarbon;
use App\Helpers;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Casts\Attribute;
Expand Down Expand Up @@ -80,8 +81,9 @@ public function attachmentUrl(): ?Attribute
public static function clearUserAttendanceCache(Authenticatable $user, Carbon $date)
{
if (is_null($user)) return false;
$date = new ExtendedCarbon($date);
$monthYear = "$date->month-$date->year";
$week = Helpers::yearWeekString($date->week, $date->year);
$week = $date->yearWeekString();
$ymd = $date->format('Y-m-d');

try {
Expand Down

0 comments on commit 0154141

Please sign in to comment.