PayPal\Validation\JsonValidator::validate PHP Method

validate() public static method

Helper method for validating if string provided is a valid json.
public static validate ( string $string, boolean $silent = false ) : boolean
$string string String representation of Json object
$silent boolean Flag to not throw \InvalidArgumentException
return boolean
    public static function validate($string, $silent = false)
    {
        @json_decode($string);
        if (json_last_error() != JSON_ERROR_NONE) {
            if ($string === '' || $string === null) {
                return true;
            }
            if ($silent == false) {
                //Throw an Exception for string or array
                throw new \InvalidArgumentException("Invalid JSON String");
            }
            return false;
        }
        return true;
    }

Usage Example

Exemplo n.º 1
0
 /**
  * Returns a list of Object from Array or Json String. It is generally used when your json
  * contains an array of this object
  *
  * @param mixed $data Array object or json string representation
  * @return array
  */
 public static function getList($data)
 {
     // Return Null if Null
     if ($data === null) {
         return null;
     }
     if (is_a($data, get_class(new \stdClass()))) {
         //This means, root element is object
         return new static(json_encode($data));
     }
     $list = array();
     if (is_array($data)) {
         $data = json_encode($data);
     }
     if (JsonValidator::validate($data)) {
         // It is valid JSON
         $decoded = json_decode($data);
         if ($decoded === null) {
             return $list;
         }
         if (is_array($decoded)) {
             foreach ($decoded as $k => $v) {
                 $list[] = self::getList($v);
             }
         }
         if (is_a($decoded, get_class(new \stdClass()))) {
             //This means, root element is object
             $list[] = new static(json_encode($decoded));
         }
     }
     return $list;
 }
All Usage Examples Of PayPal\Validation\JsonValidator::validate
JsonValidator