Skip to content

Commit

Permalink
refactor save()
Browse files Browse the repository at this point in the history
- set $conn to null before exiting function
- no need to use toArray()
  • Loading branch information
creme332 committed May 8, 2024
1 parent 81ff491 commit bc61346
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions src/models/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public function deleteUser(): void
public function save(): bool
{
// if attributes are invalid, exit
if (count($this->validate()) > 0) {
if (!empty($this->validate())) {
return false;
}

Expand All @@ -129,37 +129,36 @@ public function save(): bool
return false;
}

// get data to be inserted to user table
$user_data = $this->toArray();
unset($user_data['user_id']);
unset($user_data['street']);
unset($user_data['city']);
unset($user_data['district_id']);

// start transaction
$conn = self::connect();
$conn->beginTransaction();

// perform insertion to user table
$query = <<< EOL
INSERT INTO user(email, first_name, password, phone_no, last_name)
VALUES(:email, :first_name, :password, :phone_no, :last_name);
INSERT INTO user(email, first_name, password, phone_no, last_name)
VALUES(:email, :first_name, :password, :phone_no, :last_name);
EOL;
$stm = $conn->prepare($query);
$success = $stm->execute($user_data);

$success = $stm->execute([
'email' => $this->email,
'first_name' => $this->first_name,
'password' => $this->password,
'phone_no' => $this->phone_no,
'last_name' => $this->last_name
]);

if (!$success) {
$conn->rollBack();
$conn = null;
return false;
}

$this->user_id = (int)$conn->lastInsertId();

// perform insertion to client table
$query = <<< EOL
INSERT INTO client(user_id, street, city, district_id)
VALUES(:user_id, :street, :city, :district_id);
INSERT INTO client(user_id, street, city, district_id)
VALUES(:user_id, :street, :city, :district_id);
EOL;
$stm = $conn->prepare($query);
$success = $stm->execute([
Expand All @@ -171,6 +170,7 @@ public function save(): bool

if (!$success) {
$conn->rollBack();
$conn = null;
return false;
}

Expand Down

0 comments on commit bc61346

Please sign in to comment.