0

i have a php object i called $product, it has several string properties. Now i want to check the values of its fields to see if they are empty, but i am having to do this with many if statements like below, is there any smarter way?, i don't mind using a library

private function validate(Product $product)
{


    if (isEmpty($product->country)) {

        throw New \Exception("country is empty");
    } elseif (isEmpty($product->getCategory())) {

        throw New \Exception("category is empty");
     } elseif (isEmpty($product->getSubCategory())) {

        throw New \Exception("subcategory is empty");
     } elseif (isEmpty($product->getCoolingType())) {

        throw New \Exception("category is empty");
    } elseif (isEmpty($product->getPackagingType())) {

        throw New \Exception("category is empty");
    } 


}

btw i am using symfony framwork 3.0 if that helps all the fields i am trying to validate are strings

Edwin O.
  • 4,998
  • 41
  • 44

1 Answers1

1

You could loop them with the function names / error to print if returned value is empty as the key/value array.

Would look something like this:

 <?php
 private function validate(Product $product)
 {
     $functions = array("getCategory" => "category",
                         "getSubCategory" => "subcategory"
                        // as many function_name => error messages here as you want
     );

     foreach($functions as $function_name => $error) {
         if(isEmpty($product->$function())) {
           throw New \Exception("$error is empty");
         }
     }
}

Note that your first example, $product->country doesn't fit this, so it would have to use a different case.

This answer explains what I'm doing with the if(isEmpty($product->$function())) { line of code.

Bing
  • 3,071
  • 6
  • 42
  • 81