PermissionsChecker.php
49 lines
| 1 | <?php |
| 2 | /** |
| 3 | * WP Infrastructure layer implementation of the permissions service. |
| 4 | */ |
| 5 | |
| 6 | namespace AmeliaBooking\Infrastructure\WP\PermissionsService; |
| 7 | |
| 8 | use AmeliaBooking\Domain\Entity\User\AbstractUser; |
| 9 | use AmeliaBooking\Domain\Entity\User\Admin; |
| 10 | use AmeliaBooking\Domain\Services\Permissions\PermissionsCheckerInterface; |
| 11 | |
| 12 | /** |
| 13 | * Class PermissionsChecker |
| 14 | * |
| 15 | * @package AmeliaBooking\Infrastructure\WP\PermissionsService |
| 16 | */ |
| 17 | class PermissionsChecker implements PermissionsCheckerInterface |
| 18 | { |
| 19 | |
| 20 | /** |
| 21 | * @param AbstractUser $user |
| 22 | * @param string $object |
| 23 | * @param string $permission |
| 24 | * |
| 25 | * @return bool |
| 26 | */ |
| 27 | public function checkPermissions($user, $object, $permission) |
| 28 | { |
| 29 | // Admin can do all |
| 30 | if ($user instanceof Admin) { |
| 31 | return true; |
| 32 | } |
| 33 | |
| 34 | // Get the WP role name of the user, rollback to customer by default |
| 35 | $wpRoleName = $user !== null ? 'wpamelia-' . $user->getType() : 'wpamelia-customer'; |
| 36 | // Get the wp name of capability we are looking for. |
| 37 | $wpCapability = "amelia_{$permission}_{$object}"; |
| 38 | |
| 39 | if ($user !== null && $user->getExternalId() !== null) { |
| 40 | return user_can($user->getExternalId()->getValue(), $wpCapability); |
| 41 | } |
| 42 | |
| 43 | // If user is guest check does it have capability |
| 44 | $wpRole = get_role($wpRoleName); |
| 45 | return $wpRole !== null && isset($wpRole->capabilities[$wpCapability]) ? |
| 46 | (bool)$wpRole->capabilities[$wpCapability] : false; |
| 47 | } |
| 48 | } |
| 49 |