swagger-codegen icon indicating copy to clipboard operation
swagger-codegen copied to clipboard

[PHP] Bug generating list of maps results in "Uncaught Error: Class "int[]][" not found"

Open Cacodaimon opened this issue 6 months ago • 0 comments

Description

The generated PHP client code for the DTO in Java with the Swagger annotation is incorrect. The error occurs due to the improper handling of the nested map and array structure in the ObjectSerializer. This results in a PHP Fatal error: Uncaught Error: Class "int[]][" not found in …/lib/ObjectSerializer.php:299

The server code the nasty data structure comes from:

@ApiModelProperty
private List<Map<String, Set<Long>>> reactions;

The client code generated looks like this:

…
protected static $swaggerTypes = [
    'inserted' => 'int',
    'updated' => 'int',
    'message_id' => 'int',
    'reactions' => 'map[string,int[]][]'
];
…

The code extracted from the ObjectSerializer:

php > echo substr('map[string,int[]][]', 4, -1);
string,int[]][

As you can see its: int [ ] ] [ and not string , int [ ]

Swagger-codegen version

2.4.42

Swagger declaration file content or url

(for YAML code) or

"ReactionDTO" : {
  "type" : "object",
  "properties" : {
    "inserted" : {
      "type" : "integer",
      "format" : "int64",
      "readOnly" : true
    },
    "updated" : {
      "type" : "integer",
      "format" : "int64",
      "readOnly" : true
    },
    "messageId" : {
      "type" : "integer",
      "format" : "int64",
      "readOnly" : true
    },
    "reactions" : {
      "type" : "array",
      "items" : {
        "type" : "object",
        "additionalProperties" : {
          "type" : "array",
          "uniqueItems" : true,
          "items" : {
            "type" : "integer",
            "format" : "int64"
          }
        }
      }
    }
  }
},
Suggest a fix/enhancement

By counting the open and closed brackets, the correct position for splitting can be determined.

$class = 'map[string,int[]][]';
$openBrackets = 0;
$cutPos = 0;

$classWithoutMap = substr($class, 3);
for ($i = 0; $i < strlen($classWithoutMap); $i++) {
    if ($classWithoutMap[$i] === '[') {
        $openBrackets++;
    } elseif ($classWithoutMap[$i] === ']') {
        $openBrackets--;
    }
    if ($openBrackets === 0) {
        $cutPos = $i - 1;
        break;
    }
}
$inner = substr($class, 4, $cutPos);

echo $inner;

Cacodaimon avatar Aug 08 '24 11:08 Cacodaimon