From 197ca2a237d3172a358d40a6940a8dd659e350e6 Mon Sep 17 00:00:00 2001 From: WenRenHai Date: Thu, 26 Sep 2024 21:01:25 +0800 Subject: [PATCH] Added `Hyperf\Database\Model\Relations\Relation::getMorphAlias()`. (#7025) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 李铭昕 <715557344@qq.com> --- src/Model/Relations/Relation.php | 8 ++++++++ tests/ModelTest.php | 16 ++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/Model/Relations/Relation.php b/src/Model/Relations/Relation.php index a1cd915..62f26d7 100755 --- a/src/Model/Relations/Relation.php +++ b/src/Model/Relations/Relation.php @@ -349,6 +349,14 @@ public function getRelationCountHash(bool $incrementJoinCount = true) return 'hyperf_reserved_' . ($incrementJoinCount ? static::$selfJoinCount++ : static::$selfJoinCount); } + /** + * Get the alias associated with a custom polymorphic class. + */ + public static function getMorphAlias(string $className): string + { + return array_search($className, static::$morphMap, strict: true) ?: $className; + } + /** * Get all of the primary keys for an array of models. * diff --git a/tests/ModelTest.php b/tests/ModelTest.php index 41be159..250a5d7 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -91,15 +91,11 @@ class ModelTest extends TestCase protected function setUp(): void { - parent::setUp(); - Carbon::setTestNow(Carbon::now()); } protected function tearDown(): void { - parent::tearDown(); - Mockery::close(); Carbon::setTestNow(null); @@ -2075,6 +2071,18 @@ public function testUuid() $this->assertTrue(Str::isUuid($model->newUniqueId())); } + public function testGetMorphAlias() + { + Relation::morphMap(['user' => ModelStub::class]); + + try { + $this->assertSame('user', Relation::getMorphAlias(ModelStub::class)); + $this->assertSame('Does\Not\Exist', Relation::getMorphAlias('Does\Not\Exist')); + } finally { + Relation::morphMap([], false); + } + } + protected function getContainer() { $container = Mockery::mock(ContainerInterface::class);