Files
nexusphp/app/Models/Setting.php

90 lines
2.2 KiB
PHP
Raw Normal View History

2021-04-17 19:01:33 +08:00
<?php
namespace App\Models;
use Illuminate\Support\Arr;
use Nexus\Database\NexusDB;
2021-04-17 19:01:33 +08:00
class Setting extends NexusModel
{
protected $fillable = ['name', 'value'];
2022-05-06 22:25:00 +08:00
/**
* get setting autoload = yes with cache
*
* @param null $name
* @param null $default
* @return array|\ArrayAccess|false|int|mixed|string|null
*/
2022-04-04 17:26:26 +08:00
public static function get($name = null, $default = null)
2021-04-17 19:01:33 +08:00
{
$settings = NexusDB::remember("nexus_settings_in_laravel", 600, function () {
2022-04-04 17:26:26 +08:00
return self::getFromDb();
});
2021-04-17 19:01:33 +08:00
if (is_null($name)) {
return $settings;
}
2022-04-04 17:26:26 +08:00
return Arr::get($settings, $name, $default);
}
2022-05-06 22:25:00 +08:00
/**
* get setting autoload = yes without cache
*
* @param null $name
* @param null $default
* @return mixed
*/
public static function getFromDb($name = null, $default = null): mixed
2022-04-04 17:26:26 +08:00
{
2022-05-06 22:25:00 +08:00
$rows = self::query()->where('autoload', 'yes')->get(['name', 'value']);
2022-04-04 17:26:26 +08:00
$result = [];
foreach ($rows as $row) {
2022-05-06 22:25:00 +08:00
$value = self::normalizeValue($row);
2022-04-04 17:26:26 +08:00
Arr::set($result, $row->name, $value);
}
if (is_null($name)) {
return $result;
}
return Arr::get($result, $name, $default);
2021-04-17 19:01:33 +08:00
}
2021-05-15 01:24:44 +08:00
2022-05-06 22:25:00 +08:00
/**
* get from db by name, generally used for `autoload` = 'no'
*
* @param $name
* @param null $default
* @return mixed
*/
public static function getByName($name, $default = null): mixed
{
$result = self::query()->where('name', $name)->first();
if ($result) {
return self::normalizeValue($result);
}
return $default;
}
public static function getByWhereRaw($whereRaw): array
{
$result = [];
$list = self::query()->whereRaw($whereRaw)->get();
foreach ($list as $value) {
Arr::set($result, $value->name, self::normalizeValue($value));
}
return $result;
}
public static function normalizeValue(Setting $setting)
{
$value = $setting->value;
if (!is_null($value)) {
$arr = json_decode($value, true);
if (is_array($arr)) {
$value = $arr;
}
}
return $value;
}
2021-04-17 19:01:33 +08:00
}