'required|integer|exists:models,id', 'parameters' => 'required|array', 'parameters.*' => 'required', 'product_data' => 'nullable|array', 'product_data.name' => 'nullable|string|max:200', 'product_data.code' => 'nullable|string|max:100|unique:products,code', 'product_data.description' => 'nullable|string|max:1000', 'product_data.category_id' => 'nullable|integer|exists:categories,id', 'product_data.memo' => 'nullable|string|max:500', ]; } /** * Get custom messages for validator errors. */ public function messages(): array { return [ 'model_id.required' => __('error.model_id_required'), 'model_id.exists' => __('error.model_not_found'), 'parameters.required' => __('error.parameters_required'), 'parameters.array' => __('error.parameters_must_be_array'), 'product_data.code.unique' => __('error.product_code_duplicate'), ]; } /** * Configure the validator instance. */ public function withValidator($validator): void { $validator->after(function ($validator) { $this->validateParameters($validator); $this->validateProductData($validator); }); } /** * 매개변수 검증 */ private function validateParameters($validator): void { if (!$this->input('model_id') || !$this->input('parameters')) { return; } try { $parameterService = new \App\Services\ModelParameterService(); $errors = $parameterService->validateParameterValues( $this->input('model_id'), $this->input('parameters') ); if (!empty($errors)) { foreach ($errors as $paramName => $paramErrors) { foreach ($paramErrors as $error) { $validator->errors()->add("parameters.{$paramName}", $error); } } } } catch (\Throwable $e) { $validator->errors()->add('parameters', __('error.parameter_validation_failed')); } } /** * 제품 데이터 검증 */ private function validateProductData($validator): void { $productData = $this->input('product_data', []); // 제품 코드 중복 검증 (수정 시 제외) if (!empty($productData['code'])) { $query = \Shared\Models\Products\Product::where('code', $productData['code']); if ($this->route('id')) { $query->where('id', '!=', $this->route('id')); } if ($query->exists()) { $validator->errors()->add('product_data.code', __('error.product_code_duplicate')); } } // 카테고리 존재 확인 if (!empty($productData['category_id'])) { $categoryExists = \Shared\Models\Products\Category::where('id', $productData['category_id']) ->where('is_active', true) ->exists(); if (!$categoryExists) { $validator->errors()->add('product_data.category_id', __('error.category_not_found')); } } } /** * Prepare the data for validation. */ protected function prepareForValidation(): void { // JSON 문자열인 경우 배열로 변환 if ($this->has('parameters') && is_string($this->input('parameters'))) { $this->merge([ 'parameters' => json_decode($this->input('parameters'), true) ?? [] ]); } if ($this->has('product_data') && is_string($this->input('product_data'))) { $this->merge([ 'product_data' => json_decode($this->input('product_data'), true) ?? [] ]); } } }