PHP 控制台脚本 / 传递默认参数 / 重构 fopen() fread() fwrite() fclose()


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

我写了这个小脚本来交换 Ubuntu Gnome 的 Numix 主题上的颜色:

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

只要我传递两个参数,脚本就可以按预期工作。

  1. 如何设置参数的默认值?
  2. 我应该重构使用 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)
    )
);
?>

我将研究Loz Cherone的答案,这对我来说有点高级(这是我的第一个脚本),但我确实想出了更好的东西:

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

对于在 Ubuntu 上运行 Numix 主题的人来说,分享最终产品似乎是公平的。只需将脚本复制到.php文件中,然后以 sudo 身份运行即可。首先备份这两个文件。

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