From 160c114801668e3af76567b2a660848e6772a26b Mon Sep 17 00:00:00 2001 From: Joseph Silber Date: Sun, 28 Jan 2018 13:07:26 -0500 Subject: [PATCH] Automatically add a role title when missing --- src/Database/Concerns/IsRole.php | 5 +++ src/Database/Titles/RoleTitle.php | 13 +++++++ src/Database/Titles/Title.php | 47 ++++++++++++++++++++++++++ tests/AutoTitlesTest.php | 56 +++++++++++++++++++++++++++++++ 4 files changed, 121 insertions(+) create mode 100644 src/Database/Titles/RoleTitle.php create mode 100644 src/Database/Titles/Title.php create mode 100644 tests/AutoTitlesTest.php diff --git a/src/Database/Concerns/IsRole.php b/src/Database/Concerns/IsRole.php index a69f5ea..60f75c9 100644 --- a/src/Database/Concerns/IsRole.php +++ b/src/Database/Concerns/IsRole.php @@ -4,6 +4,7 @@ use Silber\Bouncer\Helpers; use Silber\Bouncer\Database\Models; +use Silber\Bouncer\Database\Titles\RoleTitle; use Silber\Bouncer\Database\Scope\BaseTenantScope; use Silber\Bouncer\Database\Queries\Roles as RolesQuery; @@ -30,6 +31,10 @@ public static function bootIsRole() static::creating(function ($role) { Models::scope()->applyToModel($role); + + if (is_null($role->title)) { + $role->title = new RoleTitle($role); + } }); } diff --git a/src/Database/Titles/RoleTitle.php b/src/Database/Titles/RoleTitle.php new file mode 100644 index 0000000..052b1db --- /dev/null +++ b/src/Database/Titles/RoleTitle.php @@ -0,0 +1,13 @@ +title = $this->humanize($role->name); + } +} diff --git a/src/Database/Titles/Title.php b/src/Database/Titles/Title.php new file mode 100644 index 0000000..69f4499 --- /dev/null +++ b/src/Database/Titles/Title.php @@ -0,0 +1,47 @@ +title; + } +} diff --git a/tests/AutoTitlesTest.php b/tests/AutoTitlesTest.php new file mode 100644 index 0000000..6d7d178 --- /dev/null +++ b/tests/AutoTitlesTest.php @@ -0,0 +1,56 @@ + 'admin', 'title' => 'Something Else']); + + $this->assertEquals('Something Else', $role->title); + } + + public function test_role_title_is_capitalized() + { + $role = Role::create(['name' => 'admin']); + + $this->assertEquals('Admin', $role->title); + } + + public function test_role_title_with_spaces() + { + $role = Role::create(['name' => 'site admin']); + + $this->assertEquals('Site admin', $role->title); + } + + public function test_role_title_with_dashes() + { + $role = Role::create(['name' => 'site-admin']); + + $this->assertEquals('Site admin', $role->title); + } + + public function test_role_title_with_underscores() + { + $role = Role::create(['name' => 'site_admin']); + + $this->assertEquals('Site admin', $role->title); + } + + public function test_role_title_with_camel_casing() + { + $role = Role::create(['name' => 'siteAdmin']); + + $this->assertEquals('Site admin', $role->title); + } + + public function test_role_title_with_studly_casing() + { + $role = Role::create(['name' => 'SiteAdmin']); + + $this->assertEquals('Site admin', $role->title); + } +}