| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Http\Requests; |
| 4 |
|
| 5 |
use FluentCart\App\Http\Rules\MaxLengthRule; |
| 6 |
use FluentCart\Framework\Foundation\RequestGuard; |
| 7 |
|
| 8 |
class GroupBulkUpdateVariantRequest extends RequestGuard |
| 9 |
{ |
| 10 |
const MAX_VARIANTS_PER_REQUEST = 500; |
| 11 |
const SKU_MAX_LENGTH = 30; |
| 12 |
|
| 13 |
public function rules() |
| 14 |
{ |
| 15 |
$variantIds = $this->get('variant_ids', []); |
| 16 |
if (is_array($variantIds)) { |
| 17 |
$variantIds = array_values(array_filter(array_map('absint', $variantIds))); |
| 18 |
} |
| 19 |
|
| 20 |
// maxLength is a Validator::extend()-registered custom rule, whose |
| 21 |
// dispatcher (Validator::__call()) always uses the rule callback's |
| 22 |
// own return value and never consults messages() — so it's passed |
| 23 |
// as a closure carrying its own message instead of "maxLength:30". |
| 24 |
$skuRules = [ |
| 25 |
'nullable', |
| 26 |
'sanitizeText', |
| 27 |
'maxLength' => MaxLengthRule::withMessage( |
| 28 |
self::SKU_MAX_LENGTH, |
| 29 |
esc_html__('SKU may not be greater than 30 characters.', 'fluent-cart') |
| 30 |
), |
| 31 |
]; |
| 32 |
|
| 33 |
if (is_array($variantIds) && count($variantIds) === 1) { |
| 34 |
$excludeId = absint($variantIds[0]); |
| 35 |
$skuRules[] = 'unique:fct_product_variations,sku,' . $excludeId; |
| 36 |
} |
| 37 |
|
| 38 |
return [ |
| 39 |
'variant_ids' => 'required|array', |
| 40 |
'sku' => $skuRules, |
| 41 |
]; |
| 42 |
} |
| 43 |
|
| 44 |
public function messages() |
| 45 |
{ |
| 46 |
return [ |
| 47 |
'variant_ids.required' => esc_html__('At least one variant ID is required.', 'fluent-cart'), |
| 48 |
'variant_ids.array' => esc_html__('variant_ids must be an array.', 'fluent-cart'), |
| 49 |
'sku.unique' => esc_html__('The SKU must be unique.', 'fluent-cart'), |
| 50 |
]; |
| 51 |
} |
| 52 |
|
| 53 |
public function sanitize() |
| 54 |
{ |
| 55 |
return [ |
| 56 |
'variant_ids' => function ($value) { |
| 57 |
if (!is_array($value)) { |
| 58 |
return []; |
| 59 |
} |
| 60 |
return array_slice( |
| 61 |
array_values(array_filter(array_map('absint', $value))), |
| 62 |
0, |
| 63 |
self::MAX_VARIANTS_PER_REQUEST |
| 64 |
); |
| 65 |
}, |
| 66 |
'sku' => function ($value) { |
| 67 |
return ($value !== null && $value !== '') ? sanitize_text_field($value) : null; |
| 68 |
}, |
| 69 |
]; |
| 70 |
} |
| 71 |
} |
| 72 |
|