<?php
// src/CommerceBundle/Security/MaterialVoter.php
namespace Uniski\CommerceBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Uniski\CommerceBundle\Entity\Booking;
use Uniski\UserBundle\Entity\User;
class BookingVoter extends Voter
{
// these strings are just invented: you can use anything
const CANCEL = 'cancel';
const VIEW = 'view';
const PAY = 'pay';
const APPLY_CANCEL = 'apply_cancel';
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, array(
self::CANCEL, self::VIEW, self::PAY, self::APPLY_CANCEL))) {
return false;
}
// only vote on Booking objects inside this voter
if (!$subject instanceof Booking) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $booking, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
switch($attribute) {
case self::CANCEL:
return $this->canCancel($booking, $user);
case self::VIEW:
return $this->canView($booking, $user);
case self::PAY:
return $this->canPay($booking, $user);
case self::APPLY_CANCEL:
return $this->canApplyCancel($booking, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canCancel(Booking $booking, User $user)
{
if (( $user->hasRole('ROLE_ADMIN') ||
$user->hasRole('ROLE_SALESMAN') ) &&
$booking->getStatus() != Booking::STATUS_DELETED) return true;
return $booking->getStatus() == Booking::STATUS_PRE_BOOKED &&
$booking->getUser()->getId() == $user->getId();
}
private function canApplyCancel(Booking $booking, User $user)
{
if (( $user->hasRole('ROLE_ADMIN') ||
$user->hasRole('ROLE_SALESMAN') ) &&
$booking->getStatus() != Booking::STATUS_DELETED) return true;
return ($booking->getStatus() == Booking::STATUS_PAYED ||
$booking->getStatus() == Booking::STATUS_HALF_PAYED) &&
$booking->getDateIn() > new \DateTime() &&
$booking->getUser()->getId() == $user->getId();
}
private function canView(Booking $booking, User $user)
{
if ( $user->hasRole('ROLE_ADMIN') ||
$user->hasRole('ROLE_SALESMAN')) return true;
else return $booking->getUser()->getId() == $user->getId();
}
private function canPay(Booking $booking, User $user)
{
if ( $booking->getUser()->getId() != $user->getId() ) return false;
return $booking->getStatus() == Booking::STATUS_PENDING ||
$booking->getStatus() == Booking::STATUS_HALF_PAYED;
}
}