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

Serializer doesn't keep types but convert them if not it can #1181

Closed
krabouilleur opened this issue Mar 31, 2020 · 4 comments
Closed

Serializer doesn't keep types but convert them if not it can #1181

krabouilleur opened this issue Mar 31, 2020 · 4 comments

Comments

@krabouilleur
Copy link

krabouilleur commented Mar 31, 2020

Q A
Bug report? yes
Feature request? no
BC Break report? no
RFC? no

Steps required to reproduce the problem

  1. Symfony + fostrestbundle + jmserializer + SensioFrameworkExtraBundle : the doc
  2. with postman : Post a body { "name": true }
  3. Body must be mapped with MyClass
use JMS\Serializer\Annotation as JMS;
class MyClass {
    /**
     * @JMS\Type("string") 
     */
    private $name;
}
  1. My controller :
/*
 * @ParamConverter("myClass", converter="fos_rest.request_body")
 */
public function postMyClass(Myclass $myClass)
    {
        dump($myClass);die();
}
  1. dump() result
MyClass:
{
  name: "1"
}

Expected Result

MyClass:
{
  name: true
}

'true' should not be converted to string
the serializer have not to convert the boolean in type string

Actual Result

'true' is converted to string "1". (same case for numbers where 123 is converted to "123"
Is there a way to keep type ? (so "name" would set to true then in my controller I get error validation)

@goetas
Copy link
Collaborator

goetas commented Apr 1, 2020

This is not a bug but the expected behaviour. If you define @Type("string") jms will enforce it to be a string.

You can use @Type("stringOrBoolean") and define for stringOrBoolean a custom type handler that allows both string and boolean values.

@goetas goetas closed this as completed Apr 1, 2020
@krabouilleur
Copy link
Author

ok I understand, so, in API, if we post

{
"IwantToSellMySoulToTheDevil" : "false"
}

will be returned to:

{
"IwantToSellMySoulToTheDevil" : true
}

@goetas
Copy link
Collaborator

goetas commented Apr 1, 2020

Exactly. "false" passed as string will be evaluated as true by most programming languages

@krabouilleur
Copy link
Author

Is there a way to override the type "string" for doing thing like this ?

@Type("string")

if ( !is_string($value) { 
 // exception
}

instead of creating a custom type ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants