Search code examples
phpfopenfwritefreadfclose

PHP console script / pass default arguments / refactoring fopen() fread() fwrite() fclose()


I wrote this tiny script to swap out colors on the Numix theme for Ubuntu Gnome:

<?php
$oldColor = $argv[1];
$newColor = $argv[2];
// defaults
// $oldColor = 'd64937';
// $newColor = 'f66153';

$path = '/usr/share/themes/Numix/gtk-3.0/gtk-dark.css';
$fileRead =  fopen($path, 'r');
$contents = fread($fileRead, filesize($path));
$newContents = str_replace($oldColor, $newColor, $contents);
$fileWrite =  fopen($path, 'w');
fwrite($fileWrite, $newContents);
fclose($fileWrite);
?>

The script works as intended so long as I pass the two arguments.

  1. How do I set defaults for the arguments?
  2. Should I refactor maybe making use of file_put_contents()?

Solution

  • <?php 
    // How do I set defaults for the arguments?
    $oldColor = !empty($argv[1]) ? $argv[1] : 'd64937';
    $newColor = !empty($argv[2]) ? $argv[2] : 'f66153';
    $file = '/usr/share/themes/Numix/gtk-3.0/gtk-dark.css';
    
    // Your choice whether its cleaner, I think so.
    file_put_contents(
        $file, 
        str_replace(
            $oldColor, 
            $newColor, 
            file_get_contents($file)
        )
    );
    ?>