Question

I'm working permissions represented by bitmasks. These permissions are

$permissionMap = [
    'VIEW'     => 1;
    'CREATE'   => 2;
    'EDIT'     => 4;
    'DELETE'   => 8
    'UNDELETE' => 16;         
    'OPERATOR' => 32;         
    'MASTER'   => 64;         
    'OWNER'    => 128;
];       

If I combine multiple permissions, say VIEW ,EDIT, and DELETE to get a bitmask of 13. Is it possible to reverse engineer that integer to know what permissions were used to create it?

function getPermissions($mask, $permissionMap) {
    // use $permissionMap to return string[] 
}

$viewEditAndDelete = 1 | 4 | 8; // 13

getPermissions($viewEditAndDelete, $permissionMap); // ['VIEW', 'EDIT', 'DELETE']
Was it helpful?

Solution

Just check for if a particular mask is set. It's pretty simple actually if we loop through the $map and check if its flag is set:

function getPermissions($mask, $permissionMap) {
    $permissions = [];
    foreach( $permissionMap as $perm => $val )
        if( $mask & $val )
            array_push( $permissions, $perm );
    return $permissions;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top