Add the role inheritence "where" clause to the given query.

@param  \Illuminate\Database\Query\Builder  $query
@param  \Illuminate\Database\Eloquent\Model  $authority
@param  string  $roles
@return \Closure
496461
protected static function addRoleInheritCondition(Builder $query, Model $authority, $roles)
    {
        $query->orWhere('level', '<', function ($query) use ($authority, $roles) {
            $query->selectRaw('max(level)')
                  ->from($roles)
                  ->whereExists(static::getAuthorityRoleConstraint($authority));

            Models::scope()->applyToModelQuery($query, $roles);
        });
    }
1069649
private function getRule($role, $resource, $privilege)
    {
        $role = $this->roles->get($role);

        if (is_scalar($resource)) {
            $resource = new Resource($resource);
        } elseif (!$resource instanceof ResourceInterface) {
            throw new \InvalidArgumentException('$resource is expected to be of type string or Gobline\Acl\ResourceInterface');
        }

        if (is_scalar($privilege)) {
            $privilege = new Privilege($privilege);
        } elseif (!$privilege instanceof Privilege) {
            throw new \InvalidArgumentException('$privilege is expected to be of type string or Gobline\Acl\Privilege');
        }

        foreach ($this->rules as $rule) {
            if (!$rule->getRole()->equals($role)) {
                continue;
            }
            if (!$rule->getPrivilege()->equals($privilege) && !$rule->getPrivilege()->equals('*')) {
                continue;
            }
            if (!$rule->getResource()->matches($resource) && (!$rule->getResource() instanceof Resource || !$rule->getResource()->matches('*'))) {
                continue;
            }

            return $rule;
        }

        foreach ($role->getParents() as $role) {
            $rule = $this->getRule($role, $resource, $privilege);
            if ($rule !== null) {
                return $rule;
            }
        }

        return null;
    }
227922
public function scopeWhereRole($query, $role)
    {
        return $query->whereHas('roles', function ($query) use ($role) {
            return $query->where('keyword', $role);
        });
    }
846557
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        if ($parentQuery->getQuery()->from == $query->getQuery()->from) {
            return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
        }

        return $query->select($columns)->whereColumn(
            $this->getQualifiedForeignKeyName(), '=', $query->qualifyColumn($this->ownerKey)
        );
    }
1162277
public function scopeRole(Builder $query, $roles): Builder
    {
        if ($roles instanceof Collection) {
            $roles = $roles->all();
        }

        if (! is_array($roles)) {
            $roles = [$roles];
        }

        $roles = array_map(function ($role) {
            if ($role instanceof Role) {
                return $role;
            }

            return RoleProxy::findByName($role, $this->getDefaultGuardName());
        }, $roles);

        return $query->whereHas('roles', function ($query) use ($roles) {
            $query->where(function ($query) use ($roles) {
                foreach ($roles as $role) {
                    $query->orWhere('roles.id', $role->id);
                }
            });
        });
    }
1303004
protected function addConditions($query, $conditions)
    {
        foreach ($conditions as $key => $value) {
            if ($value instanceof Closure) {
                $query->where(function ($query) use ($value) {
                    $value($query);
                });
            } else {
                $this->addWhere($query, $key, $value);
            }
        }

        return $query;
    }
1002443
private function getQueryRunner(Query $query, int $flags = 0): QueryRunnerInterface
    {
        $showContextualSlots = (bool) ($flags & ResultSet::INCLUDE_UNKNOWN_ITEMS);

        if ($showContextualSlots && $query->isContextual()) {
            return new ContextualQueryRunner();
        }

        return new QueryRunner($this->cmsItemBuilder);
    }
615077
protected function queryAddAccessPolicyCondition($access_policy_name, $query)
	{
		// Allow by default
		if (empty($access_policy_name)) {
			return;
		}

		if (!isset($this->access_policies[$access_policy_name])) {
			throw new \InvalidArgumentException('Unknown policy: '.$access_policy_name);
		}
		$access_policy = $this->access_policies[$access_policy_name];

		//debug_dump($access_policy, 'POLICY: '.$access_policy_name.' @ '.get_class($this));

		if ($this->auth->isAllMighty()) {
			// FIXME: Remove hardcoded role name
			return;
		}

		switch ($access_policy['type']) {

			// anyone: Completely open for anyone
			case 'anyone':
				return;

			// anonymous: Only anonymous users allowed (not logged in)
			case 'anonymous':
				$user_id = $this->auth->getUserId();
				$query->where($user_id === null ? 'TRUE' : 'FALSE');
				return;

			// user: All logged-in users allowed
			case 'user':
				$user_id = $this->auth->getUserId();
				$query->where($user_id !== null ? 'TRUE' : 'FALSE');
				return;

			// owner: Owner must match current user
			case 'owner':
				$user_id = $this->auth->getUserId();
				$owner_property = $query->quoteIdent($access_policy['owner_property']);
				$table = $query->quoteIdent($this->table);
				if (isset($access_policy['session_state'])) {
					if ($this->auth->getSessionMachine()->state != $access_policy['session_state']) {
						$query->where('FALSE');
						return;
					}
				}
				if ($user_id === null) {
					$query->where("$table.$owner_property IS NULL");
					return;
				} else {
					$query->where("$table.$owner_property = ?", $user_id);
					return;
				}

			// role: Current user must have specified role ($ref is ignored)
			case 'role':
				$query->where($this->auth->hasUserRoles($access_policy['required_role']) ? 'TRUE' : 'FALSE');
				return;

			// These are done by SQL select.
			case 'condition':
				$this->queryAddSimpleAccessPolicyCondition($access_policy_name, $access_policy, $query, 'where');
				return;

			// These are done by SQL select.
			case 'user_relation':
				$this->queryAddUserRelationAccessPolicyCondition($access_policy_name, $access_policy, $query, 'where');
				return;

			// unknown policies are considered unsafe
			default:
				$query->where('FALSE');
				return;
		}

		// This should not happen.
		throw new \RuntimeException('Policy '.$policy.' did not decide.');
	}
53053
protected function whereBasic(Builder $query, $where)
    {
        if (Str::contains(strtolower($where['operator']), 'like')) {
            return sprintf(
                '%s::text %s %s',
                $this->wrap($where['column']),
                $where['operator'],
                $this->parameter($where['value'])
            );
        }

        return parent::whereBasic($query, $where);
    }
466079
public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
	{
		$query->select($columns);

		$key = $this->wrap($this->getQualifiedParentKeyName());

		return $query->where($this->getHasCompareKey(), '=', new Expression($key));
	}
450655
public function countUsersByRole(Role $role, $restrictionRoleNames = null, $organizations = null)
    {
        $qb = $this->createQueryBuilder('user')
            ->select('COUNT(DISTINCT user.id)')
            ->leftJoin('user.roles', 'roles')
            ->andWhere('roles.id = :roleId')
            ->andWhere('user.isEnabled = :enabled')
            ->setParameter('roleId', $role->getId())
            ->setParameter('enabled', true);
        if (!empty($restrictionRoleNames)) {
            $qb->andWhere('user.id NOT IN (:userIds)')
                ->setParameter('userIds', $this->findUserIdsInRoles($restrictionRoleNames));
        }
        if (null !== $organizations) {
            $qb->join('user.userOrganizationReferences', 'orgaRef')
                ->andWhere('orgaRef.organization IN (:organizations)')
                ->setParameter('organizations', $organizations);
        }
        $query = $qb->getQuery();

        return $query->getSingleScalarResult();
    }
1196759
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        if ($parentQuery->getQuery()->from === $query->getQuery()->from) {
            return $this->getRelationExistenceQueryForSelfRelation($query, $parentQuery, $columns);
        }

        return $query->select($columns)->whereColumn(
            $this->getQualifiedForeignKey(),
            '=',
            $query->getModel()->getTable() . '.' . $this->ownerKey
        );
    }
4206
public function addRoleForUser($userId, $roleName)
    {
        $roleIdExpression = new Expression(
            '(SELECT `id` from `user_roles` WHERE `name` = ?)',
            $roleName
        );

        $query = $this->getSqlObject()
            ->insert()
            ->values([
                'user_id' => $userId,
                'role_id' => $roleIdExpression,
            ]);

        $this->execute($query);
    }
630061
private function queryJoinBuilder($query, $relation)
    {
        $relatedTable = $relation->getRelated()->getTable();
        $parentTable  = $relation->getParent()->getTable();

        if ($parentTable === $relatedTable) {
            $query       = $query->from($parentTable.' as parent_'.$parentTable);
            $parentTable = 'parent_'.$parentTable;
            $relation->getParent()->setTable($parentTable);
        }

        if ($relation instanceof HasOne) {
            $relatedPrimaryKey = $relation->getQualifiedForeignKeyName();
            $parentPrimaryKey  = $relation->getQualifiedParentKeyName();
        } elseif ($relation instanceof BelongsTo) {
            $relatedPrimaryKey = $relation->getQualifiedOwnerKeyName();
            $parentPrimaryKey  = $relation->getQualifiedForeignKeyName();
        } else {
            throw new \Exception();
        }

        return $this->formJoin($query, $parentTable, $relatedTable, $parentPrimaryKey, $relatedPrimaryKey);
    }
56025
protected function assignRoles(Collection $roles, $authorityClass, Collection $authorityIds)
    {
        $roleIds = $roles->map(function ($model) {
            return $model->getKey();
        });

        $morphType = (new $authorityClass)->getMorphClass();

        $records = $this->buildAttachRecords($roleIds, $morphType, $authorityIds);

        $existing = $this->getExistingAttachRecords($roleIds, $morphType, $authorityIds);

        $this->createMissingAssignRecords($records, $existing);
    }
1023285
public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());

        $query->getModel()->setTable($hash);

        return $query->select($columns)->whereColumn(
            $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->getForeignKeyName()
        );
    }
788721
public function scopeWhereOwnedBy(Builder $query, CanBeOwnerContract $owner)
    {
        return $query->where([
            'owned_by_id' => $owner->getKey(),
            'owned_by_type' => $owner->getMorphClass(),
        ]);
    }