简体   繁体   中英

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

I'm going to study Loz Cherone's answer which is a little advanced for me (this is my first script), but I did come 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);
?>

It seems only fair to share the final product for anyone out there running the Numix theme on Ubuntu. Just copy script into a .php file and run as sudo. Make a back up of the two files first.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM