Skip to content

Commit

Permalink
Merge pull request #241 from naxvog/main
Browse files Browse the repository at this point in the history
Use Illuminate\Database\Eloquent\Casts\Json if possible
  • Loading branch information
rubenvanassche authored Dec 1, 2023
2 parents adf98fd + e81292f commit ee792da
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions src/SettingsRepositories/DatabaseSettingsRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Spatie\LaravelSettings\SettingsRepositories;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Json;
use Spatie\LaravelSettings\Models\SettingsProperty;

class DatabaseSettingsRepository implements SettingsRepository
Expand All @@ -27,7 +28,7 @@ public function getPropertiesInGroup(string $group): array
->where('group', $group)
->get(['name', 'payload'])
->mapWithKeys(function (object $object) {
return [$object->name => json_decode($object->payload, true)];
return [$object->name => $this->decode($object->payload, true)];
})
->toArray();
}
Expand All @@ -48,15 +49,15 @@ public function getPropertyPayload(string $group, string $name)
->first('payload')
->toArray();

return json_decode($setting['payload']);
return $this->decode($setting['payload']);
}

public function createProperty(string $group, string $name, $payload): void
{
$this->getBuilder()->create([
'group' => $group,
'name' => $name,
'payload' => json_encode($payload),
'payload' => $this->encode($payload),
'locked' => false,
]);
}
Expand All @@ -67,7 +68,7 @@ public function updatePropertiesPayload(string $group, array $properties): void
return [
'group' => $group,
'name' => $name,
'payload' => json_encode($payload),
'payload' => $this->encode($payload),
];
})->values()->toArray();

Expand Down Expand Up @@ -123,4 +124,18 @@ public function getBuilder(): Builder

return $model->newQuery();
}

private function encode(mixed $value): mixed
{
return class_exists(Json::class)
? Json::encode($value)
: json_encode($value);
}

private function decode(string $payload, bool $associative = false): mixed
{
return class_exists(Json::class)
? Json::decode($payload, ! $associative)
: json_decode($payload, $associative);
}
}

0 comments on commit ee792da

Please sign in to comment.