When should I return?

I am struggling to create an access object to sections stored in the Database. This is a skellington of the process, this contains static data until I can get the principle working.

class User {
    const IS_ADMIN = 1;
    const IS_MODERATOR = 2;
    const IS_MEMBER = 4;
}

This class will auto-load data from the database eventually but for the time being, this class has default values.

class Scope {
    private $priv = [];

    public function __construct() {
        $this->priv = [1];
    }

    public function getPrivilidges() {
        return $this->priv;
    }
}

This is where it messes up, I can tell that the second and third conditions cannot be met if the first fails, how can I stop this?

class Priverlidges {
    public function canView($type, Scope $scope) {
        if($type & User::IS_ADMIN) {
            foreach($scope->getPrivilidges() as $p) {
                if($p == User::IS_ADMIN) continue;
                return false;
            }
            return true;
        }

        if($type & User::IS_MODERATOR) {
            foreach($scope->getPrivilidges() as $p) {
                if($p == User::IS_MODERATOR) continue;
                return false;
            }
            return true;
        }

        if($type & User::IS_MEMBER) {
            foreach($scope->getPrivilidges() as $p) {
                if($p == User::IS_MEMBER) continue;
                return false;
            }
            return true;
        }
    }
}

Example usage which works fine when the default value of the priverlidge is 1:

echo (int)(new Priverlidges)->canView(User::IS_ADMIN, new Scope());

Example usage which works fine when the default value of the priverlidge is 2:

echo (int)(new Priverlidges)->canView(User::IS_MODERATOR | User::IS_ADMIN, new Scope()); // it returns false at the first condition

Can anyone help me with when to return true or false? Thanks in advance.
PS - Users can be both Mods and Admins

EDIT: I have tried to use in_array() and still am unsure when to return the value true or false because it get's overwrite if the second method runs.


I figured it out. First, check the user is not already authenticated using a placeholder ( $this->_state ). Then check the type of user and check it is inside the scope.

class Priverlidges {

    private $_state = false;

    public function canView($type, Scope $scope) {
        if(!$this->_state && $type & User::IS_ADMIN && in_array(User::IS_ADMIN, $scope->getPrivilidges())) {
            $this->_state = true;
        }

        if(!$this->_state && $type & User::IS_MODERATOR && in_array(User::IS_MODERATOR, $scope->getPrivilidges())) {
            $this->_state = true;
        }

        if(!$this->_state && $type & User::IS_MEMBER && in_array($scope->getPrivilidges(), User::IS_MEMBER)) {
            $this->_state = true;
        }

        return $this->_state;
    }

}
链接地址: http://www.djcxy.com/p/58874.html

上一篇: 管理员角色只能通过身份验证

下一篇: 我应该什么时候回来?