Skip to content

Instantly share code, notes, and snippets.

@logaretm
Created April 30, 2016 05:43
Show Gist options
  • Save logaretm/2bb1ace44f7281dd4fc406b588883a56 to your computer and use it in GitHub Desktop.
Save logaretm/2bb1ace44f7281dd4fc406b588883a56 to your computer and use it in GitHub Desktop.
Class to manage user settiings in laravel.
<?php
namespace App;
class Settings
{
/**
* @var array
*/
protected $allowed = [
// Allowed Keys.
];
/**
* @var User
*/
protected $user;
/**
* @var mixed
*/
protected $settings = [];
/**
* Settings constructor.
* @param User $user
*/
public function __construct(User $user)
{
$this->user = $user;
$this->settings = $user->settings;
}
/**
* @param $attributes
* @return bool|int
*/
public function merge($attributes)
{
$this->settings = array_merge(
$this->settings,
array_only($attributes, $this->allowed)
);
return $this->save();
}
/**
* Gets the settings value.
*
* @param $key
* @return mixed
*/
public function get($key)
{
return array_get($this->settings, $key);
}
/**
* Sets a settings.
* @param $key
* @param $value
*/
public function set($key, $value)
{
if (! in_array($key, $this->allowed)) {
$this->allowed[] = $key;
}
$this->settings[$key] = $value;
$this->save();
}
/**
* @return mixed
*/
public function all()
{
return $this->settings;
}
/**
* @return bool|int
*/
public function save()
{
return $this->user->update(['settings' => $this->settings]);
}
/**
* Checks if settings has a key.
*
* @param $key
* @return bool
*/
public function has($key)
{
return array_key_exists($key, $this->settings);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment