Jack Coolen Jack Coolen - 23 days ago 6
PHP Question

PHP If conditions

I'm embarrassed.

I have three functions to check what the current logged in user is:

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();
}


And then I want to add a condition inside my actions to check if the user is any of the above mentioned three. If he is not one of them access should be denied. A user can sometimes be more than one of them, but mostly only one of the three.'

I was first thinking of something like this, but obviously it can't work

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


What will be the best way to check if a user is one of them? Should I create a whole new function?

Should I use something like this:

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


Can I please have some thoughts and input from others? Because I'm now really confused. Still a newbie here

Answer

Use below code:

Common Function

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

Use/Call of common function

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