How to replace SNAPSHOT dependencies with their respective Releases

I’m currently struggling to implement a feature for my build. I want all internal artifacts to be release artifacts during a release build.

I’m able to do the following statically:

configurations.all {
	resolutionStrategy {
		dependencySubstitution {
			substitute module("$groupId:demo2:1.0.3-SNAPSHOT") with module("$groupId:demo2:1.0.3")
		}
	}
}

What I would want to do instead is the following:

configurations.all {
	resolutionStrategy {
		dependencySubstitution {
			all { DependencySubstitution dependency ->
				if (dependency.requested instanceof ModuleComponentSelector) {
					if (dependency.requested.group == groupId && dependency.requested.version.endswith(SNAPSHOT)) {
						substitute module(groupId + ":" + dependency.requested.name + ":" + dependency.requested.version) with module(groupId + ":" + dependency.requested.name + ":" + dependency.requested.version.replace(SNAPSHOT,""))
					}
				}
			}
		}
	}
}

But this fails the dependency resolution:

me@my-PC MINGW64 /d/workspaces/workspace-test/demo1 (master)
$ ./gradlew dependencies
Parallel execution with configuration on demand is an incubating feature.
:dependencies

------------------------------------------------------------
Root project - Some description
------------------------------------------------------------

apiElements - API elements for main. (n)
No dependencies

archives - Configuration for archive artifacts.
No dependencies

compile - Dependencies for source set 'main' (deprecated, use 'implementation ' instead).
+--- my.company:demo2:1.0.3-SNAPSHOT FAILED

[...]

I can’t iterate over the dependencies after resolution for obvious reasons. I thus would need a generic filter of some sort which replaces the “-SNAPSHOT” part of the version of each dependency with “”, but only for the groupId I specified.

Why does the former work as expected but the later doesn’t? Is there another way I might have missed so far to pre-process dependencies and modify their versions before they are actually resolved?