Symfony3 Serializer - 如何从点字符串中分离值并组合在一个数组列中

时间:2017-05-10 14:18:31

标签: php symfony symfony-2.8 symfony-3.1 symfony-3.2

我从给定格式的http请求中获取数据

{
  "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,
}

列的主义实体定义

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

对于visitor_country和views_country,数组键/值由点分隔。这些点分隔值

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

应该

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

我正在使用Symfony序列化组件来序列化所请求的数据,并且存在使数据非规范化的问题。

我做了类似的事

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;
    }

}

有什么想法解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

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);
    }
}

并在序列化程序中使用此规范化程序:

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

结果:

enter image description here