From 8237e7d2691fc96f271b0b9a4cd5fe338994b56c Mon Sep 17 00:00:00 2001 From: pkly Date: Mon, 7 Apr 2025 12:16:19 +0200 Subject: [PATCH 1/2] Prevent vendor class name overlap --- src/Generator.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Generator.php b/src/Generator.php index fbadc1bca..1e6b00454 100644 --- a/src/Generator.php +++ b/src/Generator.php @@ -181,19 +181,34 @@ public function getFileContentsForPendingOperation(string $targetPath): string public function createClassNameDetails(string $name, string $namespacePrefix, string $suffix = '', string $validationErrorMessage = ''): ClassNameDetails { $fullNamespacePrefix = $this->namespacePrefix.'\\'.$namespacePrefix; + $suggestedClassName = null; if ('\\' === $name[0]) { // class is already "absolute" - leave it alone (but strip opening \) $className = substr($name, 1); } else { $className = Str::asClassName($name, $suffix); + $suggestedClassName = rtrim($fullNamespacePrefix, '\\').'\\'.$className; try { Validator::classDoesNotExist($className); - $className = rtrim($fullNamespacePrefix, '\\').'\\'.$className; + $className = $suggestedClassName; + $suggestedClassName = null; } catch (RuntimeCommandException) { } } + if (null !== $suggestedClassName) { + Validator::validateClassName($suggestedClassName, $validationErrorMessage); + + // if this is a custom class, we may be completely different than the namespace prefix + // the best way can do, is find the PSR4 prefix and use that + if (!str_starts_with($suggestedClassName, $fullNamespacePrefix)) { + $fullNamespacePrefix = $this->fileManager->getNamespacePrefixForClass($suggestedClassName); + } + + return new ClassNameDetails($suggestedClassName, $fullNamespacePrefix, $suffix); + } + Validator::validateClassName($className, $validationErrorMessage); // if this is a custom class, we may be completely different than the namespace prefix From 680e56c96489fbeefe30761f20f63dd17d1c699e Mon Sep 17 00:00:00 2001 From: pkly Date: Tue, 8 Apr 2025 08:43:32 +0200 Subject: [PATCH 2/2] Also require the suggested class to exist to try to suggest it --- src/Generator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Generator.php b/src/Generator.php index 1e6b00454..e5d80e8ca 100644 --- a/src/Generator.php +++ b/src/Generator.php @@ -197,7 +197,7 @@ public function createClassNameDetails(string $name, string $namespacePrefix, st } } - if (null !== $suggestedClassName) { + if (null !== $suggestedClassName && class_exists($suggestedClassName)) { Validator::validateClassName($suggestedClassName, $validationErrorMessage); // if this is a custom class, we may be completely different than the namespace prefix