Skip to content

fix: Create deep copy before checking each sub schema in oneOf #791

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

Merged
merged 5 commits into from
Feb 26, 2025
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Add required permissions for welcome action ([#789](https://github.com/jsonrainbow/json-schema/pull/789))
- Upgrade php cs fixer to latest ([#783](https://github.com/jsonrainbow/json-schema/pull/783))
- Create deep copy before checking each sub schema in oneOf ([#791](https://github.com/jsonrainbow/json-schema/pull/791))

### Changed
- Used PHPStan's int-mask-of<T> type where applicable ([#779](https://github.com/jsonrainbow/json-schema/pull/779))
Expand Down
16 changes: 11 additions & 5 deletions src/JsonSchema/Constraints/UndefinedConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use JsonSchema\Constraints\TypeCheck\LooseTypeCheck;
use JsonSchema\Entity\JsonPointer;
use JsonSchema\Exception\ValidationException;
use JsonSchema\Tool\DeepCopy;
use JsonSchema\Uri\UriResolver;

/**
Expand Down Expand Up @@ -352,26 +353,31 @@ protected function validateOfProperties(&$value, $schema, JsonPointer $path, $i

if (isset($schema->oneOf)) {
$allErrors = [];
$matchedSchemas = 0;
$matchedSchemas = [];
$startErrors = $this->getErrors();
$coerce = $this->factory->getConfig(self::CHECK_MODE_COERCE_TYPES);

foreach ($schema->oneOf as $oneOf) {
try {
$this->errors = [];
$this->checkUndefined($value, $oneOf, $path, $i);
if (count($this->getErrors()) == 0) {
$matchedSchemas++;

$oneOfValue = $coerce ? DeepCopy::copyOf($value) : $value;
$this->checkUndefined($oneOfValue, $oneOf, $path, $i);
if (count($this->getErrors()) === 0) {
$matchedSchemas[] = ['schema' => $oneOf, 'value' => $oneOfValue];
}
$allErrors = array_merge($allErrors, array_values($this->getErrors()));
} catch (ValidationException $e) {
// deliberately do nothing here - validation failed, but we want to check
// other schema options in the OneOf field.
}
}
if ($matchedSchemas !== 1) {
if (count($matchedSchemas) !== 1) {
$this->addErrors(array_merge($allErrors, $startErrors));
$this->addError(ConstraintError::ONE_OF(), $path);
} else {
$this->errors = $startErrors;
$value = $matchedSchemas[0]['value'];
}
}
}
Expand Down
38 changes: 38 additions & 0 deletions src/JsonSchema/Tool/DeepCopy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace JsonSchema\Tool;

use JsonSchema\Exception\JsonDecodingException;
use JsonSchema\Exception\RuntimeException;

class DeepCopy
{
/**
* @param mixed $input
*
* @return mixed
*/
public static function copyOf($input)
{
$json = json_encode($input);
if (JSON_ERROR_NONE < $error = json_last_error()) {
throw new JsonDecodingException($error);
}

if ($json === false) {
throw new RuntimeException('Failed to encode input to JSON: ' . json_last_error_msg());
}

return json_decode($json, self::isAssociativeArray($input));
}

/**
* @param mixed $input
*/
private static function isAssociativeArray($input): bool
{
return is_array($input) && array_keys($input) !== range(0, count($input) - 1);
}
}
75 changes: 75 additions & 0 deletions tests/Constraints/UndefinedConstraintTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

declare(strict_types=1);

namespace JsonSchema\Tests\Constraints;

use JsonSchema\Constraints\Constraint;

class UndefinedConstraintTest extends BaseTestCase
{
/**
* @return array{}
*/
public function getInvalidTests(): array
{
return [];
}

/**
* @return array<string, array{input: string, schema: string, checkMode?: int}>
*/
public function getValidTests(): array
{
return [
'oneOf with type coercion should not affect value passed to each sub schema (#790)' => [
'input' => <<<JSON
{
"id": "LOC1",
"related_locations": [
{
"latitude": "51.047598",
"longitude": "3.729943"
}
]
}
JSON
,
'schema' => <<<JSON
{
"title": "Location",
"type": "object",
"properties": {
"id": {
"type": "string"
},
"related_locations": {
"oneOf": [
{
"type": "null"
},
{
"type": "array",
"items": {
"type": "object",
"properties": {
"latitude": {
"type": "string"
},
"longitude": {
"type": "string"
}
}
}
}
]
}
}
}
JSON
,
'checkMode' => Constraint::CHECK_MODE_COERCE_TYPES
]
];
}
}
53 changes: 53 additions & 0 deletions tests/Tool/DeepCopyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace JsonSchema\Tests\Tool;

use JsonSchema\Tool\DeepCopy;
use PHPUnit\Framework\TestCase;

class DeepCopyTest extends TestCase
{
public function testCanDeepCopyObject(): void
{
$input = (object) ['foo' => 'bar'];

$result = DeepCopy::copyOf($input);

self::assertEquals($input, $result);
self::assertNotSame($input, $result);
}

public function testCanDeepCopyObjectWithChildObject(): void
{
$child = (object) ['bar' => 'baz'];
$input = (object) ['foo' => $child];

$result = DeepCopy::copyOf($input);

self::assertEquals($input, $result);
self::assertNotSame($input, $result);
self::assertEquals($input->foo, $result->foo);
self::assertNotSame($input->foo, $result->foo);
}

public function testCanDeepCopyArray(): void
{
$input = ['foo' => 'bar'];

$result = DeepCopy::copyOf($input);

self::assertEquals($input, $result);
}

public function testCanDeepCopyArrayWithNestedArray(): void
{
$nested = ['bar' => 'baz'];
$input = ['foo' => $nested];

$result = DeepCopy::copyOf($input);

self::assertEquals($input, $result);
}
}