Created
June 30, 2022 13:23
-
-
Save domthomas-dev/b4a25dd5840bfd736a81c90a8f0a768c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Livewire\Traits; | |
use Illuminate\Support\Str; | |
trait ConvertEmptyStringsToNull | |
{ | |
public function updatedConvertEmptyStringsToNull(string $name, mixed $value): void | |
{ | |
if (! $this->shouldConvertValue($value, $name)) { | |
return; | |
} | |
$value = trim($value); | |
$value = $value === '' ? null : $value; | |
if (Str::of($name)->contains('.')) { | |
$nestedTargetName = Str::of($name)->beforeLast('.'); | |
$nestedPropertyName = Str::of($name)->afterLast('.'); | |
$nested = data_get($this, $nestedTargetName); | |
data_set($nested, $nestedPropertyName, $value); | |
data_set($this, $nestedTargetName, $nested); | |
return; | |
} | |
data_set($this, $name, $value); | |
} | |
protected function shouldConvertValue(mixed $value, string $name): bool | |
{ | |
return | |
is_string($value) | |
&& ( | |
! property_exists($this, 'convertEmptyStringsExcept') | |
|| ! in_array($name, $this->convertEmptyStringsExcept) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment