Skip to content

Commit 8fbb0f7

Browse files
committed
add method removeRelation which remove a dynamic relation
1 parent 7cd9b1b commit 8fbb0f7

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/DynamicRelations.php

+10
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Imanghafoori\Relativity;
44

55
use Illuminate\Support\Str;
6+
use Imanghafoori\Relativity\Exceptions;
67

78
trait DynamicRelations
89
{
@@ -20,6 +21,15 @@ public function hasDynamicRelation(string $relation)
2021
return isset(static::$dynamicRelations[$relation]);
2122
}
2223

24+
public static function removeRelation(string $relationName)
25+
{
26+
if (!isset(static::$dynamicRelations[$relationName])) {
27+
throw new Exceptions\UndefinedDynamicRelationException($relationName);
28+
}
29+
30+
unset(static::$dynamicRelations[$relationName]);
31+
}
32+
2333
public static function defineRelation($relationType, $relationName, $data, $constraints)
2434
{
2535
$method = function () use ($relationType, $data, $constraints) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
namespace Imanghafoori\Relativity\Exceptions;
4+
5+
use Exception;
6+
7+
class UndefinedDynamicRelationException extends Exception
8+
{
9+
public function __construct(string $relation)
10+
{
11+
$this->message = sprintf("Undefined dynamic relation '%s' called", $relation);
12+
}
13+
}

tests/BasicTest.php

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
namespace Imanghafoori\Relativity\Tests;
4+
5+
use Imanghafoori\Relativity\Tests\RelativeModels\User;
6+
use Imanghafoori\Relativity\Tests\RelativeModels\Comment;
7+
use Imanghafoori\Relativity\Exceptions\UndefinedDynamicRelationException;
8+
9+
class BasicTest extends TestCase
10+
{
11+
public function test_remove_relation()
12+
{
13+
User::has_many('comments', Comment::class);
14+
$this->assertTrue((new User)->hasDynamicRelation('comments'));
15+
$this->assertEquals(1, count((new User)->getDynamicRelations()));
16+
17+
User::removeRelation('comments');
18+
$this->assertFalse((new User)->hasDynamicRelation('comments'));
19+
$this->assertEquals(0, count((new User)->getDynamicRelations()));
20+
}
21+
22+
public function test_exception_undefined_relation()
23+
{
24+
$this->expectException(UndefinedDynamicRelationException::class);
25+
User::removeRelation('comments');
26+
}
27+
}

0 commit comments

Comments
 (0)