I have the following question: 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 should create a new object with the JSON converted to 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 I stop sending 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 : 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?
Just like you said, with
isset()
and then the functionheader()
to send you the error response.In the file where you receive the data you could use a block
try/catch
and handle the error status there. Something like that:And in the class send an exception when some validation fails:
As I see it, the most optimal way to do what you want is to add a property to your products object or the ones you create later called unused, along with its getter, in which you are going to add the properties that you are not interested in whether or not they appear when you collect the array in the json, by default all the properties you have will be required, and only for them will it be checked to verify if your array is valid or not. In my case I made a class called Validator to put there the functionalities that I used to do the validations. This is the code:
This is your products class :
And here is the entry point with which you start your code:
I give you two ways of implementation, in the second way you can create more validation rules once you know that you have the complete array
1 how to check if an array is "complete" (all keys defined in a template)
Result:
2 included as a check in the constructor
Result:
You could create a private method in the class in charge of verifying that all the fields in
array
which you pass to the constructor are present, this method could be called from the same constructor.The code would look more or less like this: