From fb4b52d64918bec59eaacb624b7075e2ebd90bb8 Mon Sep 17 00:00:00 2001 From: klsoft-web Date: Mon, 19 Jan 2026 09:18:45 +0300 Subject: [PATCH] The 'Using rules' section is refactored --- src/guide/security/authorization.md | 36 +++++++++++++---------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/guide/security/authorization.md b/src/guide/security/authorization.md index 853216ff..2f994b49 100644 --- a/src/guide/security/authorization.md +++ b/src/guide/security/authorization.md @@ -424,22 +424,18 @@ Let's fix it. First, you need a rule to verify that the user is the post author: namespace App\User\Rbac; use Yiisoft\Rbac\Item; -use \Yiisoft\Rbac\Rule; +use Yiisoft\Rbac\RuleContext; +use Yiisoft\Rbac\RuleInterface; /** * Checks if the authorID matches user passed via params. */ -final readonly class AuthorRule extends Rule +final readonly class AuthorRule implements RuleInterface { - private const NAME = 'isAuthor'; - - public function __construct() { - parent::__construct(self::NAME); - } - - public function execute(string $userId, Item $item, array $parameters = []): bool + public function execute(?string $userId, Item $item, RuleContext $context): bool { - return isset($params['post']) ? $params['post']->getAuthorId() == $userId : false; + $post = $context->getParameterValue('post'); + return $post !== null && $post->getAuthorId() == $userId; } } ``` @@ -447,23 +443,23 @@ final readonly class AuthorRule extends Rule The rule checks if user created the `post`. Create a special permission `updateOwnPost` in the command you've used before: ```php -/** @var \Yiisoft\Rbac\ManagerInterface $auth */ - -// add the rule -$rule = new AuthorRule(); -$auth->add($rule); +use Yiisoft\Rbac\Permission; +use Yiisoft\Rbac\ManagerInterface; // add the "updateOwnPost" permission and associate the rule with it. -$updateOwnPost = (new \Yiisoft\Rbac\Permission('updateOwnPost')) +$updateOwnPost = (new Permission('updateOwnPost')) ->withDescription('Update own post') - ->withRuleName($rule->getName()); -$auth->add($updateOwnPost); + ->withRuleName(AuthorRule::class); +$this->manager->addPermission($updateOwnPost); // "updateOwnPost" will be used from "updatePost" -$auth->addChild($updateOwnPost, $updatePost); +$this->manager->addChild($updateOwnPost->getName(), $updatePost->getName()); // allow "author" to update their own posts -$auth->addChild($author, $updateOwnPost); +$this->manager->addChild($authorRole->getName(), $updateOwnPost->getName()); + +// Remove this line since we don't want the AuthorRule to be applied to the 'admin' role +$this->manager->addChild('admin', 'author'); ``` Now you've got the following hierarchy: