Skip to content
This repository has been archived by the owner on Jan 20, 2024. It is now read-only.

Commit

Permalink
Fix object validation error when input is not an array (#158)
Browse files Browse the repository at this point in the history
  • Loading branch information
nofirg authored and martin-georgiev committed Sep 24, 2019
1 parent 0e431da commit a400e0c
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Types/ObjectType.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public static function createFromArray($name, array $data = [])
*/
public function discriminate($value)
{
if (isset($value[$this->getDiscriminator()])) {
if (\is_array($value) && isset($value[$this->getDiscriminator()])) {
if ($this->getDiscriminatorValue() !== null) {
return $this->getDiscriminatorValue() === $value[$this->getDiscriminator()];
}
Expand Down
59 changes: 59 additions & 0 deletions tests/Types/ObjectTypeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace Raml\Tests\Types;

use PHPUnit\Framework\TestCase;
use Raml\ApiDefinition;
use Raml\Parser;
use Raml\Types\TypeValidationError;

class ObjectTypeTest extends TestCase
{
/**
* @var ApiDefinition
*/
private $apiDefinition;

protected function setUp()
{
parent::setUp();
$this->apiDefinition = (new Parser())->parse(__DIR__ . '/../fixture/object_types.raml');
}

/**
* @test
*/
public function shouldCorrectlyValidateCorrectType()
{
$resource = $this->apiDefinition->getResourceByUri('/actors/1');
$method = $resource->getMethod('get');
$response = $method->getResponse(200);
$body = $response->getBodyByType('application/json');
$type = $body->getType();

$type->validate([
'fistName' => 'Jackie',
'lastName' => 'Сhan',
]);

$this->assertTrue($type->isValid());
}

/**
* @test
*/
public function shouldNotCorrectlyValidateObjectType()
{
$resource = $this->apiDefinition->getResourceByUri('/actors/1');
$method = $resource->getMethod('get');
$response = $method->getResponse(200);
$body = $response->getBodyByType('application/json');
$type = $body->getType();

$type->validate('Jackie Сhan');

$this->assertFalse($type->isValid());
$this->assertCount(1, $type->getErrors());
$this->assertInstanceOf(TypeValidationError::class, $type->getErrors()[0]);
}
}
23 changes: 23 additions & 0 deletions tests/fixture/object_types.raml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#%RAML 1.0

title: List of actors API
baseUri: http://example.api.com/{version}
version: v1
mediaType: application/json

/actors/{id}:
get:
responses:
200:
body:
application/json:
type: Actor
types:
Actor:
properties:
fistName:
type: string
required: true
lastName:
type: string
required: true

0 comments on commit a400e0c

Please sign in to comment.