protected function update_reference_fields($fields)
 {
     $count = 0;
     $fieldsRepository = $this->getContainer()->get("doctrine")->getManager()->getRepository('TellawLeadsFactoryBundle:Field');
     $arr_scope = $this->getScopesArray();
     $em = $this->getContainer()->get("doctrine")->getEntityManager();
     $fields = $this->mergeFields($fields);
     foreach ($fields as $code => $field) {
         $testValues = $arr_scope;
         $testValues['default'] = isset($field['test-value']) ? $field['test-value'] : "";
         $field = $fieldsRepository->findOneByCode($code);
         // No match
         if (!$field) {
             $new_field = new Field();
             $new_field->setCode($code);
             $new_field->setTestValue(json_encode($testValues));
             $em->persist($new_field);
             $count++;
         } else {
             // first check if data is already set
             // If is is already check and not empty form form source replace (default)
             $testValuesArr = json_decode($field->getTestValue(), true);
             if (is_array($testValuesArr)) {
                 // data is valid JSON
                 foreach ($testValuesArr as $scope => $item) {
                     if ($testValuesArr[$scope] != $testValues[$scope] && !empty($testValues[$scope])) {
                         $testValuesArr[$scope] = $testValues[$scope];
                     }
                 }
                 $field->setTestValue(json_encode($testValuesArr));
             } else {
                 // data is not valid JSON
                 $field->setTestValue(json_encode($testValues));
             }
             $em->persist($field);
         }
     }
     $em->flush();
     return $count;
 }