From 79b2b4e0fbc1d1ef6ae99c4e078137b42bd43d19 Mon Sep 17 00:00:00 2001
From: Vincent Langlet <VincentLanglet@users.noreply.github.com>
Date: Mon, 2 Sep 2024 15:35:10 +0200
Subject: [PATCH] fix: Fix aliasing functions with multiple-level namespaces
 (#1061)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---------

Co-authored-by: Théo FIDRY <5175937+theofidry@users.noreply.github.com>
---
 src/Autoload/ScoperAutoloadGenerator.php       | 2 +-
 tests/Autoload/ScoperAutoloadGeneratorTest.php | 5 +++++
 2 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/Autoload/ScoperAutoloadGenerator.php b/src/Autoload/ScoperAutoloadGenerator.php
index b4c9206a..decbbf11 100644
--- a/src/Autoload/ScoperAutoloadGenerator.php
+++ b/src/Autoload/ScoperAutoloadGenerator.php
@@ -306,7 +306,7 @@ private static function groupFunctionsByNamespace(array $exposedFunctions): arra
             $originalFQ = new FullyQualified($exposed);
 
             $namespace = $originalFQ->slice(0, -1);
-            $functionName = null === $namespace ? $exposed : (string) $originalFQ->slice(1);
+            $functionName = null === $namespace ? $exposed : (string) $originalFQ->slice(-1, 1);
 
             $groupedFunctions[(string) $namespace][] = [$exposed, $functionName, $prefix];
         }
diff --git a/tests/Autoload/ScoperAutoloadGeneratorTest.php b/tests/Autoload/ScoperAutoloadGeneratorTest.php
index 7fa4b91d..939de540 100644
--- a/tests/Autoload/ScoperAutoloadGeneratorTest.php
+++ b/tests/Autoload/ScoperAutoloadGeneratorTest.php
@@ -188,6 +188,7 @@ public static function provideRegistry(): iterable
                     ['Acme\bar', 'Humbug\Acme\bar'],
                     ['Acme\foo', 'Humbug\Acme\foo'],
                     ['Emca\baz', 'Humbug\Emca\baz'],
+                    ['Acme\Emca\foo', 'Humbug\Acme\Emca\foo'],
                 ],
             ),
             [],
@@ -218,6 +219,10 @@ public static function provideRegistry(): iterable
 
                 // Function aliases. For more information see:
                 // https://github.com/humbug/php-scoper/blob/master/docs/further-reading.md#function-aliases
+                namespace Acme\Emca {
+                    if (!function_exists('Acme\Emca\foo')) { function foo() { return \Humbug\Acme\Emca\foo(...func_get_args()); } }
+                }
+
                 namespace Acme {
                     if (!function_exists('Acme\bar')) { function bar() { return \Humbug\Acme\bar(...func_get_args()); } }
                     if (!function_exists('Acme\foo')) { function foo() { return \Humbug\Acme\foo(...func_get_args()); } }