Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pass Schema class to format validator #219

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Schema/Keywords/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public function validate($data, $types, ?string $format = null): void
$formatValidator = new $formatValidator();
}

if (! $formatValidator($data)) {
if (! $formatValidator($data, $this->parentSchema)) {
throw FormatMismatch::fromFormat($format, $data, $matchedType);
}
}
Expand Down
31 changes: 31 additions & 0 deletions tests/Schema/Keywords/TypeFormatTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace League\OpenAPIValidation\Tests\Schema\Keywords;

use cebe\openapi\spec\Schema;
use League\OpenAPIValidation\Schema\Exception\FormatMismatch;
use League\OpenAPIValidation\Schema\SchemaValidator;
use League\OpenAPIValidation\Schema\TypeFormats\FormatsContainer;
Expand Down Expand Up @@ -80,6 +81,36 @@ public function __invoke($value): bool
$this->addToAssertionCount(1);
}

public function testItAllowsCustomFormatWithParentSchema(): void
{
$spec = <<<SPEC
schema:
type: string
format: country
x-continent: europe
SPEC;

$countryFormat = new class ()
{
/**
* @param mixed $value
*/
public function __invoke($value, Schema $parentSchema): bool
{
if ($parentSchema->{'x-continent'} === 'europe') {
return $value === 'england';
}

return false;
}
};
FormatsContainer::registerFormat('string', 'country', $countryFormat);

$schema = $this->loadRawSchema($spec);
(new SchemaValidator())->validate('england', $schema);
$this->addToAssertionCount(1);
}

public function testItAllowsCustomFormatRed(): void
{
$spec = <<<SPEC
Expand Down