src/Authorizer/functions.php source

1 <?php
2
3 namespace mini;
4
5 use mini\Authorizer\Ability;
6 use mini\Authorizer\Authorization;
7
8 Mini::$mini->addService(Authorization::class, Lifetime::Singleton, fn() => new Authorization());
9
10 /**
11 * Check authorization
12 *
13 * Checks if the current user can perform an ability on an entity.
14 * Returns false if no handler allows the action.
15 *
16 * ## Usage
17 *
18 * ```php
19 * // Collection-level
20 * can(Ability::List, User::class);
21 * can(Ability::Create, Post::class);
22 *
23 * // Instance-level
24 * can(Ability::Read, $user);
25 * can(Ability::Update, $post);
26 * can(Ability::Delete, $comment);
27 *
28 * // Field-level
29 * can(Ability::Update, $user, 'role');
30 * can(Ability::Read, $employee, 'salary');
31 * ```
32 *
33 * @param Ability|string $ability The ability to check
34 * @param object|string $entity Entity instance or class name
35 * @param string|null $field Optional field name for field-level checks
36 * @return bool True if allowed, false if denied
37 * @throws \InvalidArgumentException If string ability is not registered
38 */
39 function can(Ability|string $ability, object|string $entity, ?string $field = null): bool
40 {
41 return Mini::$mini->get(Authorization::class)->can($ability, $entity, $field);
42 }
43