Skip to content
Snippets Groups Projects
Select Git revision
  • 8701a5f6feceb356055347c20f725ed0cab44a1c
  • master default protected
2 results

DbConfig.php

Blame
  • DbConfig.php 2.62 KiB
    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Support\Facades\Cache;
    
    class DbConfig extends Model
    {
        use HasFactory;
    
        public $timestamps = false;
    
        protected $fillable = [
            'key',
            'value',
        ];
    
        /**
         * Get a configuration value by its key.
         * Value types casts:
         * - 'true' => true
         * - 'false' => false
         * - integers => int
         * - floats => float
         * - strings => string
         *
         * @param  string  $key  The key of the configuration value. Example: 'app.name'
         * @param  float|bool|int|string|null  $default  The default value to return if the configuration does not exist.
         * @return float|bool|int|string|null The value of the configuration.
         */
        public static function get(string $key, float|bool|int|string|null $default = null): float|bool|int|string|null
        {
            $config = Cache::rememberForever('config_'.$key, function () use ($key) {
                return self::where('key', $key)->first();
            });
    
            if (empty($config) || ! $config->exists || $config->value === null) {
                return $default;
            }
    
            // Cast to boolean if the value is a boolean
            if ($config->value === 'true') {
                return true;
            } elseif ($config->value === 'false') {
                return false;
            }
    
            // Cast to integer if the value is an integer
            if (is_numeric($config->value)) {
                if (is_float($config->value)) {
                    return (float) $config->value;
                } else {
                    return (int) $config->value;
                }
            }
    
            return $config->value;
        }
    
        /**
         * Set a configuration value by its key.
         *
         * @param  string  $key  The key of the configuration value. Example: 'app.name'
         * @param  string|int|float|bool  $value  The value of the configuration.
         */
        public static function set(string $key, float|bool|int|string|null $value): void
        {
            if (Cache::has('config_'.$key)) {