Skip to content

Commit

Permalink
Merge pull request #5 from ARCANEDEV/update-ability-class
Browse files Browse the repository at this point in the history
Allowing to get ability's method and class names
  • Loading branch information
arcanedev-maroc committed Sep 29, 2020
2 parents 01879ad + e985ef7 commit 3fbb806
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 2 deletions.
3 changes: 1 addition & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,7 @@
}
},
"scripts": {
"test": "phpunit",
"coverage": "phpunit --coverage-html build/coverage/html"
"test": "phpunit --testdox"
},
"extra": {
"branch-alias": {
Expand Down
32 changes: 32 additions & 0 deletions src/Ability.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,38 @@ public function method()
return $this->method;
}

/**
* Get the ability's method name.
*
* @return string|null
*/
public function methodName()
{
if ($this->isClosure())
return null;

return last(explode('@', $this->method()));
}

/**
* Get the ability's class name.
*
* @param bool $fqn
*
* @return string|null
*/
public function className(bool $fqn = true)
{
if ($this->isClosure())
return null;

$class = head(explode('@', $this->method()));

return $fqn
? $class
: class_basename($class);
}

/**
* Set the callback as method.
*
Expand Down
16 changes: 16 additions & 0 deletions src/Contracts/Ability.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ public function setKey(string $key);
*/
public function method();

/**
* Get the ability's method name.
*
* @return string|null
*/
public function methodName();

/**
* Get the ability's class name.
*
* @param bool $fqn
*
* @return string|null
*/
public function className(bool $fqn = true);

/**
* Set the callback as method.
*
Expand Down
19 changes: 19 additions & 0 deletions tests/AbilityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -163,4 +163,23 @@ public function it_can_convert_to_json(): void
static::assertJsonStringEqualsJsonString($expectedJson, json_encode($ability));
static::assertJsonStringEqualsJsonString($expectedJson, (string) $ability->toJson());
}

/** @test */
public function it_can_get_method_and_class_names_separately(): void
{
$ability = Ability::make('posts.list', 'Arcanedev\Package\Policies\PostsPolicy@index');

static::assertSame('index', $ability->methodName());
static::assertSame('Arcanedev\Package\Policies\PostsPolicy', $ability->className());
static::assertSame('PostsPolicy', $ability->className(false));
}

/** @test */
public function it_cannot_get_method_and_class_names_when_using_closure(): void
{
$ability = Ability::make('posts.list', function () {});

static::assertNull($ability->methodName());
static::assertNull($ability->className());
}
}

0 comments on commit 3fbb806

Please sign in to comment.