Skip to content

[PHP] Model's valid() method should validate parents too #4530

@nazieb

Description

@nazieb
Description

When some Swagger definitions using allOf for inheritance, the models are generated correctly with extends keyword and parent::__construct($data) in the constructor. But the valid() method doesn't check the validity of the parent's attribute, only the model's own one.

IMO, since the model inherits all the parent's attribute, it'll more make sense to validate those too.

Swagger-codegen version

2.2.1

Swagger declaration file content or url

http://pastebin.com/k2EtN43n

Command line used for generation
swagger-codegen generate -i swagger.json -l php
Steps to reproduce

Using definitions above, the generated models would be like this:

BaseDevice.php

    public function valid()
    {
        if ($this->container['uuid'] === null) {
            return false;
        }
        if ($this->container['platform'] === null) {
            return false;
        }
        $allowed_values = array("android", "ios");
        if (!in_array($this->container['platform'], $allowed_values)) {
            return false;
        }
        return true;
    }

DeviceDetail.php

    public function valid()
    {
        if ($this->container['id'] === null) {
            return false;
        }
        return true;
    }

That way, if I construct DeviceDetail with only id, the valid() method will return true

php > include 'autoload.php';
php > $dev = new \DeviceDetail(['id' => 123]);
php > var_dump($dev->valid());
bool(true)
Suggest a Fix

IMO the "correct" valid() method for DeviceDetail should be like this:

    public function valid()
    {
        if (!parent::valid()) {
            return false;
        }

        if ($this->container['id'] === null) {
            return false;
        }
        return true;
    }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions