mardi 30 novembre 2021

I'm trying to create a conditional PHP script that depends on whether an array is NOT empty. Is my logic here correct?

I had a CSS minifier written in PHP (it takes a *.css file, or files, and strips out a bunch of stuff). Today, I learned that if, for whatever reason my webhost disables allow_url_fopen, my script stops working if an absolute URL is specified (and I need an absolute URL here because different pages call this script as an include from different locations).

I decided to write a fallback using a simple if-else condition: because I read my CSS file(s) into an array, the script checks whether an array is not empty; if so, it does its thing; if the array happens to be empty, it outputs a conventional link to the un-minified stylesheet.

I'm not entirely confident in my logic here. Does the following make sense?

<?php
// CSS MINIFIER
// Read the CSS file
$cssFiles = array("https://foobar.com/styles.css");

if (!empty($cssFiles)) {
  // Cycle through the files
  $buffer = "";
  foreach ($cssFiles as $cssFile) {
    $buffer .= file_get_contents($cssFile);
  }

  // Remove comments
  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);

  // Remove spaces after colons
  $buffer = str_replace(': ', ':', $buffer);

  // Remove whitespace
  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);

  // Output the minified CSS string
  echo "<style>" . $buffer . "</style>";

} else {

  // If the array is empty, output a conventional CSS line
  echo '<link rel="stylesheet" href="https://foobar.com/styles.css">';

}
?>

Aucun commentaire:

Enregistrer un commentaire