Challenge 1: Eliminate Exceptions Using the Either Monad
Test your knowledge by rewriting the given code without using any exceptions.
A code snippet is given below. It has an authenticateUser
function that authenticates the provided username
and password
with the stored username
and password
. If authentication fails, the program throws an exception.
Press + to interact
<?phpconst USER_DATA = ['password' => '$2y$10$gaGFDPMaVRS61ONjnkGQAODo64voLOUJK1AlokiZY2HY3QiPE4zHq','username' => 'kelly92','admin' => false,]; // valid password is trap_223function authenticateUser(string $username, string $password): array{if ($username !== USER_DATA['username']) {throw new Exception('Sorry, your username is invalid');}if (!password_verify($password, USER_DATA['password'])) {throw new Exception('Sorry, your password is invalid');}return USER_DATA;}authenticateUser('Some_User_Name','Some_Password');?>
Problem statement
Eliminate the exception in the snippet above by rewriting the authenticateUser
as a two-track Either monad-based function. You have to perform the following tasks to complete the challenge:
-
If the provided
username
is not valid, then the string returned by the function ...