Skip to content
Snippets Groups Projects
Commit b00c52ec authored by Rich Lott / Artful Robot's avatar Rich Lott / Artful Robot
Browse files

tweak string to integer coercing

parent a701da4d
Branches
Tags
No related merge requests found
......@@ -63,7 +63,7 @@ namespace Civi\Inlay;
*
* If you use setCoerce() then it will make reasonable efforts to coerce scalar values to the desired types.
* - most things work as you'd expect.
* - if the type is integer, then '123' is cast, but '123.4' is not. '123.00' IS cast.
* - if the type is integer, then '123' is cast, but '123.4' or '123.0' is not.
* - it will try to cast to the given types in turn. So if the value can't be cast to the first type
* it will try the next type.
* - if NULL is in the list of acceptable types, data will be set NULL, if it could not be cast to
......@@ -361,7 +361,7 @@ class ArraySchema {
}
elseif ($acceptableType === 'integer') {
if (in_array($actualType, ['bool', 'double', 'NULL'])
|| ($actualType === 'string' && strval(intval($value)) === rtrim($value, '.0'))
|| ($actualType === 'string' && strval(intval($value)) === $value)
) {
$value = (int) $value;
return TRUE;
......
......@@ -135,9 +135,7 @@ class ArraySchemaTest extends \PHPUnit\Framework\TestCase /*implements HeadlessI
[ ['i' => '123' ], 0, $wanted ],
[ ['i' => (double) 123.0 ], 0, $wanted ],
[ ['i' => (double) 123.1 ], 0, $wanted ],
[ ['i' => '123.0' ], 0, $wanted ], // Put up with .000
[ ['i' => '123.1' ], 1 ], // If we want an int, we'll put up with it in a string, but we're not having decimals.
[ ['i' => '234.1' ], 1 ], // wrong number completely.
[ ['i' => '123.0' ], 1 ], // If we want an int, we'll put up with it in a string, but we're not having decimals.
[ ['i' => [234] ], 1], // can't cast arrays.
[ ['i' => NULL ], 0, ['i' => 0]], // null gets cast to zero
],
......@@ -197,7 +195,7 @@ class ArraySchemaTest extends \PHPUnit\Framework\TestCase /*implements HeadlessI
$this->runTests('coerce to fallbacks', $as,
[
// #1 fred is not an int, so fallback should be used. trunk not required.
[['i' => 'fred'], 0, ['i' => 567]],
[['i' => 'fred'], 0, ['i' => 567]],
// #2 'i' is fine. trunk is given but the branch value is invalid (not a bool)
[['i' => 1, 'trunk' => ['branch' => 123]], 0, ['i' => 1, 'trunk' => ['branch' => true]]],
// #3 'i' is fine, foo is not and we have no fallback: error.
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment