Php_codesniffer: FunctionCommentThrowTag.WrongNumber when exception is thrown once but built conditionally

Created on 14 Apr 2019  路  2Comments  路  Source: squizlabs/PHP_CodeSniffer

When you have a code like below, PHPCS complains via FunctionCommentThrowTag.WrongNumber sniff that 8 @thorws are expected even though all unique exceptions are documented and only one of them will be ever thrown when meets the condition.

Only two ways are there to mitigate this issue:

  • Disable the sniff at the function, file, or project level.
  • Use a factory function!?! to throw Exception.

Code Example

    /**
     * Process HTTP errors of 4xx, and 5xx.
     *
     * @param array  $response Response array returned by some_method().
     * @param string $url      URI called in request.
     * @param string $method   Optional. Request method type. Default 'GET'.
     * @param array  $data     Optional. Raw data used while creating the request.
     *
     * @throws HTTPClientException Throws client exception if error within 4xx range.
     * @throws HTTPServerException Throws server exception if error within 5xx range.
     * @throws UnknownErrorException Thrown when unknown status is returned.
     */
    private function handle_http_errors( array $response, string $url, string $method, array $data ): void {
        $status_code = $response['response']['code'];
        switch ( $status_code ) {
            case 400:
                throw HttpClientException::bad_request( $response, $url, $method, $data );
            case 401:
                throw HttpClientException::unauthorized( $response );
            case 404:
                throw HttpClientException::not_found( $response );
            case 406:
                throw AreaNotServiceable::from_http_response( $response, $url, $data, $this );
            case 409:
                throw HttpClientException::duplicate_booking( $response, $data );
            case 422:
                throw HttpClientException::invalid_shipping_method( $response, $data );
            case 500 <= $status_code:
                throw HttpServerException::server_error( $status_code );
            default:
                throw new UnknownErrorException();
        }
    }
Bug

Most helpful comment

This has now been fixed and will be in the next release. Thanks for reporting it.

All 2 comments

Looks like a bug to me, caused by throwing exceptions that are not using an explicit new keyword or a variable. In my testing of a fix, it still shows that you need 4 exception types documented (you're missing AreaNotServiceable) but that looks correct to me.

This has now been fixed and will be in the next release. Thanks for reporting it.

Was this page helpful?
0 / 5 - 0 ratings