Skip to content

Instantly share code, notes, and snippets.

@JoshuaEstes JoshuaEstes/User.php
Last active Oct 9, 2015

Embed
What would you like to do?
<?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
You can’t perform that action at this time.