Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PHP] - Add range HTTP code support #20992

Merged
merged 8 commits into from
Apr 6, 2025

Conversation

jtreminio
Copy link
Contributor

@jtreminio jtreminio commented Mar 29, 2025

Adds ranged HTTP code support to the php and php-nextgen generators.

Given:

paths:
  /fake/with_4xx_range_response/endpoint:
    post:
      tags:
        - fake
      summary: test endpoint with 400-499 range response http code with dataType
      operationId: fake-with_4xx_range_response-endpoint
      responses:
        200:
          description: Valid status value
        '4xx':
          description: Range of HTTP code 400-499
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      requestBody:
        $ref: '#/components/requestBodies/Pet'

we want the API endpoint to handle a range of HTTP codes between 400 and 499.

Additional fixes:

The php/psr-18 currently generates broken code:

            switch($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\OpenAPI\Client\Model\Pet',
                        $response,
                    );
                case 4xx:
                    return $this->handleResponseWithDataType(
                        '\OpenAPI\Client\Model\ErrorResponse',
                        $response,
                    );
            }

Additional refactoring:

Creates new method inside Api classes, ::handleResponseWithDataType(). This method handles the repeated code throughout the Api classes that check response code against a list and returns the deserialized object type.

Finally, there appears to be a bug in how non-2xx HTTP codes are handled. Given a set of response codes 200 and 400:

  /fake/with_400_response/endpoint:
    post:
      tags:
        - fake
      summary: test endpoint with 400 response http code with dataType
      operationId: fake-with_400_response-endpoint
      responses:
        200:
          description: Valid status value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Pet'
        '400':
          description: Invalid status value
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      requestBody:
        $ref: '#/components/requestBodies/Pet'

the generated code before this PR looks like this:

            $statusCode = $response->getStatusCode();


            switch($statusCode) {
                case 200:
                    if ('\OpenAPI\Client\Model\Pet' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\OpenAPI\Client\Model\Pet' !== 'string') {
                            try {
                                $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                            } catch (\JsonException $exception) {
                                throw new ApiException(
                                    sprintf(
                                        'Error JSON decoding server response (%s)',
                                        $request->getUri()
                                    ),
                                    $statusCode,
                                    $response->getHeaders(),
                                    $content
                                );
                            }
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                case 400:
                    if ('\OpenAPI\Client\Model\ErrorResponse' === '\SplFileObject') {
                        $content = $response->getBody(); //stream goes to serializer
                    } else {
                        $content = (string) $response->getBody();
                        if ('\OpenAPI\Client\Model\ErrorResponse' !== 'string') {
                            try {
                                $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                            } catch (\JsonException $exception) {
                                throw new ApiException(
                                    sprintf(
                                        'Error JSON decoding server response (%s)',
                                        $request->getUri()
                                    ),
                                    $statusCode,
                                    $response->getHeaders(),
                                    $content
                                );
                            }
                        }
                    }

                    return [
                        ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\ErrorResponse', []),
                        $response->getStatusCode(),
                        $response->getHeaders()
                    ];
                
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

The line if ($statusCode < 200 || $statusCode > 299) { never gets triggered to throw an exception because the switch finds a match in case 400:.

This may not matter because my understanding is the $response = $this->client->send($request, $options); call will throw an exception on any non-2xx response code, triggering the following catch:

        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\OpenAPI\Client\Model\Pet',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);
                    throw $e;
                
            }
        
            if ($this->responseWithinRangeCode('4xx', $e->getCode())) {
                $data = ObjectSerializer::deserialize(
                    $e->getResponseBody(),
                    '\OpenAPI\Client\Model\ErrorResponse',
                    $e->getResponseHeaders()
                );
                $e->setResponseObject($data);
                throw $e;
            }

            throw $e;
        }

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@jtreminio jtreminio marked this pull request as ready for review March 29, 2025 18:54
@jtreminio
Copy link
Contributor Author

Pinging maintainers:

@jebentier (2017/07), @dkarlovi (2017/07), @mandrean (2017/08), @jfastnacht (2017/09), @ybelenko (2018/07), @renepardon (2018/12)

@wing328
Copy link
Member

wing328 commented Apr 6, 2025

tests passed locally

PHPUnit 9.6.22 by Sebastian Bergmann and contributors.

...............................................................  63 / 234 ( 26%)
............................................................... 126 / 234 ( 53%)
............................................................... 189 / 234 ( 80%)
.............................................                   234 / 234 (100%)

Time: 00:01.516, Memory: 14.00 MB

OK (234 tests, 410 assertions)

@wing328 wing328 merged commit 6b13ad5 into OpenAPITools:master Apr 6, 2025
15 checks passed
@jtreminio jtreminio deleted the php-range_http_code_support branch April 6, 2025 16:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants