- Модуль: crm
- Путь к файлу: ~/bitrix/modules/crm/lib/entityaddress.php
- Класс: Bitrix\Crm\EntityAddress
- Вызов: EntityAddress::prepareLocationAddress
static function prepareLocationAddress(
Address $locationAddress,
int $typeId, int $entityTypeId, int $entityId,
int $prevLocationAddressId
) : Address
{
$locationAddressId = $locationAddress->getId();
// Processing of the previous location-address, if the identifier is not equal to the current one,
// removal of links, if necessary, of the address itself.
if ($prevLocationAddressId > 0 && $locationAddressId !== $prevLocationAddressId)
{
// Check the existence of a location address
$prevLocationAddress = Address::load((int)$prevLocationAddressId);
if ($prevLocationAddress instanceof Address)
{
// Clearing links
$isPrevLocationAddressessLinksModified = self::cleanLocationAddressLinks(
$prevLocationAddress,
$typeId, $entityTypeId, $entityId
);
// If there are no links left, then delete the location-address
if (!$prevLocationAddress->hasLinks())
{
$prevLocationAddress->delete();
}
else if ($isPrevLocationAddressessLinksModified)
{
$result = $prevLocationAddress->save();
if (!$result->isSuccess())
{
throw new Main\SystemException(
implode(PHP_EOL, $result->getErrorMessages())
);
}
}
}
}
// Checking location-address links
self::cleanLocationAddressLinks($locationAddress, $typeId, $entityTypeId, $entityId);
// If, after verification, links remain, then clone the location-address
if ($locationAddress->hasLinks())
{
$locationAddress->setId(0);
}
// Set link to the current crm-address
$linkIdentifier = static::getLocationAddressLinkIndentifier($typeId, $entityTypeId, $entityId);
$locationAddress->setLinks(
new AddressLinkCollection(
[
new Address\AddressLink(
$linkIdentifier['entityId'],
$linkIdentifier['entityType']
)
]
)
);
$result = $locationAddress->save();
if (!$result->isSuccess())
{
throw new Main\SystemException(
implode(PHP_EOL, $result->getErrorMessages())
);
}
// Clearing lost links and addresses
// I did not want to do this in this way, but there are no others yet.
// Could be:
// Address\AddressLink::deleteByIdentifiers($linkIdentifier['entityType'], $linkIdentifier['entityId']);
/** @var $locationAddress Address */
foreach (
AddressService::getInstance()->findByLinkedEntity(
$linkIdentifier['entityId'],
$linkIdentifier['entityType']
) as $address
)
{
$modified = false;
/** @var $addressLinks Address\AddressLinkCollection */
$addressLinks = $address->getLinks();
/** @var $link Address\AddressLink */
foreach ($addressLinks as $offset => $link)
{
if ($address->getId() !== $locationAddress->getId()
&& $link->getAddressLinkEntityType() === $linkIdentifier['entityType']
&& $link->getAddressLinkEntityId() === $linkIdentifier['entityId'])
{
unset($addressLinks[$offset]);
$modified = true;
}
}
if (count($addressLinks) > 0)
{
if ($modified)
{
$address->setLinks($addressLinks);
$address->save();
}
}
else
{
$address->delete();
}
}
return $locationAddress;
}