Created
September 10, 2013 06:44
-
-
Save qdelettre/6505770 to your computer and use it in GitHub Desktop.
FacebookProvider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FacebookProvider implements UserProviderInterface | |
{ | |
/** | |
* @var \Facebook | |
*/ | |
protected $facebook; | |
protected $userManager; | |
protected $validator; | |
public function __construct(BaseFacebook $facebook, $userManager, $validator) | |
{ | |
$this->facebook = $facebook; | |
$this->userManager = $userManager; | |
$this->validator = $validator; | |
} | |
public function supportsClass($class) | |
{ | |
return $this->userManager->supportsClass($class); | |
} | |
/** | |
* Find user by email | |
* | |
* @param string $email | |
* | |
* @return mixed | |
*/ | |
public function findUserByEmail($email) | |
{ | |
return $this->userManager->findUserBy(array('email' => $email)); | |
} | |
public function findUserByFbId($fbId) | |
{ | |
return $this->userManager->findUserBy(array('facebookId' => $fbId)); | |
} | |
public function loadUserByUsername($username) | |
{ | |
// we don't want to use this function, because | |
// we don't store the FbId in database | |
// $user = $this->findUserByFbId($username); | |
// | |
$user = null; | |
try { | |
$fbdata = $this->facebook->api('/me'); | |
} catch (FacebookApiException $e) { | |
$fbdata = null; | |
} | |
if (!empty($fbdata)) { | |
// check user : find user with email | |
if (null === $user) { | |
$user = $this->findUserByEmail($fbdata['email']); | |
} | |
// new user : redirect to registration form | |
if (null === $user) { | |
$user = new User(); | |
$user->setUsername($fbdata['first_name'][0].$fbdata['last_name']); | |
$user->setEnabled(true); | |
$user->setPassword(''); | |
} | |
// TODO use http://developers.facebook.com/docs/api/realtime | |
$user->setFBData($fbdata); | |
if (count($this->validator->validate($user, 'Facebook'))) { | |
// TODO: the user was found obviously, but doesnt match our expectations, do something smart | |
throw new UsernameNotFoundException('The facebook user could not be stored'); | |
} | |
// $this->userManager->updateUser($user); | |
} | |
if (empty($user)) { | |
throw new UsernameNotFoundException('The user is not authenticated on facebook'); | |
} | |
return $user; | |
} | |
public function refreshUser(UserInterface $user) | |
{ | |
if (!$this->supportsClass(get_class($user)) || !$user->getFacebookId()) { | |
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); | |
} | |
return $this->loadUserByUsername($user->getFacebookId()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment