clqms-be/app/Controllers/Specimen/SpecimenCollectionController.php
mahdahar 425595f5c0 feat: Implement custom ResponseTrait with automatic empty string to null conversion
- Create App\Traits\ResponseTrait that wraps CodeIgniter\API\ResponseTrait
- Add json_helper with convert_empty_strings_to_null() and prepare_json_response() functions
- Replace all imports of CodeIgniter\API\ResponseTrait with App\Traits\ResponseTrait across all controllers
- Add 'json' helper to BaseController helpers array
- Ensure consistent API response formatting across the application
2026-02-18 10:15:47 +07:00

81 lines
2.8 KiB
PHP

<?php
namespace App\Controllers\Specimen;
use App\Traits\ResponseTrait;
use App\Controllers\BaseController;
use App\Libraries\ValueSet;
use App\Models\Specimen\SpecimenCollectionModel;
class SpecimenCollectionController extends BaseController {
use ResponseTrait;
protected $db;
protected $model;
protected $rules;
public function __construct() {
$this->db = \Config\Database::connect();
$this->model = new SpecimenCollectionModel();
$this->rules = [];
}
public function index() {
try {
$rows = $this->model->findAll();
$rows = ValueSet::transformLabels($rows, [
'CollectionMethod' => 'collection_method',
'Additive' => 'additive',
'SpecimenRole' => 'specimen_role',
]);
return $this->respond([ 'status' => 'success', 'message'=> "data fetched successfully", 'data' => $rows ], 200);
} catch (\Exception $e) {
return $this->failServerError('Exception : '.$e->getMessage());
}
}
public function show($id) {
try {
$row = $this->model->where('SpcColID', $id)->first();
if (empty($row)) {
return $this->respond([ 'status' => 'success', 'message'=> "data not found", 'data' => null ], 200);
}
$row = ValueSet::transformLabels([$row], [
'CollectionMethod' => 'collection_method',
'Additive' => 'additive',
'SpecimenRole' => 'specimen_role',
])[0];
return $this->respond([ 'status' => 'success', 'message'=> "data fetched successfully", 'data' => $row ], 200);
} catch (\Exception $e) {
return $this->failServerError('Exception : '.$e->getMessage());
}
}
public function create() {
$input = $this->request->getJSON(true);
if (!$this->validateData($input, $this->rules)) { return $this->failValidationErrors($this->validator->getErrors()); }
try {
$id = $this->model->insert($input);
return $this->respondCreated([ 'status' => 'success', 'message' => "data $id created successfully" ]);
} catch (\Exception $e) {
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
public function update() {
$input = $this->request->getJSON(true);
if (!$this->validateData($input, $this->rules)) { return $this->failValidationErrors($this->validator->getErrors()); }
try {
$id = $this->model->update($input['SpcColID'], $input);
return $this->respondCreated([ 'status' => 'success', 'message' => "data $id updated successfully" ]);
} catch (\Exception $e) {
return $this->failServerError('Something went wrong: ' . $e->getMessage());
}
}
}