Created
April 19, 2022 13:03
-
-
Save inxilpro/bab01ecb22a6019c850a8f51c0820e6a to your computer and use it in GitHub Desktop.
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
<?php | |
use Illuminate\Support\Facades\Gate; | |
use RuntimeException; | |
/** | |
* @template M | |
*/ | |
trait HasRouteBoundModel | |
{ | |
/** | |
* @param string $parameter | |
* @param class-string<M> $model_class | |
* @param bool $allow_null | |
* @return M|null | |
*/ | |
protected function getRouteBoundModel(string $parameter, string $model_class, bool $allow_null = false) | |
{ | |
$bound = $this->route($parameter); | |
if (null === $bound && $allow_null) { | |
return null; | |
} | |
if (is_a($bound, $model_class)) { | |
return $bound; | |
} | |
$actual_type = get_debug_type($bound); | |
throw new RuntimeException("Expected '{$parameter}' to be bound to '{$model_class}' but got '{$actual_type}'"); | |
} | |
/** | |
* @param string $parameter | |
* @param class-string<M> $model_class | |
* @return M|null | |
*/ | |
protected function getOptionalRouteBoundModel(string $parameter, string $model_class) | |
{ | |
return $this->getRouteBoundModel($parameter, $model_class, true); | |
} | |
/** | |
* @param string $parameter | |
* @param class-string<M> $model_class | |
* @return bool | |
*/ | |
protected function authorizeRouteBoundModel(string $parameter, string $model_class): bool | |
{ | |
return $this->isMethod('PUT') || $this->isMethod('PATCH') | |
? Gate::allows('update', $this->getRouteBoundModel($parameter, $model_class)) | |
: Gate::allows('create', $model_class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment