2015-08-30 22:31:16 +08:00
|
|
|
<?php namespace Oxbow\Services;
|
|
|
|
|
|
|
|
use Oxbow\Setting;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Class SettingService
|
|
|
|
*
|
|
|
|
* The settings are a simple key-value database store.
|
|
|
|
*
|
|
|
|
* @package Oxbow\Services
|
|
|
|
*/
|
|
|
|
class SettingService
|
|
|
|
{
|
|
|
|
|
|
|
|
protected $setting;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* SettingService constructor.
|
|
|
|
* @param $setting
|
|
|
|
*/
|
|
|
|
public function __construct(Setting $setting)
|
|
|
|
{
|
|
|
|
$this->setting = $setting;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets a setting from the database,
|
|
|
|
* If not found, Returns default, Which is false by default.
|
|
|
|
* @param $key
|
|
|
|
* @param string|bool $default
|
|
|
|
* @return bool|string
|
|
|
|
*/
|
|
|
|
public function get($key, $default = false)
|
|
|
|
{
|
|
|
|
$setting = $this->getSettingObjectByKey($key);
|
2015-09-06 00:42:05 +08:00
|
|
|
$value = $setting === null ? null : $setting->value;
|
|
|
|
|
|
|
|
// Change string booleans to actual booleans
|
|
|
|
if($value === 'true') $value = true;
|
|
|
|
if($value === 'false') $value = false;
|
|
|
|
|
|
|
|
// Set to default if empty
|
|
|
|
if($value === '') $value = $default;
|
|
|
|
|
|
|
|
return $value === null ? $default : $value;
|
2015-08-30 22:31:16 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if a setting exists.
|
|
|
|
* @param $key
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
public function has($key)
|
|
|
|
{
|
|
|
|
$setting = $this->getSettingObjectByKey($key);
|
|
|
|
return $setting !== null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add a setting to the database.
|
|
|
|
* @param $key
|
|
|
|
* @param $value
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
public function put($key, $value)
|
|
|
|
{
|
|
|
|
$setting = $this->setting->firstOrNew([
|
|
|
|
'setting_key' => $key
|
|
|
|
]);
|
|
|
|
$setting->value = $value;
|
|
|
|
$setting->save();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Removes a setting from the database.
|
|
|
|
* @param $key
|
|
|
|
* @return bool
|
|
|
|
*/
|
|
|
|
public function remove($key)
|
|
|
|
{
|
|
|
|
$setting = $this->getSettingObjectByKey($key);
|
2015-09-01 03:11:44 +08:00
|
|
|
if ($setting) {
|
2015-08-30 22:31:16 +08:00
|
|
|
$setting->delete();
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets a setting model from the database for the given key.
|
|
|
|
* @param $key
|
|
|
|
* @return mixed
|
|
|
|
*/
|
2015-09-01 03:11:44 +08:00
|
|
|
private function getSettingObjectByKey($key)
|
|
|
|
{
|
2015-08-30 22:31:16 +08:00
|
|
|
return $this->setting->where('setting_key', '=', $key)->first();
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|