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

I wrote this little script to change the Numix theme colors 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 as long as I pass two arguments.

  • How do I set default values ​​for arguments?
  • Should refactoring perhaps use file_put_contents ()?
+3


source to share


3 answers


<?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)
    )
);
?>

      



+3


source


I'm going to look into Loz Cherone's answer, which advanced a bit for me (this is my first script), but I came up with something better:



<?php
if (empty($argv[1])) {
    $oldColor = 'd64937';
    $newColor = 'f66153';
} elseif (empty($argv[2])) {
    echo "Please supply new color";
    return false;
} else {
    $oldColor = $argv[1];
    $newColor = $argv[2];
}
$path = '/usr/share/themes/Numix/gtk-3.0/gtk-dark.css';
$oldContents = file_get_contents($path);
$newContents = str_replace($oldColor, $newColor, $oldContents);
file_put_contents($path, $newContents);
?>

      

+1


source


Seems fair to share the final product for those out there working in Numix on Ubuntu. Just copy the script to a .php file and run it as sudo. First, back up two files.

<?php 

if (!empty($argv[1]) && empty($argv[2])) {
    echo "Please supply two colors for your very own custom color swap or zero colors for a slight improvement";
    return false;
}

$oldColor = !empty($argv[1]) ? $argv[1] : 'd64937';
$newColor = !empty($argv[2]) ? $argv[2] : 'f66153';
$file_1 = '/usr/share/themes/Numix/gtk-3.0/gtk-dark.css';
$file_2 = '/usr/share/themes/Numix/gtk-2.0/gtkrc';

file_put_contents(
    $file_1, 
    str_replace(
        $oldColor, 
        $newColor, 
        file_get_contents($file_1)
    )
);

file_put_contents(
    $file_2, 
    str_replace(
        $oldColor, 
        $newColor, 
        file_get_contents($file_2)
    )
);
?>

      

0


source







All Articles