phpvms/app/Repositories/SettingRepository.php

123 lines
2.8 KiB
PHP
Raw Normal View History

<?php
namespace App\Repositories;
2018-02-21 12:33:09 +08:00
use App\Exceptions\SettingNotFound;
use App\Interfaces\Repository;
2018-02-21 12:33:09 +08:00
use App\Models\Setting;
use Illuminate\Support\Carbon;
2018-02-21 12:33:09 +08:00
use Log;
use Prettus\Repository\Contracts\CacheableInterface;
use Prettus\Repository\Traits\CacheableRepository;
use Prettus\Validator\Exceptions\ValidatorException;
/**
* Class SettingRepository
*/
class SettingRepository extends Repository implements CacheableInterface
{
use CacheableRepository;
2017-12-26 08:10:24 +08:00
public $cacheMinutes = 1;
/**
* @return string
*/
public function model()
{
return Setting::class;
}
/**
* Get a setting, reading it from the cache possibly
2018-08-27 00:40:04 +08:00
*
* @param string $key
2018-08-27 00:40:04 +08:00
*
* @throws SettingNotFound
2018-08-27 00:40:04 +08:00
*
* @return mixed
*/
public function retrieve($key)
{
2018-01-01 01:19:18 +08:00
$key = Setting::formatKey($key);
$setting = $this->findWhere(['id' => $key], ['type', 'value'])->first();
if (!$setting) {
throw new SettingNotFound($key.' not found');
}
2018-08-27 00:40:04 +08:00
// cast some types
switch ($setting->type) {
case 'bool':
case 'boolean':
2018-01-20 05:02:49 +08:00
$value = $setting->value;
if ($value === 'true' || $value === '1') {
2018-01-20 05:02:49 +08:00
$value = true;
} elseif ($value === 'false' || $value === '0') {
2018-01-20 05:02:49 +08:00
$value = false;
}
return (bool) $value;
break;
case 'date':
return Carbon::parse($setting->value);
break;
case 'int':
case 'integer':
case 'number':
return (int) $setting->value;
break;
case 'float':
return (float) $setting->value;
break;
default:
return $setting->value;
}
}
/**
* @alias store($key,$value)
2018-08-27 00:40:04 +08:00
*
* @param mixed $key
* @param mixed $value
*/
public function save($key, $value)
{
return $this->store($key, $value);
}
/**
* Update an existing setting with a new value. Doesn't create
* a new setting
2018-08-27 00:40:04 +08:00
*
* @param $key
* @param $value
2018-08-27 00:40:04 +08:00
*
* @return null
*/
public function store($key, $value)
{
2018-01-01 01:19:18 +08:00
$key = Setting::formatKey($key);
$setting = $this->findWhere(
['id' => $key],
2018-08-27 00:40:04 +08:00
['id', 'value'] // only get these columns
)->first();
if (!$setting) {
2018-08-27 00:40:04 +08:00
return;
}
try {
if (\is_bool($value)) {
$value = $value === true ? 1 : 0;
}
$this->update(['value' => $value], $setting->id);
} catch (ValidatorException $e) {
Log::error($e->getMessage(), $e->getTrace());
}
return $value;
}
}