90 lines
3.2 KiB
PHP
90 lines
3.2 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Requests;
|
|
|
|
use App\Enums\CrudAction;
|
|
use App\Enums\CrudType;
|
|
use App\Exceptions\CrudException;
|
|
use App\Http\Controllers\CrudController;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Foundation\Http\FormRequest;
|
|
|
|
class CrudRequest extends FormRequest
|
|
{
|
|
|
|
/** @var array */
|
|
protected $rules = [];
|
|
|
|
/**
|
|
* Get rules for a specific action
|
|
*
|
|
* @param CrudAction $action
|
|
* @return array
|
|
*/
|
|
public function getRulesForAction(CrudAction $action): array
|
|
{
|
|
$model = $this->getCurrentModel();
|
|
$props = $this->getCurrentModel()::getEditableProperties();
|
|
$propsRules = [];
|
|
foreach ($this->getCurrentModel()::getRules() as $k => $rules) {
|
|
$propsRules[$k] = [];
|
|
$propIsAllowedOnUpdateAction = in_array($action, $props[$k]['actions']);
|
|
foreach ($rules as $rule) {
|
|
// dont copy required if prop is not allowed on update
|
|
if (!$propIsAllowedOnUpdateAction and is_string($rule) and $rule == 'required') {
|
|
continue;
|
|
}
|
|
if (!in_array($rule, $propsRules[$k])) {
|
|
$propsRules[$k][] = $rule;
|
|
}
|
|
// handle password
|
|
if (
|
|
$props[$k]['type']->equals(CrudType::password()) and
|
|
!$this->{$k} or (is_string($this->{$k}) and !\strlen($this->{$k}))
|
|
) {
|
|
$this->offsetUnset($k);
|
|
}
|
|
// handle boolean
|
|
if ($props[$k]['type']->equals(CrudType::boolean())) {
|
|
$this->merge([$k => $this->{$k} ? 1 : 0]);
|
|
}
|
|
// handle image
|
|
if ($props[$k]['type']->equals(CrudType::image())) {
|
|
$tableName = Str::singular((new $model())->getTable());
|
|
if ($this->{$tableName}) {
|
|
$i = array_search('required', $propsRules[$k]);
|
|
unset($propsRules[$k][$i]);
|
|
}
|
|
}
|
|
// handle belongsToMany
|
|
if ($props[$k]['type']->equals(CrudType::belongsToMany())) {
|
|
$propsRules["$k.*"][0] = 'exists:' .
|
|
(new $props[$k]['belongsToMany']())->getTable() . ',id';
|
|
if (!isset($this->{$k})) {
|
|
$this->merge([$k => []]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return $propsRules;
|
|
}
|
|
/**
|
|
* Returns the first parameter that is a crud model
|
|
*
|
|
* @return string \Illuminate\Database\Eloquent\Model class name
|
|
* @throws \App\Exceptions\CrudException if the request does not have a crud model parameter
|
|
*/
|
|
protected function getCurrentModel(): string
|
|
{
|
|
if (
|
|
!is_object($this->route()->controller) or
|
|
!$this->route()->controller instanceof CrudController
|
|
) {
|
|
throw new CrudException(sprintf(
|
|
'Request `%s` needs to be bound on route that use a CrudController',
|
|
get_class($this)
|
|
));
|
|
}
|
|
return $this->route()->controller->getModelClass();
|
|
}
|
|
}
|