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
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
Comment #3
dries commentedI 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
@todoexplains.Comment #4
dries commentedComment #5
ronaldtebrake commentedComment #6
dries commented@ronaldtebrake, thanks for the review.
You found a real bug: Drupal's
PrimitiveTypeconstraint 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 becausejustinrainbowcompiles the pattern as PCRE, where$also matches before a final newline. I believe that is a bug injustinrainbowso 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.
Comment #7
ronaldtebrake commentedThanks @dries, I hadn't thought of that!
I've resolved my comment on the MR and am marking this as RTBC :)