Created
April 13, 2023 20:20
-
-
Save atakde/ff3b078ef75c6e8bcee5374131acabdb to your computer and use it in GitHub Desktop.
Guard Clause Example In PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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