TL;DR: What strategy can I follow to simplify request's if
hell?
I'm refering specifically to one of my github files. It's there to deal with different possible user actions. I'm trying to refactor it, but I'm not sure what's the best way. A small fraction of the code:
// The users returned from validating
if (!empty($_SESSION['service_connect']))
{
// If the service is a valid one
if (in_array($_SESSION['service'], $UMConfig->services))
{
// Include the needed files.
include $UMConfig->path . "/services/" . $_SESSION['service'] . "/verify.php";
}
}
// One service has set an email
if (isset($_SESSION['service_email']))
{
// The user is already in the database
if (Validate::is_user($_SESSION['service_email']))
{
// User is logged in
$_SESSION['email'] = $_SESSION['service_email'];
include 'actions/login.php';
}
// The user is not in the database and didn't submit anythign
elseif (empty($_POST))
{
// !POST
$UMLog = "We are trying to register you with a service.";
// Check if the popup has been submited or not
include 'actions/service_verified.php';
}
// The user has submitted something with POST
else {
include 'actions/register_service.php';
$UMLog = "Registering with " . $_SESSION['service'] . ".";
}
}
// No user was in the session but there's a user in the cookies
elseif (isset($_COOKIE['email']))
{
// The email is in the database
if (Validate::is_user($_COOKIE['email']))
{
// If there's a token
if (isset($_COOKIE['token']))
My idea right now is to simplify the code into smaller chunks and call them individually. This is the general idea of what I intend to do:
// Get what kind of action is needed
require 'request.php';
$action = request($_POST, $_SESSION, $_COOKIE);
if (file_exists($action_path = "actions/" . $action . ".php"))
include $action_path;
else
throw new Exception("Action was not valid: " . $action);
However, this only simplifies it slightly, as I'm only moving the if hell to 'request.php'. It has the advantage that testing is much easier in this way.
I have read how polymorphism can simplify some if
s, however I don't think it can be applied in this case. What strategy can I follow to simplify this if
hell?
EDIT: in case anyone's wondering, I have so many ifs because, besides the regular login/register, I allow users to login/register using an external service as facebook/google/etc, which requires more steps and makes it significantly more difficult.