2017-04-13 23 views
0

我想知道如何執行一個實體的選民內的字段檢查。與symfony中的選民單場檢查

我有例如我的實體發佈,我希望用戶不是管理員不能編輯標題字段。只有管​​理員可以編輯此字段。

所以我創建了我的選民,但我不知道如何,因爲裏面$post有老後的實體創建這樣的檢查,我不知道如何實現在檢查title

這是我的簡單選民檔案

class PostVoter extends Voter 
{ 
    const VIEW = 'view'; 
    const EDIT = 'edit'; 

    private $decisionManager; 

    public function __construct(AccessDecisionManagerInterface $decisionManager) 
    { 
     $this->decisionManager = $decisionManager; 
    } 

    protected function supports($attribute, $subject) 
    { 
     if (!in_array($attribute, array(self::VIEW, self::EDIT))) { 
      return false; 
     } 

     if (!$subject instanceof Post) { 
      return false; 
     } 

     return true; 
    } 

    protected function voteOnAttribute(
     $attribute, 
     $subject, 
     TokenInterface $token 
    ) { 
     $user = $token->getUser(); 

     if (!$user instanceof User) { 
      return false; 
     } 

     if ($this->decisionManager->decide($token, array('ROLE_SUPER_ADMIN'))) { 
      return true; 
     } 

     /** @var Post $post */ 
     $post = $subject; 

     switch ($attribute) { 
      case self::VIEW: 
       return $this->canView($post, $user); 
      case self::EDIT: 
       return $this->canEdit($post, $user); 
     } 

     throw new \LogicException('This code should not be reached!'); 
    } 

    private function canView(Post $post, User $user) 
    { 
     if ($this->canEdit($post, $user)) { 
      return true; 
     } 

     return true; 
    } 

    private function canEdit(Post $post, User $user) 
    { 
     return $user === $post->getUser(); 
    } 
} 

我想在canEdit中實現一個標題欄檢查。 我試圖打印$發佈,但只有舊值不是一些新的價值信息。

+0

只是爲了澄清,你試圖確定標題已從選民內部改變? – Cerad

+0

是的,或者如果不是更好的方式告訴我,我將這個邏輯移動到控制器或服務中。我不知道如何檢查字段 –

回答

1

幾種可能的方法。

我會使用的是爲選民添加一個'edit_title'權限,然後調整我的表單,使標題只有在edit_title權限被拒絕時纔會被讀取。這不僅消除了檢查改變的標題的需要,而且使得用戶對於事情有點友好。有人可能會想到,他們對錶單感到有點沮喪,因爲表單允許他們更改標題,但是應用會拒絕更改。

如果您確實想要檢測標題更改,那麼您可以調整post實體中的setTitle方法。就像:

class Post { 
    private $titleWasChanged = false; 
    public function setTitle($title) { 
     if ($title !== $this->title) $this->titleWasChanged = true; 
     $this->title = $title; 

然後,當然檢查從選民$ titleWasChanged。

如果你真的想全力以赴,Doctrine實體管理器實際上有一些改變檢查功能。你可能可以通過選民訪問它,但這可能會矯枉過正。 http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/change-tracking-policies.html

+0

非常有趣的解決方案的最佳途徑!我會嘗試。 非常感謝 –