PHP如果条件

时间:2016-11-17 09:09:35

标签: php

我很尴尬。

我有三个函数来检查当前登录用户的内容:

public function isAuthor(User $user)
{
    return $user->getId() === $this->getDestination();
}

public function isSupervisor(User $user)
{
    return $user->getId() === $this->getFirstApprover();
}

public function isSecondApprover(User $user)
{
    return $user->getId() === $this->getSecondApprover();
}

然后我想在我的动作中添加一个条件来检查用户是否是上面提到的三个中的任何一个。如果他不是其中之一,则应拒绝访问。用户有时可能不止一个,但大多只是三个中的一个。'

我第一次想到这样的事情,但显然它无法正常工作

if (!$object->isAuthor($this->getUser()) || !$object->isSupervisor($this->getUser()) || !$object->isSecondApprover($this->getUser())) {
    throw new AccessDeniedException();
}

检查用户是否是其中之一的最佳方法是什么?我应该创建一个全新的功能吗?

我应该使用这样的东西:

if (!$object->isAuthor($this->getUser())) {
    throw new AccessDeniedException();
} elseif (!$object->isSupervisor($this->getUser())) {
    throw new AccessDeniedException();
}

我可以请其他人提出一些想法和意见吗?因为我现在真的很困惑。 还是新手

2 个答案:

答案 0 :(得分:1)

你的逻辑将起作用,它只是一个"反向"布尔逻辑,很复杂。它有一个bug,Use&&而不是||。

另一种选择

if ( ! (  $object->isAuthor($this->getUser()) || 
        $object->isSupervisor($this->getUser()) || 
        $object->isSecondApprover($this->getUser() ) ) 
{
    throw new AccessDeniedException();
}

另一种选择,你可以在" Object"中编写一个函数。类:

public function hasAccessLevelX( User $user )
{
    return in_array( $user->getId(), [
            $this->getDestination(),
            $this->getFirstApprover(),
            $this->getSecondApprover()
    ] );
}

if ( !$object->hasAccessLevelX( $this->getUser() ) ) {
    throw new AccessDeniedException();
}

我会使用后者。

答案 1 :(得分:0)

使用以下代码:

常用功能

public function userLogin(User $user)
{
    $userId = $user->getId();
    if($userId == $this->getDestination() || 
       $userId == $this->getFirstApprover() || 
       $userId == $this->getSecondApprover())
    {
        return TRUE;    
    }
    return FALSE;
}

使用/调用常用功能

if ($object->userLogin($this->getUser()) == FALSE) {
    throw new AccessDeniedException();
}