From 0f9257862d644ab0b2fd57dc344c92aed78994f0 Mon Sep 17 00:00:00 2001 From: simon816 Date: Mon, 5 Aug 2024 21:04:25 +0100 Subject: [PATCH] Fix array coercion for array parameters with a $ref schema Fixes https://github.com/jhthorsen/mojolicious-plugin-openapi/issues/251 --- lib/JSON/Validator/Schema/OpenAPIv2.pm | 4 +++- t/openapiv3-coerce-array.t | 25 ++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/lib/JSON/Validator/Schema/OpenAPIv2.pm b/lib/JSON/Validator/Schema/OpenAPIv2.pm index c37460c7..d18fdd09 100644 --- a/lib/JSON/Validator/Schema/OpenAPIv2.pm +++ b/lib/JSON/Validator/Schema/OpenAPIv2.pm @@ -223,7 +223,9 @@ sub _bundle_ref_path_expand { sub _coerce_arrays { my ($self, $val, $param) = @_; my $data_type = data_type $val->{value}; - my $schema_type = schema_type $param->{schema} || $param; # $param->{schema} is for OpenAPIv3 + my $schema = $param->{schema} || $param; # $param->{schema} is for OpenAPIv3 + $schema = $self->get($schema->{'$ref'} =~ s!^#!!r) if $schema->{'$ref'}; + my $schema_type = schema_type $schema; return $val->{value} = [$val->{value}] if $schema_type eq 'array' and $data_type ne 'array'; return $val->{value} = @{$val->{value}} ? $val->{value}[-1] : undef if $schema_type ne 'array' and $data_type eq 'array'; diff --git a/t/openapiv3-coerce-array.t b/t/openapiv3-coerce-array.t index ce2cb74e..a101ffe0 100644 --- a/t/openapiv3-coerce-array.t +++ b/t/openapiv3-coerce-array.t @@ -3,7 +3,7 @@ use JSON::Validator; use Test::More; my $schema = JSON::Validator->new->schema('data://main/openapi.yaml')->schema; -my ($body, @errors); +my ($body, $query, @errors); subtest 'number to array' => sub { $body = {exists => 1, value => {id => 42}}; @@ -23,9 +23,16 @@ subtest 'already an array' => sub { is "@errors", "", "valid"; }; +subtest 'parameter array schema is $ref' => sub { + $query = {exists => 1, value => [42, 43]}; + @errors = $schema->validate_request([get => '/test'], {query => \&query}); + is "@errors", "", "valid"; +}; + done_testing; sub body {$body} +sub query {$query} __DATA__ @@ openapi.yaml @@ -53,3 +60,19 @@ paths: responses: 200: description: OK + get: + parameters: + - name: id + in: query + required: true + schema: + $ref: '#/components/schemas/IntArray' + responses: + 200: + description: OK +components: + schemas: + IntArray: + type: array + items: + type: integer