Skip to content

Commit

Permalink
Save contact to database only if there are changes
Browse files Browse the repository at this point in the history
  • Loading branch information
raviks789 committed Jun 12, 2024
1 parent 2ae3713 commit e5a5c5f
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions library/Notifications/Web/Form/ContactForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,15 +161,14 @@ protected function assemble()
public function populate($values)
{
if ($values instanceof Contact) {
$formValues = [];
if (! isset($formValues['contact'])) {
$formValues['contact'] = [
$formValues = [
'contact' => [
'full_name' => $values->full_name,
'username' => $values->username,
'color' => $values->color,
'default_channel_id' => $values->default_channel_id
];
}
]
];

foreach ($values->contact_address as $contactInfo) {
$formValues['contact_address'][$contactInfo->type] = $contactInfo->address;
Expand All @@ -183,7 +182,12 @@ public function populate($values)
return $this;
}

public function addOrUpdateContact()
/**
* Add or update the contact and its corresponding contact addresses
*
* @return void
*/
public function addOrUpdateContact(): void
{
$contactInfo = $this->getValues();

Expand All @@ -195,17 +199,23 @@ public function addOrUpdateContact()
$addressFromDb = [];
if ($this->contactId === null) {
$this->db->insert('contact', $contact);

$this->contactId = $this->db->lastInsertId();
} else {
$this->db->update('contact', $contact, ['id = ?' => $this->contactId]);
$contactFromDb = (array) $this->db->fetchOne(
Contact::on($this->db)->withoutColumns(['id'])
->filter(Filter::equal('id', $this->contactId))
->assembleSelect()
);

$addressObjects = ContactAddress::on($this->db);
if (! empty(array_diff_assoc($contact, $contactFromDb))) {
$this->db->update('contact', $contact, ['id = ?' => $this->contactId]);
}

$addressObjects->filter(Filter::equal('contact_id', $this->contactId));
$addressObjects = (ContactAddress::on($this->db))
->filter(Filter::equal('contact_id', $this->contactId));

foreach ($addressObjects as $addressRow) {
$addressFromDb[$addressRow->type] = [$addressRow->id, $addressRow->address];
$addressFromDb[$addressRow->type] = [$addressRow->id, $addressRow->address];
}
}

Expand Down Expand Up @@ -256,7 +266,7 @@ private function insertOrUpdateAddress(string $type, array $addressFromForm, arr
);
}
} elseif (isset($addressFromDb[$type])) {
$this->db->delete('contact_address', ['id = ?' => $addressFromDb[$type][0]]);
$this->db->delete('contact_address', ['id = ?' => $addressFromDb[$type][0]]);;
}
}

Expand Down

0 comments on commit e5a5c5f

Please sign in to comment.