/** * Creates or updates a preference for a given user. * * @param User $user The user to set the preference for * @param string $key The key to set * @param string $value The value to set * @throws EntityNotPersistantException Thrown if the entity is not persistant */ public static function setPreference(User $user, $key, $value) { if (!PartKeepr::getEM()->contains($user)) { throw new EntityNotPersistantException(); } $dql = "SELECT up FROM PartKeepr\\UserPreference\\UserPreference up WHERE up.user = :user AND "; $dql .= "up.preferenceKey = :key"; $query = PartKeepr::getEM()->createQuery($dql); $query->setParameter("user", $user); $query->setParameter("key", $key); try { $userPreference = $query->getSingleResult(); } catch (\Exception $e) { $userPreference = new UserPreference(); $userPreference->setUser($user); $userPreference->setKey($key); PartKeepr::getEM()->persist($userPreference); } $userPreference->setValue($value); PartKeepr::getEM()->flush(); return $userPreference; }