Skip to content

Instantly share code, notes, and snippets.

@logaretm
Created April 30, 2016 05:43
Show Gist options
  • Select an option

  • Save logaretm/2bb1ace44f7281dd4fc406b588883a56 to your computer and use it in GitHub Desktop.

Select an option

Save logaretm/2bb1ace44f7281dd4fc406b588883a56 to your computer and use it in GitHub Desktop.

Revisions

  1. Abdelrahman Awad created this gist Apr 30, 2016.
    102 changes: 102 additions & 0 deletions Settings.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,102 @@
    <?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);
    }
    }