2026-02-18 10:15:47 +07:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Traits;
|
|
|
|
|
|
|
|
|
|
use CodeIgniter\API\ResponseTrait as BaseResponseTrait;
|
|
|
|
|
use CodeIgniter\HTTP\ResponseInterface;
|
|
|
|
|
|
|
|
|
|
trait ResponseTrait
|
|
|
|
|
{
|
|
|
|
|
use BaseResponseTrait {
|
|
|
|
|
respond as baseRespond;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Send a response with automatic conversion of empty strings to null
|
|
|
|
|
*
|
|
|
|
|
* @param mixed $data
|
|
|
|
|
* @param int $status
|
|
|
|
|
* @param string $message
|
|
|
|
|
* @return ResponseInterface
|
|
|
|
|
*/
|
|
|
|
|
public function respond($data = null, int $status = 200, string $message = '')
|
|
|
|
|
{
|
|
|
|
|
// Convert empty strings to null in the data
|
|
|
|
|
if ($data !== null && (is_array($data) || is_object($data))) {
|
2026-02-18 11:07:00 +07:00
|
|
|
$data = $this->convertEmptyStringsToNull($data);
|
2026-02-18 10:15:47 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $this->baseRespond($data, $status, $message);
|
|
|
|
|
}
|
2026-02-18 11:07:00 +07:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Recursively convert empty strings to null in arrays or objects
|
|
|
|
|
*
|
|
|
|
|
* @param mixed $data The data to process (array, object, or scalar)
|
|
|
|
|
* @return mixed The processed data with empty strings converted to null
|
|
|
|
|
*/
|
|
|
|
|
private function convertEmptyStringsToNull($data)
|
|
|
|
|
{
|
|
|
|
|
if (is_array($data)) {
|
|
|
|
|
foreach ($data as $key => $value) {
|
|
|
|
|
if (is_array($value)) {
|
|
|
|
|
$data[$key] = $this->convertEmptyStringsToNull($value);
|
|
|
|
|
} elseif (is_object($value)) {
|
|
|
|
|
$data[$key] = $this->convertEmptyStringsToNull($value);
|
|
|
|
|
} elseif ($value === '') {
|
|
|
|
|
$data[$key] = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
} elseif (is_object($data)) {
|
|
|
|
|
foreach ($data as $key => $value) {
|
|
|
|
|
if (is_array($value)) {
|
|
|
|
|
$data->$key = $this->convertEmptyStringsToNull($value);
|
|
|
|
|
} elseif (is_object($value)) {
|
|
|
|
|
$data->$key = $this->convertEmptyStringsToNull($value);
|
|
|
|
|
} elseif ($value === '') {
|
|
|
|
|
$data->$key = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return $data;
|
|
|
|
|
}
|
2026-02-18 10:15:47 +07:00
|
|
|
}
|