core icon indicating copy to clipboard operation
core copied to clipboard

"The type of the \"enabled\" attribute must be \"bool\", \"string\" given."

Open rernesto opened this issue 5 years ago • 3 comments

API Platform version(s) affected: 2.6

Description
If request JSON payload includes a boolean value between quotes ("true" instead true) we got a type mismatch error.

How to reproduce
Sending a boolean value surrounded by quotes (valid standard Json) to any resource.

Additional Context
Example payload:

{
  "email": "[email protected]",
  "roles": [
    "ROLE_USER"
  ],
    "password": "demo@2021",
    "firstName": "Demo",
    "lastName": "User",
    "groups": [],
    "enabled": "true"
}

If we send "enabled": true without quotes for value will work, but I need to send the boolean value surrounded by quotes and being recognized as Bool.

rernesto avatar Mar 19 '21 20:03 rernesto

Found two solutions, Events and Decorator approach. I am using Events temporary. I believe decorator is better, but I will implement some validations. In this case all my toggleable entities implements an Interface and use a trait, so I could use that info to improve support checks.

Events Approach

namespace CoralMedia\Component\Api\Event;


use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class JsonBooleanDeserializerSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => ['deserializeBoolean', EventPriorities::PRE_DESERIALIZE]
        ];
    }

    public function deserializeBoolean(RequestEvent $event)
    {
        $request = $event->getRequest();
        if(($request->getMethod() === Request::METHOD_POST ||
                $request->getMethod() === Request::METHOD_PATCH ||
                $request->getMethod() === Request::METHOD_PUT) &&
            $request->getRequestFormat() === 'jsonld') {

            $session = $request->getSession();
            $format = $request->getRequestFormat();
            $method = $request->getMethod();
            $locale = $request->getLocale();

            $data = json_decode($request->getContent(), true);
            $data['enabled'] = ($data['enabled'] === "false" || $data['enabled'] === "0") ? false : true;

            $request->initialize(
                $request->query->all(),
                $request->request->all(),
                $request->attributes->all(),
                $request->cookies->all(),
                $request->files->all(),
                $request->server->all(),
                json_encode($data)
            );

            $request->setRequestFormat($format);
            $request->setMethod($method);
            $request->setSession($session);
            $request->setLocale($locale);
        }
    }
}

As I don't use autowiring for my reusable components:

CoralMedia\Component\Api\Event\JsonBooleanDeserializerSubscriber:
        tags: ['kernel.event_subscriber']

Service Decorator Approach

<?php

namespace CoralMedia\Component\Api\Serializer\Normalizer;


use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;

class ToggleableDecoratorNormalizer implements DenormalizerInterface
{

    private $decorated;

    public function __construct(NormalizerInterface $decorated)
    {
        if (!$decorated instanceof DenormalizerInterface) {
            throw new \InvalidArgumentException(
                sprintf('The decorated normalizer must implement the %s.', DenormalizerInterface::class));
        }

        $this->decorated = $decorated;
    }

    public function supportsNormalization($data, $format = null)
    {
        return $this->decorated->supportsNormalization($data, $format);
    }

    public function normalize($object, $format = null, array $context = [])
    {
        $data = $this->decorated->normalize($object, $format, $context);
        if (is_array($data) && isset($data['enabled'])) {
            $data['enabled'] = ($data['enabled']==false || $data['enabled']==0)?"false":"true";
        }

        return $data;
    }

    public function supportsDenormalization($data, $type, $format = null)
    {
        return $this->decorated->supportsDenormalization($data, $type, $format);
    }

    public function denormalize($data, $type, $format = null, array $context = [])
    {
        if (is_array($data) && isset($data['enabled'])) {
            $data['enabled'] = ($data['enabled']=="false" || $data['enabled']=="0")?false:true;
        }
        return $this->decorated->denormalize($data, $type, $format, $context);
    }

    public function setSerializer(SerializerInterface $serializer)
    {
        if($this->decorated instanceof SerializerAwareInterface) {
            $this->decorated->setSerializer($serializer);
        }
    }
}

My service config:

    CoralMedia\Component\Api\Serializer\Normalizer\ToggleableDecoratorNormalizer:
        # By default .inner is passed as argument
        decorates: 'api_platform.jsonld.normalizer.item'

References:

rernesto avatar Mar 23 '21 21:03 rernesto

Hey @rernesto

I don't think this is a bug, it's more of a type error on your side, a string of value "true" is not the same as true, even using a type coercing library ( shameless plug - https://github.com/azjezz/psl/blob/1.6.x/src/Psl/Type/Internal/BoolType.php#L35 ), "true" would still not be considered a boolean.

If we add a special case for this, then a special case should be added for all other types of coercitions ( e.g: "1" to true, "123e-4" to 0.0123 .. etc).

Sorry, but personally, I'm against this.

azjezz avatar Mar 24 '21 11:03 azjezz

@azjezz I agree with you, but some JavaScripts frameworks cast Boolean values as String when you perform an encoding action. And still is a valid JSON and some JSON standards requires all non-numeric values being surrounded by quotes =(. I am using Sencha Ext 3.4.1 (Legacy Project). I tried overriding Ext.util.JSON, but that generates issues with other Ext components. So if for some reason a Frontend Framework is doing that, decorating the service works.

rernesto avatar Mar 27 '21 19:03 rernesto