Skip to content

Instantly share code, notes, and snippets.

@Koc
Created September 21, 2011 19:34
Show Gist options
  • Save Koc/1233063 to your computer and use it in GitHub Desktop.
Save Koc/1233063 to your computer and use it in GitHub Desktop.
<?php
namespace Ololo\Bundle\UsersBundle\Service;
use Doctrine\ORM\EntityManager;
use Ololo\Bundle\UsersBundle\Entity\User;
use Ololo\Bundle\UsersBundle\Entity\Friendship;
use Ololo\Bundle\UsersBundle\Event\FriendshipSuccessEvent;
class FriendshipService
{
protected $em;
protected $dispatcher;
public function __construct(EntityManager $em, $eventDispatcher)
{
$this->em = $em;
$this->dispatcher = $eventDispatcher;
}
public function makeFriendship($user, $friend)
{
$user = $this->em->find('OloloUsersBundle:User', $user instanceof User ? $user->getId() : $user);
if (!$user) {
return array('status' => 'error', 'error' => 'OloloUsersBundle.friendship_service.base_user_not_exist');
}
$friend = $this->em->find('OloloUsersBundle:User', $friend instanceof User ? $friend->getId() : $friend);
if (!$friend) {
return array('status' => 'error', 'error' => 'OloloUsersBundle.friendship_service.friend_user_not_exist');
}
if ($friend->getId() == $user->getId()) {
return array('status' => 'error', 'error' => 'OloloUsersBundle.friendship_service.friend_is_user');
}
$directFriendship = $this->em
->createQuery('
SELECT f
FROM OloloUsersBundle:Friendship f
WHERE f.user = :user AND f.friend = :friend
')
->setParameters(compact('user', 'friend'))
->getOneOrNullResult();
$inversedFriendship = $this->em
->createQuery('
SELECT f
FROM OloloUsersBundle:Friendship f
WHERE f.user = :friend AND f.friend = :user
')
->setParameters(compact('user', 'friend'))
->getOneOrNullResult();
if ($directFriendship) {
return array('status' => 'error', 'error' => 'OloloUsersBundle.friendship_service.already_friendly');
}
$friendship = new Friendship();
$friendship->setFriend($friend);
$friendship->setUser($user);
if ($inversedFriendship) { // I'm already in his friends. Confirm friendship
$friendship->setMutual(true);
$inversedFriendship->setMutual(true);
//TODO: call after flushing
$event = new FriendshipSuccessEvent();
$event->setBaseUser($user);
$event->setFriend($friend);
$this->eventDispatcher->dispatch($event);
}
$this->em->persist($friendship);
$this->em->flush();
return array('status' => 'success');
}
public function removeFriendship($user, $friend)
{
throw new \BadMethodCallException('Not implimented yet');
}
}
<?php
// example of controller
if (!$this->getAuth()->isAuthenticated()) {
throw $this->createAccessDinedException($this->trans('OloloUsersBundle.not_authenticated'));
}
$service = new FriendshipService($this->getEntityManager('write'), $this->getEventDispatcher());
$response = $service->makeFriendship($this->getAuth()->getId(), $this->getQueryParam('friend'));
return $this->render($template, $response);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment