PHP Classes

File: Getopt_Util.php

Recommend this page to a friend!
  Classes of Leandro Lucarella   Getopt_Util   Getopt_Util.php   Download  
File: Getopt_Util.php
Role: Class source
Content type: text/plain
Description: The main class file.
Class: Getopt_Util
Command Line Options Parsing Utility
Author: By
Last change:
Date: 22 years ago
Size: 19,317 bytes
 

Contents

Class file image Download
<?php // $Id: Getopt_Util.php v0.7.0 /* vim: set expandtab tabstop=3 shiftwidth=3: */ // +----------------------------------------------------------------------+ // | | // | Getopt_Util es una clase para simplificar el manejo de opciones de | // | comando para hacer más simple el desarrollo de scripts para | // | consola en php. | // | -------------------------------------------------------------------- | // | Getopt_Util.php is a class to make easy the management of command | // | options to simplify development of shell scripts with php. | // | | // +----------------------------------------------------------------------+ // | Instalación: | // | La instalación recomendada es copiar este script al path que tiene | // | configurado en su php.ini. Este script se basa en el 'Getopt.php' | // | que viene en cualquier distribución de php. Para que funcione debe | // | tener en el path del php.ini el directorio con las extensiones del | // | php, en el que se encuentra el script 'Getopt.php'. Este directorio| // | por lo general es <php>/lib (donde <php> es el directorio en el | // | que instaló el php). Una buena idea es poner este script en | // | <php>/lib/Console, en donde se encuentra 'Getopt.php'. También es | // | necesario que el php este compilado como inteprete cgi-bin (de | // | otra forma tampoco tendría sentido esta clase). | // | Este script solo fue probado en php 4.0.5. Es probable que | // | funcione en veriones anteriores, pero no menores a la 4.0.x porque | // | usa funciones que estan solo disponible en estas ultimas. Casi | // | seguramente funcionara en versiones porteriores a la 4.0.5. | // | IMPORTANTE: El script Getopt.php que viene con el php 4.0.5 tiene | // | un pequeño bug. Si tiene problemas al usar este script | // | envieme un e-mail a luca@linuxmendoza.org.ar para | // | recibir una copia de Getopt.php corregido. | // | -------------------------------------------------------------------- | // | Instalation: | // | The recomended instalation it to copy this script into the path | // | for scripts thar you have in your php.ini file. This script is | // | based on 'Getopt.php' script that comes with any php distribution. | // | For this script to work you must have the standar php lib path on | // | on your php.ini file. The usual location of the standar libs of | // | php is <php>/lib, where <php> is the directory where you have | // | installed php. It's a good idea to copy this script to | // | <php>/lib/Console, where 'Getopt.php' script is. You must have php | // | compiled as a cgi-bin interpreter (in other case this script is | // | meaningless). | // | This script was only tested on php 4.0.5. It's possible that it | // | works on previous versions, but there is no way to work under | // | versions less than 4.0.x, because it uses some new functions of | // | this versions. It's almost sure that it will work in next versions.| // | IMPORTANT: The 'Getopt.php' script that is distributed with php | // | 4.0.5 has a little bug. If you have problems using this | // | script with this version, e-mail me to | // | luca@linuxmendoza.org.ar to get a working copy of | // | 'Getopt.php'. | // | | // +----------------------------------------------------------------------+ // | | // | Modo de uso: | // | El uso de esta clase es prácticamente intuitivo. Al comienzo de | // | cada función (en este archivo) se encuentra una breve descripción | // | de su sintaxis y objetivo. Sólo queda mencionar el formato del | // | array que hay que pasarle al constructor. La estructura de dicho | // | array es la siguiente: | // | | // | $opt["id"] donde "id" es el identificador de la opción que se | // | utilizará en las llamadas a selected( $id ) o | // | getopt( $id ). Cada "id" a su vez es un array. | // | | // | $opt["id"]["short"] = aquí se almacena el caracter de la opción | // | corta. | // | | // | $opt["id"]["long"] = aquí se almacena el string de la opción | // | larga. | // | | // | $opt["id"]["desc"] = aquí se almacena el string con la | // | la descripción, que se utilizará para | // | generar un mensaje de ayuda automático. | // | | // | $opt["id"]["opt"] = aquí se almacena el tipo de argumento que | // | puede utilizarse con esta opción: | // | 'n': No soporta argumento. | // | 'y': Necesita de un argumento. | // | 'o': El argumento es opcional. | // | | // | $opt["id"]["optstr"]= aquí se almacena el texto que se pondrá en | // | la ayuda cuando la opcion este presente. | // | | // | NOTA: Tanto la opcion corta como la larga deben ser UNICAS. | // | -------------------------------------------------------------------- | // | Usage: | // | The use of this class is very intuitive. At the beginning of each | // | function, there is a small description of what it does and the | // | arguments it needs. The only thing I have to say here is the | // | structure of the array you have to pass to the constructor. It | // | structure is this: | // | | // | $opt["id"] where "id" is the identifier of the option that you | // | will use when you call to selected( $id ) or | // | getopt( $id ). Each "id" is an array too. | // | | // | $opt["id"]["short"] = here you must specify a char for the short | // | option. | // | | // | $opt["id"]["long"] = here you must specify a string for the | // | long option. | // | | // | $opt["id"]["desc"] = here you must specify a string with the | // | description, that will be used to | // | automatically generate a help message. | // | | // | $opt["id"]["opt"] = here you must specify the type or | // | argument this option can have: | // | 'n': It doesn't supports an argument | // | 'y': It needs an argument. | // | 'o': The argument is optional. | // | | // | $opt["id"]["optstr"]= here you must specify the string to use in | // | the help, when the option is present. | // | | // | NOTE: The short and long options must be UNIQUES. | // | | // +----------------------------------------------------------------------+ // | Copyleft 2001 Luca - Soft | // +----------------------------------------------------------------------+ // | | // | Este programa se encuentra bajo los términos de la licencia pública | // | de GNU: GPL. Para leer esta licencia puede dirigirse a: | // | http://www.gnu.org | // | -------------------------------------------------------------------- | // | This program is under GNU GPL public license. If you want to get | // | more information or a copy go to: | // | http://www.gnu.org | // | | // +----------------------------------------------------------------------+ // | Autor: Leandro Lucarella <luca@linuxmendoza.org.ar> | // +----------------------------------------------------------------------+ // Requiere la libreria para manejo de argumentos de línea de comandos. require_once "Console/Getopt.php"; class Getopt_Util extends Console_Getopt { var $classname = "Getopt_Util"; var $opts; // Opciones disponibles, sus descripciones y posibles parámetros var $args; // Argumentos var $error; // Almacena el ultimo error (como objeto) /* * Constructor. * * @param $argv array Array con los parametros de comando (usualmente el array $argv). * Array with the command line parameters (usually $argv array) * @param $opts array Array con las opciones soportadas y sus descripciones (debe tener un formato especial). * Array with the supported options and their descriptions (with the special format named) * * @access public * */ function Getopt_Util( $argv, $opts ) { if ( !is_array( $opts ) ) { $this->opts = array(); $this->args = array(); $this->error = new Getopt_Error( "No se pasó un array de opciones.\n" ); } else { $this->opts = $opts; if ( $is_argv ) unset( $argv[0] ); $getopt = $this->getopt( $argv, $this->_makeshortopt(), $this->_makelongopt() ); if ( is_array( $getopt ) ) { // Chequea errores. $this->args = $getopt[1]; $this->_proccessopt( $getopt[0] ); $this->error = false; } elseif ( is_object( $getopt ) ) { // Hubo un error $this->error = $getopt; } else { $this->error = new Getopt_Error( "Error desconocido\n" ); } } } /* * Verifica que una opción esté presente (seleccionada por el usuario). * Verifies that a option is present (selected by the user). * * @param $opt string ID de la opción a verificar (debe existir la opción en la descripción). * ID of the option to verify (the option must exist en the description array). * * @returns boolean true si la opción está presente. * * @access public * */ function selected( $id ) { return $this->opts[$id]["selected"]; // true si está seteada "option". } /* * Obtiene la opción de una opción. * Gets the option of an option. * * @param $opt string ID de la opción de la cual se quiere obtener la opción (debe estar presente la opción). * ID of the option to get the option of (the option must be present). * * @returns string La opción de esa opción (vacío si no soporta opciones o si no las tiene). * The option's option (empty if it doesn't supports options) * * @access public * */ function getoptopt( $id ) { return $this->opts[$id]["option"]; } /* * Obtiene un argumento en particular. * Gets a particular argument. * * @param $num int Número del argumento a obtener. * The number of the argument to get. * * @returns string El argumento en la posición $num. * The argument in the $num position. * * @access public * */ function getarg( $num ) { return $this->args[$num]; } /* * Obtiene todos los argumentos. * Gets all the arguments. * * @returns array Array con todos los argumentos. * Array with all the arguments. * * @access public * */ function getargs() { return $this->args; } /* * Genera un mensaje de ayuda de las opciones. * Generates a help message with the options. * * @param $wide int Ancho de la ayuda. * Help width. * * @returns string El strig con el mensaje de ayuda. * The string with the help message. * * @access public * */ function gethelp( $wide = 78 ) { $str_opt = '$str = " " . ( !empty( $opt["short"] ) ? ("-" . $opt["short"]) : " " )' . // Agrega opcion corta ' . ( !empty( $opt["short"] ) && !empty( $opt["long"] ) ? ", " : " " )' . // Agrega la coma "," ' . ( !empty( $opt["long"] ) ? ("--" . $opt["long"]) : " " )' . // Agrega opción larga ' . ( ($opt["opt"] == "y") ? ("=" . $opt["optstr"]) : "" )' . // Agrega opcion de opcion ' . ( ($opt["opt"] == "o") ? ("[=" . $opt["optstr"] . "]") : "" ) . " ";'; // Agrega opcion de opcion (opcional) $help = ""; $max = 0; foreach ( $this->opts as $opt ) { // Calcula el largo (maximo) de las opciones eval( $str_opt ); // Me deja en $str la "cabecera" $len = strlen( $str ); if ( $len > $max ) $max = $len; } foreach ( $this->opts as $opt ) { eval( $str_opt ); // Me deja en $str la "cabecera". $str = str_pad( $str, $max ); // Agrega espacios finales. if ( strlen( $str . $opt["desc"] ) > $wide ) { // Si es muy ancho, wordwrapea. $tmp = wordwrap( $str . $opt["desc"], $wide, "\n", 1 ); // Separa con wordwrap la primera linea. list( $head, $body ) = explode( "\n", $tmp, 2 ); // Extrae sólo esa primera línea con explode. $body = substr( $str . $opt["desc"], strlen( $head ) + 1 ); // Extrae el verdadero body (sin wordwrap). $tmp = wordwrap( $body, $wide - $max - 2, "\n", 1 ); // Wordwrapea el body con el margen (el 2 es para dejar un margen). $lines = explode( "\n", $tmp ); // Separa las lineas del body. foreach ( $lines as $key => $line ) { $lines[$key] = str_repeat( " ", $max + 2 ) . $line; // Agrega los espacios faltantes a cada linea } $help .= $head . "\n" . implode( "\n", $lines ) . "\n"; // Agrega TODO al string de ayuda. } else { $help .= $str . $opt["desc"] . "\n"; // Agrega TODO al string de ayuda. } } return $help; } /* * Genera una lista con las opciones cortas para pasarle a getopt. * It generates a list with the short options to pass to getopts. * * @returns string El strig con el formato necesario para pasarselo a getopt. * The string with the necesary format to pass to getopts. * * @access private * */ function _makeshortopt() { $shortopt = ""; foreach ( $this->opts as $opt ) // opcion corta + si opcion = y => agregar ":" si no, si es 'o', agregar "::" y si no, no agregar nada. $shortopt .= $opt["short"] . ( $opt["opt"] == 'y' ? ':' : ( $opt["opt"] == 'o' ? '::' : '' ) ); return $shortopt; } /* * Genera una lista con las opciones largas para pasarle a getopt. * It generates a list with the long options to pass to getopts. * * @returns array El array con el formato necesario para pasarselo a getopt. * The array with the necesary format to pass to getopts. * * @access private * */ function _makelongopt() { $longopt = array(); foreach ( $this->opts as $opt ) // opcion corta + si opcion = y => agregar ":" si no, si es 'o', agregar "::" y si no, no agregar nada. $longopt[] = $opt["long"] . ( $opt["opt"] == 'y' ? '=' : ( $opt["opt"] == 'o' ? '==' : '' ) ); return $longopt; } /* * Agrega el campo "option" y "selected" a las opciones seleccionadas. * Adds the "option" and "selected" fields to the selected options. * * @param $getopt array Array devuelto por getopt. * Array returned by getopt. * * @access private * */ function _proccessopt( $getopt ) { foreach ( $getopt as $opt_presente ) { foreach ( $this->opts as $opt_key => $opt_buscada ) { if ( ($opt_presente[0] == $opt_buscada["short"]) || ($opt_presente[0] == "--" . $opt_buscada["long"]) ) { $this->opts[$opt_key]["selected"] = true; // Agrega el campo option en la opcion presente y le asigna el valor de la opción. $this->opts[$opt_key]["option"] = $opt_presente[1]; // Agrega el campo option en la opcion presente y le asigna el valor de la opción. break; } } } } } ?>