Skip to content

Commit f7ea08e

Browse files
committed
Initial commit
1 parent ffd0fdf commit f7ea08e

4 files changed

Lines changed: 91 additions & 2 deletions

File tree

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
/vendor/
2+
composer.lock
3+
.idea

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1-
# dates-timezone-conversion-trait
2-
Automatically convert an Eloquent model's dates to and from the current user's timezone
1+
# Dates Timezone Conversion Trait
2+
This package provides a trait that automatically converts an Eloquent
3+
model's dates to and from the current user's timezone.

composer.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "divineomega/dates-timezone-conversion-trait",
3+
"description": "Automatically convert an Eloquent model's dates to and from the current user's timezone",
4+
"type": "library",
5+
"require": {
6+
"illuminate/database": "^5.6",
7+
"illuminate/support": "^5.6"
8+
},
9+
"license": "LGPL-3.0-only",
10+
"authors": [
11+
{
12+
"name": "Jordan Hall",
13+
"email": "[email protected]"
14+
}
15+
]
16+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
<?php
2+
3+
namespace App\Traits;
4+
5+
use Carbon\Carbon;
6+
use Illuminate\Database\Eloquent\Model;
7+
use Illuminate\Support\Facades\Auth;
8+
9+
trait DatesTimezoneConversion
10+
{
11+
12+
/**
13+
* Overrides getAttributeValue, and convert any dates
14+
* to the user's timezone.
15+
*
16+
* @param string $key
17+
* @return mixed
18+
*/
19+
public function getAttributeValue($key)
20+
{
21+
/** @var Carbon $value */
22+
$value = parent::getAttributeValue($key);
23+
24+
if ($this->isDateObject($key, $value)) {
25+
26+
/** @var Model $user */
27+
$user = Auth::user();
28+
29+
if ($user) {
30+
$value->setTimezone($user->getAttributeValue('timezone'));
31+
}
32+
33+
}
34+
35+
return $value;
36+
}
37+
38+
/**
39+
* Set a given attribute on the model.
40+
*
41+
* @param string $key
42+
* @param mixed $value
43+
* @return mixed
44+
*/
45+
public function setAttribute($key, $value)
46+
{
47+
if ($this->isDateObject($key, $value)) {
48+
$value->setTimezone(config('app.timezone'));
49+
}
50+
51+
return parent::setAttribute($key, $value);
52+
}
53+
54+
/**
55+
* Checks if a date is part of the model's dates array,
56+
* is an object, and is a Carbon instance.
57+
*
58+
* @param $key
59+
* @param $value
60+
* @return bool
61+
*/
62+
private function isDateObject($key, $value)
63+
{
64+
return in_array($key, $this->getDates()) &&
65+
is_object($value) &&
66+
get_class($value) === Carbon::class;
67+
}
68+
69+
}

0 commit comments

Comments
 (0)