core icon indicating copy to clipboard operation
core copied to clipboard

Expressions on security parameter of operations

Open aurimasrim opened this issue 2 years ago • 0 comments

Description

security property of operations attributes only allows string. In our project, we want to make this part more statically typed but it's not possible atm. In a lot of parts of Symfony, you can provide either string or Expression object for the expressions. Some examples:

  • https://github.com/symfony/symfony/blob/7.1/src/Symfony/Component/Security/Http/Attribute/IsGranted.php#L34
  • https://github.com/symfony/symfony/blob/7.0/src/Symfony/Component/Validator/Constraints/Expression.php#L38
  • https://github.com/symfony/symfony/blob/7.0/src/Symfony/Component/Validator/Constraints/When.php#L26

I think it would make sense to allow it in api-platform attributes as well. To not couple it with Symfony, Stringable could be used since Expression implements Stringable.

No BC break since it would be widening the type of constructor parameter.

If you approve this change, I could provide the implementation.

Example

Implementation:

final class Get extends HttpOperation
{
    public function __construct(
        //...
        string|\Stringable|null $security = null,
        string $securityMessage = null,
        string|\Stringable|null $securityPostDenormalize = null,
        string $securityPostDenormalizeMessage = null,
        string|\Stringable|null $securityPostValidation = null,
        string $securityPostValidationMessage = null,
        //...
    ) {
        //...
    }
}
abstract class Operation
{
    public function getSecurity(): ?string
    {
        return $this->security !== null ? (string)$this->security : null;
    }
}

Usage example:

#[\Attribute]
class IsGranted extends Expression
{
    public function __construct(RoleEnum $role)
    {
        parent::__construct(\sprintf("is_granted('%s', object)", $role->value));
    }
}
#[ApiResource(
    operations: [
        new Get(
            security: new IsGranted(RoleEnum::ROLE_ADMIN),
        ),
    ],
)]
class SomeResource
{}

aurimasrim avatar Jan 08 '24 10:01 aurimasrim