I have the following question: is it possible to validate the form of an array before creating an object?
I have the following scenario. I am creating an apiRest and the programmer who consumes my API sends me a post 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 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: Presentation in C: \ xampp \ htdocs \ api \ objects \ products.php on line 21
Fatal error : Can not access empty property in C: \ xampp \ htdocs \ api \ objects \ products.php online 21 < br>
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 an error 400 to the programmer if the POST is not right.
How could I do it?