public function save(IUser $user): bool
    {
        if ($user instanceof AnonymousUser) {
            return false;
        }

        if ($user->isNew()) {
            $roles = $this->filterRoles($user->getUserRoles());
            $user->addRoles(array_values($roles));
            return entityManager()->save($user);
        }

        if (!entityManager()->save($user)) {
            return false;
        }

        if (null !== $roles = $user->getUserRoles()) {
            $toAdd = $this->filterRoles($roles);
            $toRemove = [];

            foreach ($user->roles() as $role) {
                $name = $role->name();
                if (!isset($toAdd[$name])) {
                    $toRemove[] = $role;
                } else {
                    unset($toAdd[$name]);
                }
            }

            if (!empty($toRemove)) {
                $user->removeRoles($toRemove);
            }

            if (!empty($toAdd)) {
                $user->addRoles(array_values($toAdd));
            }
        }

        return true;
    }