Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix nested dates format #2271

Open
wants to merge 1 commit into
base: 4.1
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,9 @@ public function attributesToArray()
// Convert dot-notation dates.
foreach ($this->getDates() as $key) {
Copy link

@shaedrich shaedrich Jul 14, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your change works for EmbedsOne but not for EmbedsMany since Arr::has()/Arr::set() doesn't support dot-syntax on nested arrays (entry.*.date). Interestingly, array_get()/array_set() do. So I'd add this to make it work for both EmbedsOne and EmbedsMany:

Suggested change
foreach ($this->getDates() as $key) {
foreach ($this->getDates() as $key) {
$res = data_get($attributes, $key);
if (is_array($res)) {
$res = array_filter($res);
}
if (Str::contains($key, '.') && Arr::has($attributes, $key)) {
Arr::set($attributes, $key, $this->serializeDate(
$this->asDateTime(Arr::get($attributes, $key))
));
} else if (Str::contains($key, '.') && !empty($res)) {
data_set($attributes, $key, $this->serializeDate(
$this->asDateTime(Arr::get($attributes, $key))
));
}
}

if (Str::contains($key, '.') && Arr::has($attributes, $key)) {
Arr::set($attributes, $key, (string) $this->asDateTime(Arr::get($attributes, $key)));
Arr::set($attributes, $key, $this->serializeDate(
$this->asDateTime(Arr::get($attributes, $key))
));
}
}

Expand Down
2 changes: 1 addition & 1 deletion tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ public function testDates(): void

$data = $user->toArray();
$this->assertNotInstanceOf(UTCDateTime::class, $data['entry']['date']);
$this->assertEquals((string) $user->getAttribute('entry.date')->format('Y-m-d H:i:s'), $data['entry']['date']);
$this->assertEquals($user->getAttribute('entry.date')->format('l jS \of F Y h:i:s A'), $data['entry']['date']);
}

public function testCarbonDateMockingWorks()
Expand Down