diff --git a/CHANGELOG.md b/CHANGELOG.md index a8103d02..f924d84f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,7 @@ - Enh #245: Handle same names during renaming item in `AssignmentsStorage` (@arogachev) - Chg #208: Rename `getAccessTree()` to `getHierarchy()` in `ItemsStorageInterface` (@arogachev) - Enh #251: Allow checking for user's roles in `ManagerInterface::userHasPermission()` (@arogachev) +- Enh #252: Return `$this` instead of throwing "already assigned" exception in `Manager::assign()` (@arogachev) ## 1.0.2 April 20, 2023 diff --git a/src/Manager.php b/src/Manager.php index 4ce3e9e0..8e11ee2b 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -160,9 +160,7 @@ public function assign(string $itemName, int|Stringable|string $userId, ?int $cr } if ($this->assignmentsStorage->exists($itemName, $userId)) { - throw new InvalidArgumentException( - "\"$itemName\" {$item->getType()} has already been assigned to user $userId.", - ); + return $this; } $assignment = new Assignment($userId, $itemName, $createdAt ?? time()); diff --git a/tests/Common/ManagerLogicTestTrait.php b/tests/Common/ManagerLogicTestTrait.php index 3af69fa7..7cbd8861 100644 --- a/tests/Common/ManagerLogicTestTrait.php +++ b/tests/Common/ManagerLogicTestTrait.php @@ -509,23 +509,13 @@ public function testAssignUnknownItem(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('There is no item named "nonExistRole".'); - $manager->assign( - 'nonExistRole', - 'reader' - ); + $manager->assign(itemName: 'nonExistRole', userId: 'reader'); } public function testAssignAlreadyAssignedItem(): void { $manager = $this->createFilledManager(); - - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('"reader" role has already been assigned to user reader A.'); - - $manager->assign( - 'reader', - 'reader A' - ); + $this->assertSame($manager, $manager->assign(itemName: 'reader', userId: 'reader A')); } public function testAssignPermissionDirectlyWhenItIsDisabled(): void @@ -535,7 +525,7 @@ public function testAssignPermissionDirectlyWhenItIsDisabled(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Assigning permissions directly is disabled. Prefer assigning roles only.'); - $manager->assign('readPost', 'id7'); + $manager->assign(itemName: 'readPost', userId: 'id7'); } public function testAssignPermissionDirectlyWhenEnabled(): void @@ -1045,8 +1035,8 @@ public function testDataPersistency(): void ->addRole((new Role('role1'))->withCreatedAt(1_694_502_936)->withUpdatedAt(1_694_502_936)) ->addRole((new Role('role2'))->withCreatedAt(1_694_502_976)->withUpdatedAt(1_694_502_976)) ->addChild('role1', 'role2'); - $manager->assign('role1', 1); - $manager->assign('role2', 2); + $manager->assign(itemName: 'role1', userId: 1); + $manager->assign(itemName: 'role2', userId: 2); $this->assertEquals( [