Skip to content

Instantly share code, notes, and snippets.

@atakde
Created April 13, 2023 20:20
Show Gist options
  • Select an option

  • Save atakde/ff3b078ef75c6e8bcee5374131acabdb to your computer and use it in GitHub Desktop.

Select an option

Save atakde/ff3b078ef75c6e8bcee5374131acabdb to your computer and use it in GitHub Desktop.
Guard Clause Example In PHP
<?php
function saveProfile($data) {
$errors = [];
if (!isset($data['email'])) {
$errors[] = 'Email address is required';
} else {
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email address is not valid';
}
}
if (count($errors) > 0) {
return ['success' => false, 'errors' => $errors];
}
// Save the profile to the database
// ...
return ['success' => true];
}
// How about like that?
function saveProfile($data) {
$errors = [];
if (!isset($data['email'])) {
$errors[] = 'Email address is required';
return ['success' => false, 'errors' => $errors]; // guard clause for missing email
}
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email address is not valid';
return ['success' => false, 'errors' => $errors]; // guard clause for invalid email
}
// Save the profile to the database
// ...
return ['success' => true];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment