Skip to content

Instantly share code, notes, and snippets.

@JoshuaEstes
Last active October 9, 2015 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaEstes/8a0e07172a4361e0a234 to your computer and use it in GitHub Desktop.
Save JoshuaEstes/8a0e07172a4361e0a234 to your computer and use it in GitHub Desktop.
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
/**
* This assumes you already have a User entity, this just shows the parts
* required
*/
class User
{
/**
* @var ArrayCollection
* @ORM\OneToMany(targetEntity="UserSetting", mappedBy="user", fetch="EAGER", cascade={"all"})
*/
protected $settings;
/**
* @return ArrayCollection
*/
public function getSettings()
{
return $this->settings;
}
/**
* Returns a UserSetting
*
* @param string $key
* @return UserSetting
*/
public function getSetting($key)
{
$criteria = Criteria::create()->where(Criteria::exper()-eq('key', $key));
$setting = $this->settings->matching($criteria)->first();
if (false === $setting) {
$setting = new UserSetting();
$setting->setUser($this);
$setting->setKey($key);
}
return $setting;
}
/**
* @param string $key
* @return boolean
*/
public function hasSetting($key)
{
$criteria = Criteria::create()->where(Criteria::expr()->eq('key', $key));
if ($this->settings->matching($criteria)->first()) {
return true;
}
return false;
}
/**
* This will either add the setting, or if a setting
* with the same key is found, it will update that setting
*
* @param UserSetting $setting
*/
public function addSetting(UserSetting $setting)
{
if (false === $this->hasSetting($setting->getKey())) {
$setting->setUser($this);
$this->settings->add($setting);
return;
}
$this->getSetting($setting->getKey())->setValue($setting->getValue());
}
public function removeSetting(UserSetting $setting)
{
if ($this->settings->contains($setting)) {
$this->setting->removeElement($setting);
}
}
/**
* @param array $settings
*/
public function setSettings($settings)
{
$this->settings = new ArrayCollection();
foreach ($settings as $setting) {
$this->addSetting($setting);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment