• Модуль: crm
  • Путь к файлу: ~/bitrix/modules/crm/lib/binding/entitybinding.php
  • Класс: Bitrix\Crm\Binding\EntityBinding
  • Вызов: EntityBinding::prepareBindingChanges
static function prepareBindingChanges($entityTypeID, array $origin, array $current, array &$added, array &$removed)
{
	if(!is_int($entityTypeID))
	{
		$entityTypeID = (int)$entityTypeID;
	}

	self::validateEntityTypeId($entityTypeID);

	$fieldName = self::resolveEntityFieldName($entityTypeID);

	$maxSort = 0;

	$originMap = array();
	$originPrimaryID = 0;
	foreach($origin as $binding)
	{
		$ID = isset($binding[$fieldName]) ? (int)$binding[$fieldName] : 0;
		if($ID > 0)
		{
			$originMap[$ID] = $binding;

			if(isset($binding['SORT']) && $binding['SORT'] > $maxSort)
			{
				$maxSort = (int)$binding['SORT'];
			}

			if(isset($binding['IS_PRIMARY']) && $binding['IS_PRIMARY'] === 'Y')
			{
				$originPrimaryID = $ID;
			}
		}
	}

	$currentMap = array();
	$currentPrimaryID = 0;
	foreach($current as $binding)
	{
		$ID = isset($binding[$fieldName]) ? (int)$binding[$fieldName] : 0;
		if($ID <= 0)
		{
			continue;
		}

		$currentMap[$ID] = $binding;
		if(isset($binding['IS_PRIMARY']) && $binding['IS_PRIMARY'] === 'Y')
		{
			$currentPrimaryID = $ID;
		}
	}

	$originIDs = array_keys($originMap);
	$currentIDs = array_keys($currentMap);

	if(!empty($removed))
	{
		$removed = array();
	}
	foreach(array_diff($originIDs, $currentIDs) as $ID)
	{
		$removed[$ID] = $originMap[$ID];
	}

	if(!empty($added))
	{
		$added = array();
	}
	foreach(array_diff($currentIDs, $originIDs) as $ID)
	{
		$binding = $currentMap[$ID];
		if($maxSort > 0 && !isset($binding['SORT']))
		{
			$maxSort += 10;
			$binding['SORT'] = $maxSort;
		}
		$added[$ID] = $binding;
	}

	foreach($current as $currentBinding)
	{
		$ID = isset($currentBinding[$fieldName]) ? (int)$currentBinding[$fieldName] : 0;
		if($ID <= 0)
		{
			continue;
		}

		if(isset($added[$ID]) || isset($removed[$ID]))
		{
			continue;
		}

		$originBinding = isset($originMap[$ID]) ? $originMap[$ID] : null;
		if(!is_array($originBinding))
		{
			continue;
		}

		$originSort = isset($originBinding["SORT"]) ? (int)$originBinding["SORT"] : 0;
		$currentSort = isset($currentBinding["SORT"]) ? (int)$currentBinding["SORT"] : 0;

		if($originSort !== $currentSort)
		{
			$added[$ID] = $currentBinding;
		}
	}

	if(($originPrimaryID > 0 || $currentPrimaryID > 0) && $originPrimaryID !== $currentPrimaryID)
	{
		if($currentPrimaryID > 0 && !isset($added[$currentPrimaryID]))
		{
			$added[$currentPrimaryID] = array_merge(
				$currentMap[$currentPrimaryID],
				array('IS_PRIMARY' => 'Y')
			);
		}

		if($originPrimaryID > 0 && !isset($removed[$originPrimaryID]))
		{
			$added[$originPrimaryID] = array_merge(
				$currentMap[$originPrimaryID],
				array('IS_PRIMARY' => 'N')
			);
		}
	}

	$removed = array_values($removed);
	$added = array_values($added);
}