Skip to content

Commit

Permalink
ENH Add permission methods based on owner
Browse files Browse the repository at this point in the history
  • Loading branch information
GuySartorelli committed Dec 5, 2023
1 parent 9debde6 commit 0be87ca
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/Models/Link.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down

0 comments on commit 0be87ca

Please sign in to comment.