Question:
I have the following doubt: is it possible to validate the shape of an array before creating an object?
I have the following scenario. I am creating an apiRest and the programmer that consumes my API sends me a message with the following JSON:
[
{
"Codigo":"1",
"Nombre":"NESTEA",
"Presentacion":"1.5 L",
"Foto":"http://localhost/api/public/img/pepsi.jpg",
"MarcaId":"1",
"FamiliaId":"1",
"ProveedorId":"2",
"Rating":"5",
"Estado":"0"
}
]
In the apiRest I implemented a post method and it must create a new object with the JSON converted into an array:
if($_SERVER['REQUEST_METHOD']=='POST'){
$postBody = file_get_contents("php://input");
$jsonToArray = json_decode($postBody,true);
$producto = new productos($jsonToArray);
print_r($producto->getCodigo());
http_response_code(200);
}
Class code:
class productos {
//atributos
private $Codigo;
private $Nombre;
private $Presentacion;
private $Foto;
private $MarcaId;
private $FamiliaId;
private $ProveedorId;
private $Rating;
private $Estado;
//constructor
public function productos($array){
$this->Codigo = $array[0]['Codigo'];
$this->Nombre = $array[0]['Nombre'];
$this->$Presentacion = $array[0]['Presentacion'];
$this->Foto = $array[0]['Foto'];
$this->MarcaI = $array[0]['MarcaId'];
$this->FamiliaId = $array[0]['FamiliaId'];
$this->ProveedorId = $array[0]['ProveedorId'];
$this->Rating = $array[0]['Rating'];
$this->Estado = $array[0]['Estado'];
}
public function GuardarProducto(){
return $this->Codigo;
}
}
So far everything is fine. The problem arises when they stop sending me a parameter. For example:
[
{
"Codigo":"1",
"Nombre":"NESTEA",
"Presentacion":"1.5 L",
"Foto":"http://localhost/api/public/img/pepsi.jpg",
"MarcaId":"1",
"FamiliaId":"1",
"ProveedorId":"2",
}
]
I get the following error:
Notice : Undefined variable: Presentacion in C: \ xampp \ htdocs \ api \ objects \ products.php on line 21
Fatal error : Cannot access empty property in C: \ xampp \ htdocs \ api \ objects \ products.php on line 21
The only thing I can think of is to use if(isset(array[0]['Estado']){ //validar }
, but I want all the fields to be required and send a 400 error to the programmer if the POST is not correct.
How could I do it?
Answer:
Just like you said, with isset()
and then the header()
function to send you the error response.
In the file where you receive the data you could use a try/catch
block and there handle the error status. Something like that:
try {
$postBody = file_get_contents("php://input");
$jsonToArray = json_decode($postBody,true);
$producto = new productos($jsonToArray);
print_r($producto->getCodigo());
http_response_code(200);
} catch (Exception $e) {
header('HTTP/1.1 400 ' . $e->getMessage());
}
And in the class throw an exception when some validation fails:
if (!isset($array[0]['Estado'])) {
throw new Exception('El campo Estado es obligatorio');
}