Skip to content

Commit 058122d

Browse files
committed
Source of the Trait
1 parent 19dceac commit 058122d

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

composer.json

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"name": "torzer/laravel-datetime-mutator",
3+
"description": "Laravel traits mutators to help Date Time manipulation on Eloquent Models",
4+
"type": "package",
5+
"license": "MIT",
6+
"authors": [
7+
{
8+
"name": "torzer",
9+
"email": "torzer@torzer.com"
10+
},
11+
{
12+
"name": "Ademir Mazer Junior",
13+
"email": "mazer@torzer.com"
14+
},
15+
{
16+
"name": "Oseas Tormen",
17+
"email": "tormen@torzer.com"
18+
}
19+
],
20+
"autoload": {
21+
"psr-4": {
22+
"Torzer\\Common\\": "src/"
23+
}
24+
}
25+
}

src/Traits/MapDateTimeMutator.php

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
3+
namespace Torzer\Common\Traits;
4+
5+
/**
6+
* Inject a function to automagically set mutators for date format, specially in
7+
* d/m/Y format.
8+
*/
9+
trait MapDateTimeMutator
10+
{
11+
12+
13+
/**
14+
* Convert a DateTime to a storable string, creating from the customized
15+
* dateFormatMutator.
16+
*
17+
* @param \DateTime|int $value
18+
* @param array $formats Array with from and to keys to map the formats
19+
* @return string
20+
*/
21+
public function fromDateTimeFormatMutator($value, $formats)
22+
{
23+
$originalDateFormat = $this->getDateFormat();
24+
25+
$this->setDateFormat($formats['from']);
26+
27+
$value = $this->asDateTime($value);
28+
29+
$this->setDateFormat($originalDateFormat);
30+
31+
return $value->format($formats['to']);
32+
}
33+
34+
/**
35+
* Overrides setAttribute from Eloquent to set format date based on-
36+
* dateFormatMutator array
37+
*
38+
* @param string $key
39+
* @param mixed $value
40+
*/
41+
public function setAttribute($key, $value)
42+
{
43+
$mapDateTimeMutator = isset($this->mapDateTimeMutator) ? $this->mapDateTimeMutator : [];
44+
45+
if (array_key_exists($key, $mapDateTimeMutator)) {
46+
if ($value && (in_array($key, $this->getDates()) || $this->isDateCastable($key))) {
47+
$value = $this->fromDateTimeFormatMutator($value, $mapDateTimeMutator[$key]);
48+
}
49+
50+
$this->attributes[$key] = $value;
51+
52+
return $this;
53+
}
54+
55+
return parent::setAttribute($key, $value);
56+
}
57+
58+
}

0 commit comments

Comments
 (0)