Problem/Motivation

The JSON Schema that core's serializer returns for a decimal accepts any string, including "not a number".

DecimalData declares {"type": "string", "format": "number"} , but "number" isn't one of the formats JSON Schema defines.

Drupal's JSON Schema validator, justinrainbow/json-schema, simply skips it.

Steps to reproduce

On a site installed with the Standard profile, after ddev drush en -y serialization, this validates two values against the decimal schema:

ddev drush php:eval '$schema = json_decode(json_encode(\Drupal::service("serializer")->getJsonSchema(\Drupal::typedDataManager()->create(\Drupal\Core\TypedData\DataDefinition::create("decimal")->setRequired(TRUE)), []))); foreach (["12.50", "not a number"] as $value) { $v = new \JsonSchema\Validator(); $v->validate($value, $schema); print "$value: " . ($v->isValid() ? "valid" : "invalid") . "\n"; }'

It prints:

12.50: valid
not a number: valid

Proposed resolution

Add a pattern to DecimalData's #[JsonSchema] attribute, keeping type: string and format: number: ^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$. It rejects strings that aren't numbers, like "not a number", "" or " 12".

API changes

None.

Issue fork drupal-3643182

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

dries created an issue. See original summary.

dries’s picture

I opened a MR with the fix and a test.

The pattern allows an exponent until #3074419: Decimal field returning the incorrect string during saving is fixed, as its @todo explains.

dries’s picture

Status: Active » Needs review
ronaldtebrake’s picture

Status: Needs review » Needs work
dries’s picture

Status: Needs work » Needs review

@ronaldtebrake, thanks for the review.

You found a real bug: Drupal's PrimitiveType constraint accepts "5\n" as a decimal. It's older than this MR and needs fixing either way, so I opened #3644214: PrimitiveType constraint accepts a decimal with a trailing newline. I already added a test to #3644214.

We don't have to change this MR for it. The pattern already rejects "5\n": JSON Schema patterns are ECMA-262, where $ is the end of input. It passes in PHP only because justinrainbow compiles the pattern as PCRE, where $ also matches before a final newline. I believe that is a bug in justinrainbow so I reported it upstream at https://github.com/jsonrainbow/json-schema/issues/1012. I guess you found two real bugs. :)

I left out $(?!\n) because JSON Schema asks schemas to avoid lookahead.

Setting this back to "Needs review" as both bugs will be addressed in their respective issues.

ronaldtebrake’s picture

Status: Needs review » Reviewed & tested by the community

Thanks @dries, I hadn't thought of that!

I've resolved my comment on the MR and am marking this as RTBC :)