Skip to content

Commit

Permalink
fix(directive): Fix condition when passing multiple roles to @role (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Log1x committed Jul 30, 2023
2 parents adf2dde + 0f4120b commit 5ecc337
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
7 changes: 5 additions & 2 deletions src/Directives/WordPress.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Log1x\SageDirectives\Directives;

use Log1x\SageDirectives\Util;
use Illuminate\Support\Str;

return [

Expand Down Expand Up @@ -482,12 +483,14 @@
$condition = [];

foreach ($expression as $value) {
$condition[] = "&& in_array(strtolower({$value}), (array) wp_get_current_user()->roles)";
$condition[] = "in_array(strtolower({$value}), (array) wp_get_current_user()->roles) ||";
}

$conditions = implode(' ', $condition);

return "<?php if (is_user_logged_in() {$conditions}) : ?>"; // phpcs:ignore
$conditions = Str::beforeLast($conditions, ' ||');

return "<?php if (is_user_logged_in() && ({$conditions})) : ?>";
},

'endrole' => function () {
Expand Down
4 changes: 2 additions & 2 deletions tests/Unit/WordPressTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -594,15 +594,15 @@

$compiled = $this->compile($directive);

expect($compiled)->toBe("<?php if (is_user_logged_in() && in_array(strtolower('editor'), (array) wp_get_current_user()->roles)) : ?>");
expect($compiled)->toBe("<?php if (is_user_logged_in() && (in_array(strtolower('editor'), (array) wp_get_current_user()->roles))) : ?>");
});

it('compiles correctly with multiple roles', function () {
$directive = "@role('editor', 'author', 'contributor')";

$compiled = $this->compile($directive);

expect($compiled)->toBe("<?php if (is_user_logged_in() && in_array(strtolower('editor'), (array) wp_get_current_user()->roles) && in_array(strtolower('author'), (array) wp_get_current_user()->roles) && in_array(strtolower('contributor'), (array) wp_get_current_user()->roles)) : ?>");
expect($compiled)->toBe("<?php if (is_user_logged_in() && (in_array(strtolower('editor'), (array) wp_get_current_user()->roles) || in_array(strtolower('author'), (array) wp_get_current_user()->roles) || in_array(strtolower('contributor'), (array) wp_get_current_user()->roles))) : ?>");
});
});

Expand Down

0 comments on commit 5ecc337

Please sign in to comment.