From 0be87ca89b80eddafab7b7f89394fcbd9e5bb4d8 Mon Sep 17 00:00:00 2001 From: Guy Sartorelli Date: Wed, 6 Dec 2023 11:04:49 +1300 Subject: [PATCH] ENH Add permission methods based on owner --- src/Models/Link.php | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/Models/Link.php b/src/Models/Link.php index 78e9cb55..63df7e1e 100644 --- a/src/Models/Link.php +++ b/src/Models/Link.php @@ -270,6 +270,57 @@ public function getURL(): string return ''; } + public function canView($member = null) + { + return $this->canPerformAction(__FUNCTION__, $member); + } + + public function canEdit($member = null) + { + return $this->canPerformAction(__FUNCTION__, $member); + } + + public function canDelete($member = null) + { + return $this->canPerformAction(__FUNCTION__, $member); + } + + public function canCreate($member = null, $context = []) + { + return $this->canPerformAction(__FUNCTION__, $member); + } + + public function can($perm, $member = null, $context = []) + { + $check = ucfirst(strtolower($perm)); + return match ($check) { + 'View', 'Create', 'Edit', 'Delete' => $this->{"can$check"}($member, $context), + default => parent::can($perm, $member, $context) + }; + } + + private function canPerformAction(string $canMethod, $member, $context = []) + { + // Allow extensions to override permission checks + $results = $this->extendedCan($canMethod, $member, $context); + if (isset($results)) { + return $results; + } + + // If we have an owner, rely on it to tell us what we can and can't do + $owner = $this->Owner(); + if ($owner && $owner->exists()) { + // Can delete or create links if you can edit its owner. + if ($canMethod === 'canCreate' || $canMethod === 'canDelete') { + $canMethod = 'canEdit'; + } + return $owner->$canMethod($member, $context); + } + + // Default to DataObject's permission checks + return parent::$canMethod($member, $context); + } + /** * Get all link types except the generic one *