0

I get data from http request in given form

{
  "start_date": "2017-03-13",
  "end_date": "2017-03-19",
  "visitors_total": 2555,
  "views_total": 2553,
  "visitors_country.france": 100,
  "visitors_country.germany": 532,
  "visitors_country.poland": 32,
  "views_country.france": 110,
  "views_country.germany": 821,
  "views_country.poland": 312,
}

doctrine entity defination for columns

"start_date" => datetime
"end_date" => datetime
"visitors_total" => int
"views_total" => int
"visitors_country" => array
"views_country => array

For the visitors_country and views_country , array keys/values are separated by dots. These dot separated values

"views_country.france": 110,
"views_country.germany": 821,
"views_country.poland": 312,

shoud be

'view_country' => array(
   'france'=> 110,
   'germany'=> 821,
   'poland'=> 312,
);

I am using Symfony serialize component for the serialization of requested data and having problem to denormalize the data.

I did something like this

class ArrayDotNormalizer implements DenormalizerInterface
{

    /**
     * {@inheritdoc}
     *

     */
    public function denormalize($data, $class, $format = null, array $context = array())
    {
     // Actually, this function applies to each column of requested data ,
    //but how to  separate values by dot and join them in one array and store as array json in db ?
    }

    /**
     * {@inheritdoc}
     */
    public function supportsDenormalization($data, $type, $format = null)
    {

        return strpos($data, '.') !== false;
    }

}

Any idea to solve this?

Shahid
  • 357
  • 5
  • 12
  • Data from http is json? if so then decode json will return array and then try using explode option with (dot) to make as your desired array structure – Vignesh Pichamani May 10 '17 at 14:28

1 Answers1

0

Try with this:

class ArrayDotNormalizer extends ObjectNormalizer
{
    /**
     * {@inheritdoc}
     */
    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = [])
    {
        if (strpos($attribute, '.') !== false) {
            list($attribute, $country) = explode('.', $attribute);
            $currentValue = (array) $this->propertyAccessor->getValue($object, $attribute);
            $value = array_replace($currentValue, [$country => $value]);
        }

        return parent::setAttributeValue($object, $attribute, $value, $format, $context);
    }
}

and use this normalizer in your serializer:

 $serializer = new Serializer([new ArrayDotNormalizer()], [new JsonEncoder()]);

Result:

enter image description here

rafrsr
  • 1,940
  • 3
  • 15
  • 31