Skip to content

Commit

Permalink
feat: add CanOwn trait
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammad-Alavi committed May 2, 2022
1 parent 0e1ade2 commit c52588a
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions Traits/CanOwnTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace Apiato\Core\Traits;

use Apiato\Core\Exceptions\CoreInternalErrorException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Throwable;

trait CanOwnTrait
{
/**
* check if the model is the owner of the $ownable model
*
* @param Model $ownable
* @param null $foreignKeyName
* @param null $localKey
* @return bool
* @throws Throwable
*/
public function owns(Model $ownable, $foreignKeyName = null, $localKey = null): bool
{
$foreignKeyName = $foreignKeyName ?: $this->guessForeignKeyName();

$ownerKey = $ownable->$foreignKeyName;

throw_if(is_null($ownerKey), (new CoreInternalErrorException())->withErrors(['foreign_key' => 'No foreign key found.']));

return $ownerKey == ($localKey ?? $this->getKey());
}

private function guessForeignKeyName(): string
{
$className = Str::snake(class_basename($this));

return $className . '_id';
}
}

0 comments on commit c52588a

Please sign in to comment.