0

I have tried searching the answer to my question in the following docs:

  1. PHP logical operators
  2. PHP operator precedence

The question

What I'm trying to understand is if PHP does actually takes into account Laws and Theorems of Boolean Algebra. An example would be:

// Complement Law
X + ~X = 1

Translating that into PHP code:

if (true || false) {
  // logically it will evaluate to true due to `Complement law`
}

// in a more complicated example:

return true
  || false
  || true
  || true
  || true;

// a more real world example. Check for permissions of a certain user to a certain resource
return $this->canSeeResource()
  || $this->hasSuperPermission()
  || $this->isAdministrator();

Does PHP takes into consideration the complement law when evaluating a boolean operation?

In other words

Does PHP executes all three methods (canSeeResource, hasSuperPermission and isAdministrator) if the first expression is true?

Why the question

I have the following logic to check if the user has the permission to see a certain resource:

return $user->hasPermission(static::$MANAGE_ALL_ISSUES_PERMISSION_NAME)
            || $this->userIsOwnerAndHasPermissionToEditOwnIssues($user, $model)
            || $this->userHasSiteAndPermissionToManageSiteIssues($model, $user)
            || IssuePolicy::canAccessViaGroup($user, Issue::whereTodoId($model->id)->first())
            || $this->userAssignedAndIssueNotDoneOrDoneAndUserHasPermission($model, $user)
                ? Response::allow()
                : Response::deny('User can not access todo.');

In this expression I would like to first check if a user has the permission $MANAGE_ALL_ISSUES_PERMISSION_NAME in order to be able to access this resource. Each one of these methods hits the database.

If PHP implements the Laws and theorems of boolean algebra in the first case (in the case that a user has the permission) we would exit the expression right away (as the first expression would be true), if not then I have to re-change my code to do:

if ($user->hasPermission(static::$MANAGE_ALL_ISSUES_PERMISSION_NAME)) { return true; }

if ($this->userIsOwnerAndHasPermissionToEditOwnIssues($user, $model)) { return true; }

...

in order to save some hits to the database.

Bruno Francisco
  • 3,841
  • 4
  • 31
  • 61

0 Answers0