Skip to content

Instantly share code, notes, and snippets.

@kayue
Created December 2, 2014 15:27
Show Gist options
  • Save kayue/f563394b7ee35a326aad to your computer and use it in GitHub Desktop.
Save kayue/f563394b7ee35a326aad to your computer and use it in GitHub Desktop.
class WordpressPostVoter implements VoterInterface
{
const VIEW = 'view';
const EDIT = 'edit';
protected $wordpressRegistry;
public function __construct(ManagerRegistry $wordpressRegistry)
{
$this->wordpressRegistry = $wordpressRegistry;
}
public function supportsAttribute($attribute)
{
return in_array($attribute, [
self::VIEW,
self::EDIT,
]);
}
public function supportsClass($class)
{
$supportedClass = 'Kayue\WordpressBundle\Entity\Post';
return $supportedClass === $class || is_subclass_of($class, $supportedClass);
}
public function vote(TokenInterface $token, $post, array $attributes)
{
if (!$this->supportsClass(get_class($post))) {
return VoterInterface::ACCESS_ABSTAIN;
}
if (1 !== count($attributes)) {
throw new \InvalidArgumentException('Only one attribute is allowed for VIEW or EDIT');
}
$attribute = $attributes[0];
if (!$this->supportsAttribute($attribute)) {
return VoterInterface::ACCESS_ABSTAIN;
}
/** @var $user User */
$user = $token->getUser();
if (false === $user instanceof User || !is_numeric($user->getWordpressId())) {
return VoterInterface::ACCESS_ABSTAIN;
}
$blogId = $this->getManager()->getBlogId();
try {
$capabilities = $this->getManager()->createQueryBuilder()
->select('m.value')
->from('KayueWordpressBundle:UserMeta', 'm')
->join('m.user', 'u')
->andWhere('u.id = :user_id')
->andWhere('m.key = :key')
->setParameter('key', 'wp_'.($blogId > 1 ? $blogId . '_' : '').'capabilities')
->setParameter('user_id', $user->getWordpressId())
->getQuery()
->getSingleScalarResult();
$capabilities = unserialize($capabilities);
} catch (UnexpectedResultException $ex) {
return VoterInterface::ACCESS_ABSTAIN;
}
switch ($attribute) {
case self::EDIT:
foreach (['administrator', 'editor', 'contributor', 'super_editor'] as $role) {
if (isset($capabilities[$role])) {
return VoterInterface::ACCESS_GRANTED;
}
}
break;
case self::VIEW:
return VoterInterface::ACCESS_GRANTED;
break;
}
return VoterInterface::ACCESS_DENIED;
}
protected function getManager()
{
return $this->wordpressRegistry->getManager();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment