#!/usr/bin/env php getMessage()); exit_after_showing_msg($msg); } function show_help() { global $opts; global $app_name; exit_after_showing_msg($opts->getUsageMessage()); } function show_version() { global $app_name; global $app_version; exit_after_showing_msg(sprintf("%s %s\n", $app_name, $app_version)); } function exit_after_showing_msg($msg) { $stderr = fopen("php://stderr", "w"); fputs($stderr, $msg); fclose($stderr); exit; } function init_cli_app() { // デバッグに便利なようにエラーレポートを最強にする if (defined("E_STRICT")) { error_reporting(E_ALL | E_STRICT); } else { error_reporting(E_ALL); } set_time_limit(0); ini_set("track_errors", true); ini_set("html_errors", false); ini_set("implicit_flush", true); ini_set("magic_quotes_runtime", false); ini_set("memory_limit", -1); } // メイン関数 function main() { // PerlのGetopt::Longに似たフォーマットでオプションを指定。 // 連想配列のキーでオプションを指定し、 // 値と同名のグローバル変数にパース結果をセットする。 $optionlist = array( "b|bool|boolean" => "specify boolean parameter", "i|int|integer=i" => "specify integer parameter", "s|str|string=s" => "specify string parameter", "v|version" => "Print the version information and exit.", "h|help" => "Print this message and exit.", "debug" => "debug mode", ); init_cli_app(); global $opts; try { $opts = new Zend_Console_Getopt($optionlist); $opts->parse(); } catch (Zend_Console_Getopt_Exception $e) { show_error($e); } if ($opts->getOption("help")) { show_help(); } if ($opts->getOption("version")) { show_version(); } $target_files = $opts->getRemainingArgs(); if ($target_files === array()) { $target_files[] = "-"; // stdin } process_files($target_files); } function process_files($target_files) { global $opts; $integer = (int)$opts->getOption("integer"); $string = $opts->getOption("string"); if ($string === null) { $string = "byte(s)"; } foreach ($target_files as $target_file) { if ($target_file === "-") { $file_path = "php://stdin"; // - は標準入力として解釈 } elseif (!file_exists($target_file)) { // エラーくらい出すべきかも continue; } else { $file_path = $target_file; } $length = strlen(file_get_contents($file_path)); printf("%s: %d %s\n", $target_file, $length+$integer, $string); } } main();