-
-
Notifications
You must be signed in to change notification settings - Fork 82
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0e1ade2
commit c52588a
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | ||
} | ||
} |