<?php
/**
*+-----------------------------------------------------------------------+
*| CliParser v0.1 - 19 Jul 2006 |
*+-----------------------------------------------------------------------+
*| Diego do Nascimento Feitosa |
*| hide@address.com |
*| www.dnfeitosa.com |
*| São Paulo/SP - Brasil |
*| The latest version can be found at www.dnfeitosa.com |
*+-----------------------------------------------------------------------+
*| CliParser is free software; you can redistribute it and/or modify |
*| it under the terms of the GNU General Public License as published by |
*| the Free Software Foundation; either version 2 of the License, or |
*| (at your option) any later version. |
*| |
*| CliParser is distributed in the hope that it will be useful, but |
*| WITHOUT ANY WARRANTY; without even the implied warranty of |
*| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
*| General Public License for more details. |
*| |
*| You should have received a copy of the GNU General Public License |
*| along with CliParser; if not, write to the Free Software |
*| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA |
*| 02111-1307 USA |
*+-----------------------------------------------------------------------+
**/
abstract class CliParser {
var $tokens = array();
var $require = array();
var $args = array();
function __construct($args) {
$this->args = new ArrayObject($args);
}
function register($token, $require = true) {
$tk = $token->getToken();
$this->tokens[$tk] = $token;
$this->require[$tk] = $require;
}
function tokenExists($token) {
return array_key_exists($token, $this->tokens);
}
function isToken($token) {
return $this->tokenExists($token);
}
function getToken($token) {
return $this->tokens[$token];
}
function requireValue($token) {
if ($this->tokenExists($token)) {
return $this->require[$token];
} else {
$this->undefinedTokenError($token);
}
}
abstract function undefinedTokenError($token);
abstract function getHelpMessage();
function getValue($token) {
if ($this->tokenExists($token)) {
return $this->tokens[$token]->getValue();
} else {
$this->undefinedTokenError($token);
}
}
function getDescriptions() {
foreach ($this->tokens as $token) {
echo $token->getHelpMessage();
}
}
function parse() {
$iter = $this->args->getIterator();
$iter->next(); // skip the filename
while ($iter->valid()) {
$curr = $iter->current();
if ($this->isToken($curr)) {
$token = $this->getToken($curr);
if ($this->requireValue($curr)) {
$iter->next();
$token->setValue($iter->current());
} else {
$token->setValue(true);
}
if (!$token->isAssigned()) {
$this->getHelpMessage();
exit;
}
} else {
$this->undefinedTokenError($curr);
}
$iter->next();
}
}
}
?>