I'm trying to create an "enum" class in PHP using bitwise operations.
class PermissionBitmap {
const VIEW = 1;
//if you can EDIT, you can VIEW
const EDIT = 2 | self::VIEW;
//if you can CREATE, you can VIEW
const CREATE = 4 | self::VIEW;
//if you can DELETE you can VIEW
const DELETE = 8 | self::VIEW;
//if you are ADMIN you can VIEW, EDIT, CREATE and DELETE
const ADMIN = self::EDIT | self::CREATE | self::DELETE;
//function to check if $permisison1 is contain within $permision2
// perm_contains(self::VIEW, self::CREATE); //should return true.
// perm_contains(self::DELETE, self::ADMIN); //should return true.
// perm_contains(self::CREATE, self::EDIT); //should return false.
public static function perm_contains($permisison1, $permisison2): bool {
return ($permisison1 & $permisison2) === $permisison1;
}
}
var_dump(PermisisonBitmap::EDIT); //sums to 3... all correct bits are set
var_dump(PermissionBitmap::ADMIN); //sums to 15... all correct bits are set
So, I've set up the 'enum' to cascade such that specific permissions are contained within higher ones. (e.g. VIEW should be contained in EDIT, CREATE and DELETE. Everything should be contained in ADMIN). I think using the bitwise or (|) is the correct way to do that, and seems to yield the correct results.
The problem I'm having is how to test, given two permissions, if one is contained within the other. What I have presently is ($permisison1 & $permisison2) === $permisison1;
, but I'm skeptical of it's universal correctness.
Should this be correct in all cases (i.e. if I add more complicated permissions to the enum)? Or is the there a better / more correct way of doing this?
There is no need to create self made enums, when using PHP >= 8.1, because it is part of the language.
But to answer your question, your bitwise operators are correct.
|
to combine multiple bits (logical bitwise or)&
to check if a bit is set (logical bitwise and)^
to toggle a bit (logical bitwise xor)Also make sure to not have ||
or &&
which are no bitwise comparisions.
See: Operator precedence and Bitwise operators