\documentclass{article}
\usepackage{ulem}
\usepackage{graphicx}
\usepackage{hyperref}
\pagestyle{headings}
\begin{document}
\part{Horde\_Argv}
\section{Option Callbacks}
When \textit{Horde\_Argv}'s built-in actions and types aren't quite enough for your needs, you have two choices: extend \textit{Horde\_Argv} or define a callback option. Extending \textit{Horde\_Argv} is more general, but overkill for a lot of simple cases. Quite often a simple callback is all you need.

You define a callback in two steps:

\begin{itemize}
\item define the option itself using the callback action


\item write the callback; this is a function (or method) that takes at least four arguments, as described below


\end{itemize}
\subsection{Defining a callback option}
As always, the easiest way to define a callback option is by using the \texttt{addOption()} method of your \texttt{Horde\_Argv\_Parser} object. The only option attribute you must specify is callback, the function to call:

<pre><code class="language-php">
\$parser->addOption('-c', array('action' => 'callback', 'callback' => 'my\_callback'));
</code></pre>
Note that you supply a \texttt{callable} here -- so you must have already defined a function \texttt{my\_callback()} when you define the \texttt{callback} option. In this simple case, \textit{Horde\_Argv} knows nothing about the arguments the "-c" option expects to take. Usually, this means that the option doesn't take any arguments -- the mere presence of "-c" on the command-line is all it needs to know. In some circumstances, though, you might want your callback to consume an arbitrary number of command-line arguments. This is where writing callbacks gets tricky; it's covered later in this document.

\textit{Horde\_Argv} always passes four particular arguments to your callback, and it will only pass additional arguments if you specify them via \texttt{callback\_args} and \texttt{callback\_kwargs}. Thus, the minimal callback function signature is:

<pre><code class="language-php">
function my\_callback(\$option, \$opt, \$value, \$parser)
</code></pre>
The four arguments to a callback are described below.

There are several other option attributes that you can supply when you define an option attribute:

\textbf{\texttt{type}}: has its usual meaning: as with the \texttt{store} or \texttt{append} actions, it instructs \textit{Horde\_Argv} to consume one argument and convert it to \texttt{type}. Rather than storing the converted value(s) anywhere, though, \textit{Horde\_Argv} passes it to your callback function.<br />
\textbf{\texttt{nargs}}: also has its usual meaning: if it is supplied and > 1, \textit{Horde\_Argv} will consume \texttt{nargs} arguments, each of which must be convertible to \texttt{type}. It then passes an array of converted values to your callback.<br />
\textbf{\texttt{callback\_args}}: an array of extra positional arguments to pass to the callback<br />
\textbf{\texttt{callback\_kwargs}}: a hash of extra keyword arguments to pass to the callback

\subsection{How callbacks are called}
All callbacks are called as follows:

<pre><code class="language-php">
func(Horde\_Argv\_Option \$option,
     string \$opt,
     mixed \$value,
     Horde\_Argv\_Parser \$parser,
     array \$args,
     array \$kwargs)
</code></pre>
where

\textbf{\texttt{\$option}}: is the \texttt{Horde\_Argv\_Option} instance that's calling the callback<br />
\textbf{\texttt{\$opt}}: is the option string seen on the command-line that's triggering the callback. (If an abbreviated long option was used, \texttt{\$opt} will be the full, canonical option string -- e.g. if the user puts "--foo" on the command-line as an abbreviation for "--foobar", then \texttt{\$opt} will be "--foobar".)<br />
\textbf{\texttt{\$value}}: is the argument to this option seen on the command-line. \textit{Horde\_Argv} will only expect an argument if \texttt{type} is set; the type of \texttt{\$value} will be the type implied by the option's type (see "Option types" below). If \texttt{type} for this option is \texttt{null} (no argument expected), then \texttt{\$value} will be \texttt{null}. If \texttt{nargs} > 1, \texttt{\$value} will be an array of values of the appropriate type.<br />
\textbf{\texttt{\$parser}}: is the \texttt{Horde\_Argv\_Parser} instance driving the whole thing, mainly useful because you can access some other interesting data through it, as instance attributes:<br />
: \texttt{\$parser->largs} : the current list of leftover arguments, ie. arguments that have been consumed but are neither options nor option arguments. Feel free to modify \texttt{\$parser->largs}, e.g. by adding more arguments to it. (This list will become \texttt{\$args}, the second return value of \texttt{parseArgs()}.)<br />
: \texttt{\$parser->rargs} : the current list of remaining arguments, ie. with \texttt{\$opt} and \texttt{\$value} (if applicable) removed, and only the arguments following them still there. Feel free to modify \texttt{\$parser->rargs}, e.g. by consuming more arguments.<br />
: \texttt{\$parser->values} : the object where option values are by default stored (an instance of \texttt{Horde\_Argv\_Values}). This lets callbacks use the same mechanism as the rest of \textit{Horde\_Argv} for storing option values; you don't need to mess around with globals or closures. You can also access or modify the value(s) of any options already encountered on the command-line.<br />
\textbf{\texttt{\$args}}: is a tuple of arbitrary positional arguments supplied via the \texttt{callback\_args} option attribute.<br />
\textbf{\texttt{\$kwargs}}: is a dictionary of arbitrary keyword arguments supplied via \texttt{callback\_kwargs}.

\subsection{Error handling}
The callback function should throw \texttt{Horde\_Argv\_OptionValueException} if there are any problems with the option or its argument(s). \textit{Horde\_Argv} catches this and terminates the program, printing the error message you supply to stderr. Your message should be clear, concise, accurate, and mention the option at fault. Otherwise, the user will have a hard time figuring out what he did wrong.

\subsection{Examples part 1: no arguments}
Here's an example of a callback option that takes no arguments, and simply records that the option was seen:

<pre><code class="language-php">
function record\_foo\_seen(\$option, \$opt, \$value, \$parser)
\{
    \$parser->saw\_foo = true;
\}

\$parser->addOption(
    '--foo',
    arry('action' => 'callback', 'callback' => 'record\_foo\_seen')
);
</code></pre>
Of course, you could do that with the \texttt{store\_true} action. Here's a slightly more interesting example: record the fact that "-a" is seen, but blow up if it comes after "-b" in the command-line.

<pre><code class="language-php">
\$check\_order = function(\$option, \$opt, \$value, \$parser)
\{
    if (\$parser->values->b) \{
        throw new Horde\_Argv\_OptionValueException("can't use -a after -b");
    \}
    \$parser->values->a = 1;
\}
[...]
\$parser->addOption(
    '-a',
    array('action' => 'callback', 'callback' => \$check\_order)
);
\$parser->addOption('-b', array('action' => 'store\_true', 'dest' => 'b'));
</code></pre>
If you want to re-use this callback for several similar options (set a flag, but blow up if "-b" has already been seen), it needs a bit of work: the error message and the flag that it sets must be generalized.

<pre><code class="language-php">
function check\_order(\$option, \$opt, \$value, \$parser)
\{
    if (\$parser->values->b) \{
        throw new Horde\_Argv\_OptionValueException(sprintf("can't use \%s after -b", \$opt));
    \}
    \$parser->values->\{\$option->dest\} = 1;
\}
[...]
\$parser->addOption(
    '-a',
    array('action' => 'callback', 'callback' => 'check\_order', 'dest' => 'a')
);
\$parser->addOption(
    '-b',
    array('action' => 'store\_true', 'dest' => 'b')
);
\$parser->addOption(
    '-c',
    array('action' => 'callback', 'callback' => 'check\_order', 'dest' => 'c')
);
</code></pre>
Of course, you could put any condition in there -- you're not limited to checking the values of already-defined options. For example, if you have options that should not be called when the moon is full, all you have to do is this:

<pre><code class="language-php">
function check\_moon(\$option, \$opt, \$value, \$parser)
\{
    if (is\_moon\_full()) \{
        throw new Horde\_Argv\_OptionValueException(sprintf('\%s option invalid when moon is full', \$opt));
    \}
    \$parser->values->\{\$option->dest\} = 1;
\}
[...]
\$parser->addOption(
    '--foo',
    array('action' => 'callback', 'callback' => 'check\_moon', 'dest' => 'foo')
);
</code></pre>
(The definition of \texttt{is\_moon\_full()} is left as an exercise for the reader.)

\subsection{Examples part 2: fixed arguments}
Things get slightly more interesting when you define callback options that take a fixed number of arguments. Specifying that a callback option takes arguments is similar to defining a \texttt{store} or \texttt{append} option: if you define \texttt{type}, then the option takes one argument that must be convertible to that type; if you further define \texttt{nargs}, then the option takes \texttt{nargs} arguments.

Here's an example that just emulates the standard \texttt{store} action:

<pre><code class="language-php">
function store\_value(\$option, \$opt, \$value, \$parser)
\{
    \$parser->values->\{\$option->dest\} = \$value;
\}
[...]
\$parser->addOption(
    '--foo',
    array('action' => 'callback', 'callback' => 'store\_value',
          'type' => 'int', 'nargs' => 3, 'dest' => 'foo')
);
</code></pre>
Note that \textit{Horde\_Argv} takes care of consuming 3 arguments and converting them to integers for you; all you have to do is store them. (Or whatever: obviously you don't need a callback for this example. Use your imagination!)

\subsection{Examples part 3: variable arguments}
Things get hairy when you want an option to take a variable number of arguments. For this case, you must write a callback, as \textit{Horde\_Argv} doesn't provide any built-in capabilities for it. And you have to deal with certain intricacies of conventional Unix command-line parsing that \textit{Horde\_Argv} normally handles for you. In particular, callbacks have to worry about bare "--" and "-" arguments; the convention is:

\begin{itemize}
\item bare "--", if not the argument to some option, causes command-line processing to halt and the "--" itself is lost


\item bare "-" similarly causes command-line processing to halt, but the "-" itself is kept


\item either "--" or "-" can be option arguments


\end{itemize}
If you want an option that takes a variable number of arguments, there are several subtle, tricky issues to worry about. The exact implementation you choose will be based on which trade-offs you're willing to make for your application (which is why \textit{Horde\_Argv} doesn't support this sort of thing directly).

Nevertheless, here's a stab at a callback for an option with variable arguments:

<pre><code class="language-php">
function vararg\_callback(\$option, \$opt, \$value, \$parser)
\{
    \$done = 0;
    \$value = array();
    \$rargs = \$parser->rargs;
    while (\$rargs) \{
        \$arg = \$rargs[0];

        // Stop if we hit an \$arg like '--foo', '-a', '-fx', '--file=f',
        // etc.  Note that this also stops on '-3' or '-3.0', so if
        // your option takes numeric values, you will need to handle
        // this.
        if ((substr(\$arg, 0, 2) == '--' \&\& strlen(\$arg) > 2) ||
            (\$arg[0] == '-' \&\& strlen(\$arg) > 1 \&\& \$arg[1] != '-')) \{
            break;
        \} else \{
            \$value[] = \$arg;
        \}
        array\_shift(\$rargs);
    \}

    \$parser->values->\{\$option->dest\} = \$value;
\}

[...]
\$parser->addOption(
    '-c', '--callback',
    array('action' => 'callback', 'callback' => 'vararg\_callback')
);
</code></pre>
The main weakness with this particular implementation is that negative numbers in the arguments following "-c" will be interpreted as further options, rather than as arguments to "-c". Fixing this is left as an exercise for the reader.

\end{document}
