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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.