Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting an if statement for readability

What's the best way to format this for readability?

if (strpos($file, '.jpg',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.gif',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.png',1) && file_exists("$thumbsdir/$file") == false) {
  createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
  fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}
like image 668
PHLAK Avatar asked Oct 20 '08 07:10

PHLAK


4 Answers

I'd extract the "is an image" logic into its own function, which makes the if more readable and also allows you to centralize the logic.

function is_image($filename) {
    $image_extensions = array('png', 'gif', 'jpg');

    foreach ($image_extensions as $extension) 
        if (strrpos($filename, ".$extension") !== FALSE)
            return true;

    return false;
}

if (is_image($file) && !file_exists("$thumbsdir/$file")) {
    createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
    fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}
like image 88
Neil Williams Avatar answered Nov 11 '22 09:11

Neil Williams


if ((strpos($file, '.jpg',1) ||
     strpos($file, '.gif',1) ||
     strpos($file, '.png',1))
    && file_exists("$thumbsdir/$file") == false)
{
  createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
  fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}
like image 36
Fire Lancer Avatar answered Nov 11 '22 08:11

Fire Lancer


function check_thumbnail($file)
{
    return (strpos($file, '.jpg',1) && file_exists("$thumbsdir/$file") == false ||
            strpos($file, '.gif',1) && file_exists("$thumbsdir/$file") == false ||
            strpos($file, '.png',1) && file_exists("$thumbsdir/$file") == false);
}

if (check_thumbnail ($file)) {
  createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
  fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}

After extracting the logic to a separate function, you can reduce the duplication:

function check_thumbnail($file)
{
    return (strpos($file, '.jpg',1) ||
            strpos($file, '.gif',1) ||
            strpos($file, '.png',1)) &&
           (file_exists("$thumbsdir/$file") == false);
}
like image 27
John Millikin Avatar answered Nov 11 '22 10:11

John Millikin


I would seperate the ifs as there is some repeating code in there. Also I try to exit a routine as early as possible:

if (!strpos($file, '.jpg',1) && !strpos($file, '.gif',1) && !strpos($file, '.png',1))
{
    return;
}

if(file_exists("$thumbsdir/$file"))
{
    return;
}

createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
like image 2
Rob Bell Avatar answered Nov 11 '22 08:11

Rob Bell