adds new relations.

@param Contact $contact
@param array $data
164089
public function addNewContactRelations($contact, $data)
    {
        // urls
        $urls = $this->getProperty($data, 'urls');
        if (!empty($urls)) {
            foreach ($urls as $urlData) {
                $this->addUrl($contact, $urlData);
            }
            $this->setMainUrl($contact);
        }

        //faxes
        $faxes = $this->getProperty($data, 'faxes');
        if (!empty($faxes)) {
            foreach ($faxes as $faxData) {
                $this->addFax($contact, $faxData);
            }
            $this->setMainFax($contact);
        }

        // Social media profiles.
        $socialMediaProfiles = $this->getProperty($data, 'socialMediaProfiles');
        if (!empty($socialMediaProfiles)) {
            foreach ($socialMediaProfiles as $socialMediaProfileData) {
                $this->addSocialMediaProfile($contact, $socialMediaProfileData);
            }
        }

        // emails
        $emails = $this->getProperty($data, 'emails');
        if (!empty($emails)) {
            foreach ($emails as $emailData) {
                $this->addEmail($contact, $emailData);
            }
            $this->setMainEmail($contact);
        }

        // phones
        $phones = $this->getProperty($data, 'phones');
        if (!empty($phones)) {
            foreach ($phones as $phoneData) {
                $this->addPhone($contact, $phoneData);
            }
            $this->setMainPhone($contact);
        }

        // addresses
        $addresses = $this->getProperty($data, 'addresses');
        if (!empty($addresses)) {
            foreach ($addresses as $addressData) {
                $address = $this->createAddress($addressData, $isMain);
                $this->addAddress($contact, $address, $isMain);
            }
        }
        // set main address (if it was not set yet)
        $this->setMainForCollection($this->getAddressRelations($contact));

        // notes
        $notes = $this->getProperty($data, 'notes');
        if (!empty($notes)) {
            foreach ($notes as $noteData) {
                $this->addNote($contact, $noteData);
            }
        }

        // handle tags
        $tags = $this->getProperty($data, 'tags');
        if (!empty($tags)) {
            foreach ($tags as $tag) {
                $this->addTag($contact, $tag);
            }
        }

        // process details
        if (null !== $this->getProperty($data, 'bankAccounts')) {
            $this->processBankAccounts($contact, $this->getProperty($data, 'bankAccounts', []));
        }
    }
1021828
protected function updateRelation($relationsData)
    {
        foreach ($relationsData as $name => $values) {
            if (!method_exists($this->model, $name)) {
                continue;
            }

            $relation = $this->model->$name();

            $oneToOneRelation = $relation instanceof \Illuminate\Database\Eloquent\Relations\HasOne
                || $relation instanceof \Illuminate\Database\Eloquent\Relations\MorphOne;

            $prepared = $this->prepareUpdate([$name => $values], $oneToOneRelation);

            if (empty($prepared)) {
                continue;
            }

            switch (get_class($relation)) {
                case \Illuminate\Database\Eloquent\Relations\BelongsToMany::class:
                case \Illuminate\Database\Eloquent\Relations\MorphToMany::class:
                    if (isset($prepared[$name])) {
                        $relation->sync($prepared[$name]);
                    }
                    break;
                case \Illuminate\Database\Eloquent\Relations\HasOne::class:

                    $related = $this->model->$name;

                    // if related is empty
                    if (is_null($related)) {
                        $related = $relation->getRelated();
                        $related->{$relation->getForeignKeyName()} = $this->model->{$this->model->getKeyName()};
                    }

                    foreach ($prepared[$name] as $column => $value) {
                        $related->setAttribute($column, $value);
                    }

                    $related->save();
                    break;
                case \Illuminate\Database\Eloquent\Relations\MorphOne::class:
                    $related = $this->model->$name;
                    if (is_null($related)) {
                        $related = $relation->make();
                    }
                    foreach ($prepared[$name] as $column => $value) {
                        $related->setAttribute($column, $value);
                    }
                    $related->save();
                    break;
                case \Illuminate\Database\Eloquent\Relations\HasMany::class:
                case \Illuminate\Database\Eloquent\Relations\MorphMany::class:

                    foreach ($prepared[$name] as $related) {
                        $relation = $this->model()->$name();

                        $keyName = $relation->getRelated()->getKeyName();

                        $instance = $relation->findOrNew(array_get($related, $keyName));

                        if ($related[static::REMOVE_FLAG_NAME] == 1) {
                            $instance->delete();

                            continue;
                        }

                        array_forget($related, static::REMOVE_FLAG_NAME);

                        $instance->fill($related);

                        $instance->save();
                    }

                    break;
            }
        }
    }
1359088
public void setContacts(java.util.Collection<ContactData> contacts) {
        if (contacts == null) {
            this.contacts = null;
            return;
        }

        this.contacts = new java.util.ArrayList<ContactData>(contacts);
    }
1309758
public function addEvent(
        ContactSource $contactSource = null,
        $type = null,
        $contact = null,
        $logs = null,
        $message = null
    ) {
        $event = new EventEntity();
        $event->setContactSource($contactSource)
            ->setDateAdded(new \DateTime())
            ->setType($type);
        if ($contact) {
            $event->setContact($contact);
        }
        if (!$logs) {
            // [ENG-418] Exception report - logs can not be null.
            $logs = '';
        }
        $event->setLogs($logs);

        if ($message) {
            $event->setMessage($message);
        }

        $this->getEventRepository()->saveEntity($event);
    }
460018
public function updateContact(Contact $contact)
    {
        return $this->httpHelper->patch("accounts/" . $contact->getAccountID() . "/contacts/" . $contact->getContactID(), [
            'name' => $contact->getName(),
            'role' => $contact->getRole(),
            'email_address' => $contact->getEmailAddress(),
            'phone_numbers' => $contact->getPhoneNumbersFormatted(),
        ]);
    }
484554
public function prepareContacts($contacts)
    {
        $retContacts = array();

        foreach ($contacts as &$contact) {
            $info = array(
                'image' => null,
                'first_name' => null,
                'last_name' => null,
                'work_title' => null,
                'administration_unit' => null,
                'email' => null,
                'phone' => null,
                'social_media' => null,
                'address' => null,
                'visiting_address' => null,
                'opening_hours' => null
            );

            switch ($contact['acf_fc_layout']) {
                case 'custom':
                    $info = apply_filters('Modularity/mod-contacts/contact-info', array(
                        'image'               => $contact['image'],
                        'first_name'          => $contact['first_name'],
                        'last_name'           => $contact['last_name'],
                        'work_title'          => $contact['work_title'],
                        'administration_unit' => $contact['administration_unit'],
                        'email'               => strtolower($contact['email']),
                        'phone'               => $contact['phone_numbers'],
                        'social_media'        => $contact['social_media'],
                        'address'             => $contact['address'],
                        'visiting_address'    => $contact['visiting_address'],
                        'opening_hours'       => $contact['opening_hours'],
                        'other'               => $contact['other']
                    ), $contact, $contact['acf_fc_layout']);
                    break;

                case 'user':
                   $info = apply_filters('Modularity/mod-contacts/contact-info', array(
                        'id'                  => $contact['user']['ID'],
                        'image'               => null,
                        'first_name'          => $contact['user']['user_firstname'],
                        'last_name'           => $contact['user']['user_lastname'],
                        'work_title'          => null,
                        'administration_unit' => null,
                        'email'               => strtolower($contact['user']['user_email']),
                        'phone'               => null,
                        'address'             => $contact['address'],
                        'visiting_address'    => null,
                        'opening_hours'       => null
                    ), $contact, $contact['acf_fc_layout']);
                    break;
            }

            //Parse thumbnail id's
            $info['thumbnail'] = false;
            if (isset($info['image']) && !empty($info['image']) && isset($info['image']['id']) && is_numeric($info['image']['id'])) {
                $info['thumbnail'] = wp_get_attachment_image_src(
                    $info['image']['id'],
                    apply_filters(
                        'Modularity/image/contact',
                        municipio_to_aspect_ratio('1:1', array(400, 400)),
                        $this->args
                    )
                );
            }

            //Parse directly inputted url:s
            if (isset($info['image']) && filter_var($info['image'], FILTER_VALIDATE_URL) !== false) {
                $info['thumbnail'] = array($info['image'], 250, 250, false);
            }

            //Create full name
            $info['full_name'] = trim($info['first_name'] . ' ' . $info['last_name']);

            //Adds chosen user meta data or removes the field completely and make it unvisible.
            if (get_field('advaced_mode', $this->ID) == "1") {

                if (get_field('profile_image', $this->ID) == "1") {
                    $info['thumbnail'][0] = get_user_meta($contact['user']['ID'], "user_profile_picture", true);
                } else {
                    unset($info['thumbnail']);
                }

                if (get_field('other_user_info', $this->ID) == "1") {
                    $info['other'] = get_user_meta($contact['user']['ID'], "user_about", true);
                } else {
                    unset($info['other']);
                }

                if (get_field('work_title', $this->ID) == "1") {
                    $info['work_title'] = get_user_meta($contact['user']['ID'], "user_work_title", true);
                } else {
                    unset($info['work_title']);
                }

                if (get_field('email', $this->ID) != "1") {
                    unset($info['email']);
                }

                if (get_field('address', $this->ID) != "1") {
                    unset($info['address']);
                }

                if (get_field('phone', $this->ID) != "1") {
                    unset($info['phone']);
                }
            }

            $retContacts[] = $info;
        }

        return $retContacts;
    }
1326067
public function addContacts($data)
	{
		$this->data = $data;
		if(empty($this->data['name']))
			$this->data['name'] = 'NoName';
			//die('Не заполнено имя контакта');
		$fields 				= array('POSITION','PHONE');
		$custom_fields 	= $this->checkCustomFields($fields, self::TYPE_CONTACTS);
		$query					= array('query' => $data['phone']);
		$out 						= $this->listData($query, self::TYPE_CONTACTS);
		if($out)
			die(); //die('Такой контакт уже существует в amoCRM');

		$set['request']['contacts']['add'][] = array(
			'name' => $data['name'],
			'custom_fields' => array(
				array(
					'id' => $custom_fields['PHONE'],
					'values' => array(
						array(
							'value' => $data['phone'],
							'enum' => 'WORK'
							)
						)
					)
				)
			);

		$response 	= $this->addData($set, $type = self::TYPE_CONTACTS);
		$response 	= json_decode($out,true);
		$response 	=	$response['response']['contacts']['add'];
		$output			= 'ID добавленных контактов:' . PHP_EOL;
		foreach($response as $v){
			if(is_array($v))
				$output .= $v['id'] . PHP_EOL;
			return $output;
		}
	}
68738
public function addRelation($relation)
    {
        $relations = $this->getRelations();
        array_push($relations, $relation);
        $this->setRelations($relations);
    }
104068
public function addContextContact(Contact $contact = null)
    {
        if (!$contact) {
            return $this;
        }
        $context = [];
        $conType = [];

        // Append contact ID.
        $contactId     = (int) $contact->getId();
        $context['id'] = isset($contactId) ? $contactId : null;
        $conType['id'] = 'number';

        // Append contact owner data.
        $owner                         = $contact->getOwner();
        $context['owner']              = [];
        $context['owner']['id']        = $owner ? $owner->getId() : null;
        $conType['owner']['id']        = 'number';
        $context['owner']['username']  = $owner ? $owner->getUsername() : null;
        $context['owner']['firstName'] = $owner ? $owner->getFirstName() : null;
        $context['owner']['lastName']  = $owner ? $owner->getLastName() : null;
        $context['owner']['email']     = $owner ? $owner->getEmail() : null;

        // Append points value.
        $points            = $contact->getPoints();
        $context['points'] = isset($points) ? $points : null;
        $conType['points'] = 'number';

        // Append IP Addresses.
        $context['ipAddresses'] = [];
        $context['ip']          = null;
        foreach ($contact->getIpAddresses()->toArray() as $ip => $value) {
            $context['ipAddresses'][] = $ip;
            $context['ip']            = $ip;
        }

        // Add Identified date.
        /** @var \DateTime $dateIdentified */
        $dateIdentified            = $contact->getDateIdentified();
        $context['dateIdentified'] = $dateIdentified ? $this->dateFormatHelper->format($dateIdentified) : null;
        $conType['dateIdentified'] = 'datetime';

        // Add Modified date.
        /** @var \DateTime $dateModified */
        $dateModified            = $contact->getDateModified();
        $context['dateModified'] = $dateModified ? $this->dateFormatHelper->format($dateModified) : null;
        $conType['dateModified'] = 'datetime';

        // Add DNC data.
        $context['doNotContacts'] = [];
        $context['doNotContact']  = false;
        if ($contactId && $this->needsDncData) {
            /** @var \Mautic\LeadBundle\Model\DoNotContact $record */
            foreach ($contact->getDoNotContact() as $record) {
                $context['doNotContacts'][$record->getChannel()]           = [
                    'comments' => $record->getComments(),
                    'reason'   => $record->getReason(),
                    'exists'   => true,
                ];
                $conType['doNotContacts'][$record->getChannel()]['exists'] = 'boolean';
                $context['doNotContact']                                   = true;
            }
            $conType['doNotContact'] = 'boolean';
        }

        // Add UTM data.
        $context['utm'] = [
            'campaign'   => null,
            'content'    => null,
            'medium'     => null,
            'query'      => null,
            'referrer'   => null,
            'remoteHost' => null,
            'source'     => null,
            'term'       => null,
            'url'        => null,
            'userAgent'  => null,
        ];
        if ($contactId && $this->needsUtmData) {
            $utmTags            = $this->utmSourceHelper->getSortedUtmTags($contact);
            $context['utmTags'] = [];
            if ($utmTags) {
                foreach ($utmTags as $utmTag) {
                    $tags                 = [
                        'campaign'   => $utmTag->getUtmCampaign(),
                        'content'    => $utmTag->getUtmContent(),
                        'medium'     => $utmTag->getUtmMedium(),
                        'query'      => $utmTag->getQuery(),
                        'referrer'   => $utmTag->getReferer(),
                        'remoteHost' => $utmTag->getRemoteHost(),
                        'source'     => $utmTag->getUtmSource(),
                        'term'       => $utmTag->getUtmTerm(),
                        'url'        => $utmTag->getUrl(),
                        'userAgent'  => $utmTag->getUserAgent(),
                    ];
                    $context['utmTags'][] = $tags;
                    // Override the {{ utm.values }} to be the latest non-empty version of each found.
                    foreach ($tags as $key => $value) {
                        if (!empty($value)) {
                            $context['utm'][$key] = $value;
                        }
                    }
                }
            }
        }

        // Add Device data.
        $context['device'] = [
            'name'        => null,
            'brand'       => null,
            'model'       => null,
            'fingerprint' => null,
            'trackingId'  => null,
            'os'          => [
                'osName'      => null,
                'osShortName' => null,
                'osVersion'   => null,
                'osPlatform'  => null,
            ],
        ];
        if ($contactId && $this->needsDeviceData) {
            /** @var LeadDeviceRepository $deviceRepo */
            $deviceRepo = $this->contactModel->getDeviceRepository();
            $devices    = $deviceRepo->getEntities(
                [
                    'limit'            => 1,
                    'orderBy'          => $deviceRepo->getTableAlias().'.id',
                    'orderByDir'       => 'DESC',
                    'filter'           => [
                        'force' => [
                            [
                                'column' => 'IDENTITY('.$deviceRepo->getTableAlias().'.lead)',
                                'expr'   => 'eq',
                                'value'  => $contactId,
                            ],
                        ],
                    ],
                    'ignore_paginator' => true,
                ]
            );
            if ($devices && $device = reset($devices)) {
                $context['device'] = [
                    'name'        => $device->getDevice(),
                    'brand'       => $device->getDeviceBrand(),
                    'model'       => $device->getDeviceModel(),
                    'fingerprint' => $device->getDeviceFingerprint(),
                    'trackingId'  => $device->getTrackingId(),
                    'os'          => [
                        'osName'      => $device->getDeviceOsName(),
                        'osShortName' => $device->getDeviceOsShortName(),
                        'osVersion'   => $device->getDeviceOsVersion(),
                        'osPlatform'  => $device->getDeviceOsPlatform(),
                    ],
                ];
            }
        }

        $fieldGroups = $contact->getFields();
        if ($fieldGroups) {
            foreach ($fieldGroups as $fgKey => $fieldGroup) {
                foreach ($fieldGroup as $fkey => $field) {
                    $value = isset($field['value']) ? $field['value'] : '';
                    $type  = isset($field['type']) ? $field['type'] : '';
                    if ('' !== $value && in_array($type, ['datetime', 'date', 'time'])) {
                        // Soft support for labels/values as dates/times.
                        @$newValue = $this->dateFormatHelper->format($value);
                        if (null !== $newValue && '' !== $newValue) {
                            $value = $newValue;
                        }
                    }
                    $context[$fkey] = $value;
                    if ($type) {
                        $conType[$fkey] = $type;
                    }
                }
            }
        }

        // Support multiple contacts in the future if needed by uncommenting a bit here.
        // $contacts = !empty($this->context['contacts']) ? $this->context['contacts'] : [];

        // Set the context to this contact.
        $this->sanitizeContext($context);
        $this->context = array_merge($this->context, $context);
        $this->conType = array_merge($this->conType, $conType);

        // Support multiple contacts for future batch processing.
        // $this->context['contacts']                 = $contacts;
        // $this->context['contacts'][$context['id']] = $context;

        return $this;
    }
621334
public static function createProcessedContactFromStdClassArray(array $contactArray): ClassValidationArray
    {
        $contacts = new ClassValidationArray();
        foreach ($contactArray as $c) {
            $contacts[] = self::createProcessedContactFromStdClass($c);
        }
        return $contacts;
    }
940038
public function addContact(array $attributes)
    {
        $attributes = $this->loadContactAttributes($attributes);

        return $this->contacts()->updateOrCreate($attributes);
    }
632025
public function setContact(Contact $contact, $isDirty = true)
    {
        $this->contactId = $contact->id;
        $this->setDirtyState($isDirty, 'contactId');
        $properties = array(
            'address1',
            'address2',
            'attention',
            'city',
            'companyName',
            'country',
            'customerId',
            'firstname',
            'lastname',
            'zipcode',
        );
        foreach ($properties as $property) {
            $this->$property = $contact->$property;
            $this->setDirtyState($isDirty, $property);
        }
        return $this;
    }
794576
protected function addFax($contact, $faxData)
    {
        $faxEntity = 'SuluContactBundle:Fax';

        $faxType = $this->em
            ->getRepository(self::$faxTypeEntityName)
            ->find($faxData['faxType']['id']);

        if (isset($faxData['id'])) {
            throw new EntityIdAlreadySetException($faxEntity, $faxData['id']);
        } elseif (!$faxType) {
            throw new EntityNotFoundException(self::$faxTypeEntityName, $faxData['faxType']['id']);
        } else {
            $fax = new Fax();
            $fax->setFax($faxData['fax']);
            $fax->setFaxType($faxType);
            $this->em->persist($fax);
            $contact->addFax($fax);
        }
    }
1369129
protected function touchRelated(): void
	{
		foreach($this->getRelationsToTouch() as $touch)
		{
			$touch = explode('.', $touch);

			$relation = $this->{array_shift($touch)}();

			foreach($touch as $nested)
			{
				$related = $relation->first();

				if($related === false)
				{
					continue 2;
				}

				$relation = $related->$nested();
			}

			$relation->update([$relation->getModel()->getUpdatedAtColumn() => null]);
		}
	}
485419
public function update(Contact $contact): Contact
    {
        $id = $contact->getId();

        $contact->setId(null);

        $response = $this->client->put($this->prepareUrlForKey('update-contact', ['id' => $id]), [], $contact->jsonSerialize());
        $responseData = $response->getDecodedBody();

        return new Contact($responseData);
    }
3431
public function deleteContact(Contact $contact)
    {
        if ($this !== $contact->contactable()->first())
            return false;

        return $contact->delete();
    }
487712
public function saveContact(Contact $contactMessage)
    {
        /* @var $mapper \SspContact\Mapper\Contact */
        $mapper = $this->getServiceLocator()->get('contact_mapper');
        $mapper->insert($contactMessage);
    }