oooas icon indicating copy to clipboard operation
oooas copied to clipboard

Schema: defining multiple types

Open happyDemon opened this issue 3 years ago • 4 comments

I have an internal API that interfaces with multiple third-party APIs and normalizes the response to something more manageable.

Because of this, I have properties that can either be 'integer' or 'string' depending on the service.

Following the spec: https://swagger.io/docs/specification/data-models/data-types/ (mixed types) it should be possible by defining them as OneOff.

Which kind of works, but I lose the possibility to set a description and such.

Is this something that just hasn't been implemented in this library or are you omitting it for a specific reason?

happyDemon avatar Dec 22 '20 11:12 happyDemon

Hi @happyDemon 👋

This functionality is provided through:

  • https://github.com/goldspecdigital/oooas/blob/master/src/Objects/OneOf.php
  • Which extends https://github.com/goldspecdigital/oooas/blob/master/src/Objects/SchemaComposition.php

Example usage will be:

OneOf::create()->schemas($schemaOne, $schemaTwo);

matthew-inamdar avatar Dec 23 '20 12:12 matthew-inamdar

Thanks for the quick reply, there's a little hiccup though, since they don't extend \GoldSpecDigital\ObjectOrientedOAS\Objects\Schema I'm unable to assign them in quite a few places.

Assigning as a property on an object-type schema for example, or when trying to add it to the schema of a MediaType.

Currently, as a workaround, I've implemented the functionality I needed locally in a separate OneOfProperty class

happyDemon avatar Dec 23 '20 13:12 happyDemon

@happyDemon you're right, I'll look at providing an update to fix this 👍

matthew-inamdar avatar Jan 03 '21 15:01 matthew-inamdar

Greetings! I would also like to have this work out of the box. But meanwhile if anybody else is looking for workaround, it could be roughly done by adding a Schema-wrapper for SchemaComposition. Something like this:

<?php

declare(strict_types=1);

namespace SomeNameSpace\Goes\Here;

use GoldSpecDigital\ObjectOrientedOAS\Objects\Schema;
use GoldSpecDigital\ObjectOrientedOAS\Objects\SchemaComposition;

class SchemaCompositionWrapper extends Schema
{
    private SchemaComposition $composition;

    public function composition(SchemaComposition $composition): self
    {
        $instance = clone $this;
        $instance->composition = $composition;

        return $instance;
    }

    protected function generate(): array
    {
        return array_merge(
            parent::generate(),
            $this->composition->toArray(),
        );
    }
}

The usage is simple:

$schema = SchemaCompositionWrapper::create()
    ->composition(
        AnyOf::create()->schemas(...)
    );

$mediaType->schema($schema);

(As always, be cautious if you copy-paste this :) It's just a draft)

Amegatron avatar Aug 31 '21 15:08 Amegatron