Skip to content

Commit 67f5ced

Browse files
Add BooleanDateAttribute class
1 parent 76c7aac commit 67f5ced

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/BooleanDateAttribute.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace SebastiaanLuca\BooleanDates;
6+
7+
use Carbon\CarbonImmutable;
8+
use Illuminate\Database\Eloquent\Casts\Attribute;
9+
10+
class BooleanDateAttribute extends Attribute
11+
{
12+
public static function for(string $column): static
13+
{
14+
return parent::make(
15+
get: static fn (?string $value, array $attributes): bool => $attributes[$column] !== null,
16+
set: static fn (bool $value, array $attributes): array => static::setBooleanDate($value, $attributes, $column),
17+
);
18+
}
19+
20+
private static function setBooleanDate(bool $value, array $attributes, string $column): array
21+
{
22+
// Only update the field if it's never been set before or when it's being "disabled"
23+
24+
if ($value === false || ! array_key_exists($column, $attributes) || $attributes[$column] === null) {
25+
return [$column => $value === false ? null : CarbonImmutable::now()];
26+
}
27+
28+
return [];
29+
}
30+
}

0 commit comments

Comments
 (0)