• Модуль: crm
  • Путь к файлу: ~/bitrix/modules/crm/lib/merger/entitymerger.php
  • Класс: Bitrix\Crm\Merger\EntityMerger
  • Вызов: EntityMerger::mergeMultiFields
static function mergeMultiFields(array &$seed, array &$targ, $skipEmpty = false, array $options = array())
{
	if(empty($seed))
	{
		return;
	}

	$map = null;
	if(isset($options['map']) && is_array($options['map']))
	{
		$map = $options['map'];
	}

	$targID = 0;
	if(isset($options['targID']) && $options['targID'] > 0)
	{
		$targID = (int)$options['targID'];
	}

	$targMap = array();
	foreach($targ as $typeID => &$fields)
	{
		if($targID > 0 && $map !== null && isset($map[$typeID]) && is_array($map[$typeID]))
		{
			$sourceIDs = isset($map[$typeID]['SOURCE_ENTITY_IDS']) && is_array($map[$typeID]['SOURCE_ENTITY_IDS'])
				? $map[$typeID]['SOURCE_ENTITY_IDS'] : array();
			if(!in_array($targID, $sourceIDs))
			{
				foreach ($fields as $fieldId => $field)
				{
					if (!preg_match('/n\d+/', (string)$fieldId)) // if not a new value
					{
						$fields[$fieldId]['VALUE'] = ''; // empty value will be removed from DB
					}
				}

				continue;
			}
		}

		$typeMap = array();
		foreach($fields as &$field)
		{
			$value = isset($field['VALUE']) ? trim($field['VALUE']) : '';
			if($value === '')
			{
				continue;
			}

			$key = $typeID === \CCrmFieldMulti::PHONE
				? Crm\Integrity\DuplicateCommunicationCriterion::normalizePhone($value)
				: mb_strtolower($value);

			if($key !== '' && !isset($typeMap[$key]))
			{
				$typeMap[$key] = true;
			}
		}
		unset($field);

		if(!empty($typeMap))
		{
			$targMap[$typeID] = &$typeMap;
		}
		unset($typeMap);
	}
	unset($fields);

	$seedID = 0;
	if(isset($options['seedID']) && $options['seedID'] > 0)
	{
		$seedID = (int)$options['seedID'];
	}

	foreach($seed as $typeID => &$fields)
	{
		if($skipEmpty && isset($targ[$typeID]))
		{
			continue;
		}

		if($seedID > 0 && $map !== null)
		{
			if(!(isset($map[$typeID]) && is_array($map[$typeID])))
			{
				//Skip merging of type that not defined in map
				continue;
			}

			$sourceIDs = isset($map[$typeID]['SOURCE_ENTITY_IDS']) && is_array($map[$typeID]['SOURCE_ENTITY_IDS'])
				? $map[$typeID]['SOURCE_ENTITY_IDS'] : array();
			if(!in_array($seedID, $sourceIDs))
			{
				//Skip merging of entity that not defined in map
				continue;
			}
		}

		$fieldNum = 1;
		foreach($fields as $field)
		{
			$value = isset($field['VALUE']) ? trim($field['VALUE']) : '';
			if($value === '')
			{
				continue;
			}

			$key = $typeID === \CCrmFieldMulti::PHONE
				? Crm\Integrity\DuplicateCommunicationCriterion::normalizePhone($value)
				: mb_strtolower($value);

			if($key !== '' && (!isset($targMap[$typeID]) || !isset($targMap[$typeID][$key])))
			{
				if(!isset($targ[$typeID]))
				{
					$targ[$typeID] = array();
				}

				while(isset($targ[$typeID]["n{$fieldNum}"]))
				{
					$fieldNum++;
				}

				$targ[$typeID]["n{$fieldNum}"] = $field;
			}
		}
	}
	unset($fields);
}