loopline-systems / closeio-api-wrapper

PHP Wrapper to use the Close.io API
MIT License
14 stars 15 forks source link

BadApiException gives a PHP exception itself for 'Phone number not valid' error #28

Closed danbarker closed 6 years ago

danbarker commented 7 years ago

When using the LeadApi to send a Lead object to Close, if you don't internationalise the phone number, it will sometimes return the following error:

{"field-errors":{"phones":[{"phone":"Phone number is not valid. Please use the international format like +16505551234"}]}}

(Sometimes it will just automatically add +1, as it guesses that you're trying to put a US phone number).

The closeio-api-wrapper throws a BadApiRequestException in this case (from Curl->getResponse method). BadApiRequestException is passed a multi-level array for the error, that is created by json_decode on the json response sent by the API. BadApiRequestException then attempts to turn the multi-level array of errors it is sent into a single string ($output):

   public function __construct(array $allErrors)
    {
        $output = '';
        foreach ($allErrors as $type => $errorsByType){
            if (! empty ($errorsByType)) {
                if (is_array($errorsByType)) {
                    $output .= $type . ' : ' .PHP_EOL;
                    foreach ($errorsByType as $key => $error){
                        $output .= $key . ' => ' . $error . PHP_EOL;
                    }
                } else {
                    $output .= $type . ' : ' . $errorsByType;
                }
            }
        }
        parent::__construct('Api request returned errors. ' . PHP_EOL . $output);
    }

However, the code above only supports being passed a 2-deep array. The error given above is 3-deep, so the line $output .= $key . ' => ' . $error . PHP_EOL; causes a PHP exception to be thrown, as $error is an array and we are trying to concatenate it to the $output string.