/**
* Allow to execute and get the result of a command which can return more than one page on the CLI
*
* @param string $cmd The command to run
* @param string $regexp A regex which will filter the rows. If a rows doesn't satisfy the regex, it will be
* skipped.
* @param Callable $callback A callback wich will be called for each rows. The first parameter is the rows itself,
* the second parameter is the result of preg_match call on the row wich the regexp
* provided
*
* @return array
*
* @throws InvalidArgumentException If $callback is not a valid callback
*/
protected function execPageableCommand(string $cmd, string $regexp, $callback) : array
{
if (false == is_callable($callback)) {
throw new InvalidArgumentException("You must provide a valid callback");
}
$result = [];
$this->ssh->write($cmd . $this->enterKey);
$readPattern = '`' . $this->morePattern . '|' . $this->promptPattern . '`';
while ($stdout = $this->ssh->read($readPattern, SSH2::READ_REGEX)) {
foreach (explode("\n", $stdout) as $line) {
if ($regexp == '' || $regexp == '`.*`' || $regexp == '`.+`') {
$result[] = $line;
continue;
}
preg_match($regexp, $line, $match);
if (count($match) > 0) {
list($index, $value) = $callback($line, $match);
if ($index !== null) {
$result[$index] = $value;
} else {
$result[] = $value;
}
}
}
if (preg_match('`' . $this->promptPattern . '`', $stdout) === 1) {
break;
}
$this->ssh->write($this->spaceKey);
}
return $result;
}