Skip to content

Instantly share code, notes, and snippets.

@kevindees
Last active July 27, 2018 07:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevindees/76dde5f6e79c94d6699ae6fde48a9b57 to your computer and use it in GitHub Desktop.
Save kevindees/76dde5f6e79c94d6699ae6fde48a9b57 to your computer and use it in GitHub Desktop.
Faster user role detection when passing requirements as a string
<?php
class User {
const ROLE_GUEST = 2;
const ROLE_SHOPPER = 4;
const ROLE_ADMIN = 8;
const ROLE_SUPER = 16;
}
function has_role($role, $roles) {
return $role & $roles;
}
$roles = User::ROLE_ADMIN | User::ROLE_SUPER;
var_dump( has_role(User::ROLE_GUEST, $roles)); // retruns 0
var_dump( has_role(User::ROLE_ADMIN, $roles)); // returns 8
var_dump( has_role(User::ROLE_ADMIN | User::ROLE_SUPER, $roles)); // returns 24
<?php
class User {
const ROLE_GUEST = 1;
const ROLE_SHOPPER = 2;
const ROLE_ADMIN = 3;
const ROLE_SUPER = 4;
}
function has_role($check, $roles) {
$exploded_roles = explode('|', $roles);
if(is_array($check)) {
foreach ($check as $role) {
if(in_array($role, $exploded_roles)) { return true; }
return false;
}
}
return in_array($check, $exploded_roles);
}
$roles = implode('|', [User::ROLE_ADMIN, User::ROLE_SUPER]);
var_dump( has_role(User::ROLE_GUEST, $roles)); // retruns false
var_dump( has_role(User::ROLE_ADMIN, $roles)); // retruns true
var_dump( has_role([User::ROLE_ADMIN, User::ROLE_SUPER], $roles)); // retruns true
@kevindees
Copy link
Author

kevindees commented Jul 5, 2018

Example

Note that in this example I'm trying to reduce the role information into a compact form so that it can be passed around a single scalar value. We are trying not to use an array or DB to pass the role information around the program.

Information

In this example, I'm using the bitwise operators do work the roles magic. These operators give you a great deal of flexibility. One of the biggest benefits is not just the speed and eloquence of the code but also that the return value is more informative.

http://php.net/manual/en/language.operators.bitwise.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment