| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Http\Requests; |
| 4 |
|
| 5 |
use FluentCart\App\Models\AttributeGroup; |
| 6 |
use FluentCart\Framework\Foundation\RequestGuard; |
| 7 |
use FluentCart\Framework\Support\Arr; |
| 8 |
|
| 9 |
class AttrTermUpdateRequest extends RequestGuard |
| 10 |
{ |
| 11 |
public function rules() |
| 12 |
{ |
| 13 |
$rules = [ |
| 14 |
'title' => 'required|sanitizeText|maxLength:50', |
| 15 |
'settings' => 'nullable', |
| 16 |
]; |
| 17 |
|
| 18 |
// Same type-aware guards as create — keep the term's settings |
| 19 |
// consistent with the parent group's type. |
| 20 |
$groupType = $this->getGroupType(); |
| 21 |
if ($groupType === 'color') { |
| 22 |
// Same `sanitize_hex_color` + `required` pairing as the bulk |
| 23 |
// endpoint — invalid hex collapses to empty, which the required |
| 24 |
// rule then catches with the standard user-facing message. |
| 25 |
$rules['settings.color'] = ['required']; |
| 26 |
} elseif ($groupType === 'image') { |
| 27 |
$rules['settings.image'] = ['required', 'url']; |
| 28 |
} |
| 29 |
|
| 30 |
return $rules; |
| 31 |
} |
| 32 |
|
| 33 |
public function messages() |
| 34 |
{ |
| 35 |
return [ |
| 36 |
'title.required' => esc_html__('Title is required.', 'fluent-cart'), |
| 37 |
'settings.color.required' => esc_html__('A color is required for color-type terms.', 'fluent-cart'), |
| 38 |
'settings.image.required' => esc_html__('An image is required for image-type terms.', 'fluent-cart'), |
| 39 |
'settings.image.url' => esc_html__('Image must be a valid URL.', 'fluent-cart'), |
| 40 |
]; |
| 41 |
} |
| 42 |
|
| 43 |
public function sanitize() |
| 44 |
{ |
| 45 |
return [ |
| 46 |
'title' => 'sanitize_text_field', |
| 47 |
// Hex-only — sanitize_hex_color() returns null on bad input, |
| 48 |
// which trips the required rule for the user-facing error. |
| 49 |
'settings.color' => 'sanitize_hex_color', |
| 50 |
'settings.image' => 'esc_url_raw', |
| 51 |
]; |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Look up the parent attribute group's type ('color' | 'image' | 'options') |
| 56 |
* from the route param {group_id} so settings can be required to match. |
| 57 |
* |
| 58 |
* @return string|null |
| 59 |
*/ |
| 60 |
protected function getGroupType() |
| 61 |
{ |
| 62 |
$groupId = (int) $this->get('group_id', 0); |
| 63 |
if ($groupId <= 0) { |
| 64 |
return null; |
| 65 |
} |
| 66 |
$group = AttributeGroup::query()->find($groupId); |
| 67 |
if (!$group) { |
| 68 |
return null; |
| 69 |
} |
| 70 |
return Arr::get($group->settings ?: [], 'type'); |
| 71 |
} |
| 72 |
} |
| 73 |
|