<?php
namespace App\Modules\TangibleAsset\Security;
use App\Modules\TangibleAsset\Entity\ListingPhoto;
use App\Modules\TangibleAsset\Service\AssetAccessService;
use App\Modules\User\Entity\UserContract;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class ListingPhotoVoter extends Voter
{
const DELETE_LISTING_PHOTO = 'delete_listing_photo';
static $access = [
self::DELETE_LISTING_PHOTO,
];
private $security;
/**
* @var AssetAccessService
*/
private $planeAccessService;
public function __construct(Security $security, AssetAccessService $planeAccessService)
{
$this->security = $security;
$this->planeAccessService = $planeAccessService;
}
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool True if the attribute and subject are supported, false otherwise
*/
protected function supports($attribute, $subject)
{
if (!in_array($attribute, self::$access)) {
return false;
}
return true;
}
/**
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param string $attribute
* @param mixed $subject
*
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$loginedUser = $token->getUser();
if (!$loginedUser instanceof UserContract) {
// the user must be logged in; if not, deny access
return false;
}
$listingPhoto = $subject;
switch ($attribute) {
case self::DELETE_LISTING_PHOTO:
return $this->canDelete($listingPhoto, $loginedUser);
}
}
private function canDelete(ListingPhoto $listingPhoto, UserContract $loginedUser)
{
$listing = $listingPhoto->getListing();
$plane = $listing->getAsset();
if ($this->planeAccessService->userHasAccess($plane, $loginedUser)) {
return true;
}
return false;
}
}