I have an array that is actually a tree array:
array:2 [▼
0 => array:7 [▼
"id" => 36
"attribute_key" => "amount"
"attribute_value" => "Amount"
"input_type_id" => 3
"is_required" => 1
"parent_id" => null
]
1 => array:8 [▼
"id" => 37
"attribute_key" => "products"
"attribute_value" => "Products"
"input_type_id" => 7
"is_required" => 1
"parent_id" => null
"event" => null
"children" => array:2 [▼
0 => array:7 [▼
"id" => 38
"attribute_key" => "product_name"
"attribute_value" => "Product Name"
"input_type_id" => 1
"is_required" => 1
"parent_id" => 37
]
1 => array:7 [▼
"id" => 39
"attribute_key" => "price"
"attribute_value" => "Price"
"input_type_id" => 3
"is_required" => 1
"parent_id" => 37
]
]
]
]
and I would like to get output something like this:
[
'amount' => 'required',
'products.*.product_name' => 'required',
'products.*.price' => 'required|numeric',
]
My data is highly dynamic and I'd like to create validation rules for Laravel.
Here is what do I have:
class EventRules
{
protected $rules = [];
public function rules(array $attributes) : array
{
foreach ($attributes as $attribute) {
$this->addRules($attribute);
}
return $this->rules;
}
public function addRules($attribute) : void
{
if (isset($attribute['children'])) {
$this->rules($attribute['children']);
return;
}
$attributeKey = $attribute['attribute_key'];
$rule = '';
$rule .= $this->addRequiredRule($attribute);
$rule .= $this->addFieldTypeRule($attribute);
$this->rules[$attributeKey] = $rule;
}
protected function addRequiredRule($attribute) : string
{
$rule = '';
if ($attribute['is_required'] === 1) {
$rule .= 'required|';
}
// The rest will be here..
return $rule;
}
protected function addFieldTypeRule($attribute) : string
{
$rule = [
InputTypeEnum::STRING_TYPE => 'string',
InputTypeEnum::INTEGER_TYPE => 'integer',
InputTypeEnum::DECIMAL_TYPE => 'numeric',
InputTypeEnum::DATE_TYPE => 'date',
];
return $rule[$attribute['input_type_id']];
}
}
Anyway, I stuck with creating a rule key (with *). I am aware I need a recursion which is something I use, but still not sure how to handle the rest.
Thanks.