ArrayOf.php
2 months ago
ConnectionOf.php
2 months ago
Deprecated.php
2 months ago
Description.php
2 months ago
Experimental.php
4 weeks ago
HiddenFromMetadataQuery.php
4 weeks ago
Ignore.php
2 months ago
Internal.php
4 weeks ago
Metadata.php
4 weeks ago
Name.php
2 months ago
Parameter.php
2 months ago
ParameterDescription.php
2 months ago
PublicAccess.php
4 weeks ago
RequiredCapability.php
4 weeks ago
ReturnType.php
2 months ago
ScalarType.php
2 months ago
Unroll.php
2 months ago
RequiredCapability.php
52 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Api\Attributes; |
| 6 | |
| 7 | use Attribute; |
| 8 | use Automattic\WooCommerce\Api\Infrastructure\Principal; |
| 9 | |
| 10 | /** |
| 11 | * Declares a WordPress capability required to execute a query or mutation, |
| 12 | * or to read an output field, or to set an input field on a mutation. |
| 13 | * |
| 14 | * This attribute is repeatable: apply it multiple times to require several |
| 15 | * capabilities (logical AND). |
| 16 | * |
| 17 | * Mutually exclusive with #[PublicAccess] at the class level. At the field |
| 18 | * level a `#[PublicAccess]` placement on the same property is a build |
| 19 | * warning and is treated as a no-op. |
| 20 | * |
| 21 | * Targets: class (query/mutation/output type) and property (output field, |
| 22 | * input field, or trait-declared property). Trait-declared properties |
| 23 | * carry the attribute onto every implementing class through PHP's |
| 24 | * reflection. |
| 25 | */ |
| 26 | #[Attribute( Attribute::IS_REPEATABLE | Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY )] |
| 27 | final class RequiredCapability { |
| 28 | /** |
| 29 | * Constructor. |
| 30 | * |
| 31 | * @param string $capability A WordPress capability slug |
| 32 | * (e.g. 'manage_woocommerce'). |
| 33 | */ |
| 34 | public function __construct( |
| 35 | public readonly string $capability, |
| 36 | ) { |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Decide whether the given principal holds the required capability. |
| 41 | * |
| 42 | * Reads the WordPress user from the principal wrapper and delegates to |
| 43 | * {@see \user_can()}. Anonymous principals (the WP user has `ID === 0`) |
| 44 | * never hold any capability, so the check returns false naturally. |
| 45 | * |
| 46 | * @param Principal $principal The resolved request principal. |
| 47 | */ |
| 48 | public function authorize( Principal $principal ): bool { |
| 49 | return user_can( $principal->user, $this->capability ); |
| 50 | } |
| 51 | } |
| 52 |