134 lines
3.5 KiB
PHP
134 lines
3.5 KiB
PHP
<?php
|
|
|
|
namespace NoccyLabs\PulseAudio\Helper;
|
|
|
|
class Pacmd
|
|
{
|
|
public static function call($command, array $args=[])
|
|
{
|
|
// assemble command lin
|
|
$cmdl = array_merge([ $command ], $args);
|
|
$cmdl = join(" ", array_map("escapeshellarg", $cmdl));
|
|
|
|
// call pacmd
|
|
exec("pacmd {$cmdl}", $output, $retval);
|
|
|
|
// handle errors
|
|
if ($retval != 0) {
|
|
throw new \RuntimeException("Failed to call pacmd. exitcode={$retval}");
|
|
}
|
|
|
|
// return output
|
|
return $output;
|
|
}
|
|
|
|
public static function query($command, array $args=[])
|
|
{
|
|
$output = Pacmd::call($command, $args);
|
|
|
|
$status = array_shift($output);
|
|
// printf("[pacmd] %s\n", $status);
|
|
|
|
$parser = new ListParser();
|
|
$output = $parser->parse($output);
|
|
|
|
return $output;
|
|
}
|
|
}
|
|
|
|
class ListParser
|
|
{
|
|
public function parse(array $lines)
|
|
{
|
|
$lines = $this->prepare($lines);
|
|
return $this->parseRecursive($lines, 0);
|
|
}
|
|
|
|
private function prepare(array $lines)
|
|
{
|
|
$data = [];
|
|
foreach ($lines as $line) {
|
|
if ($line=="") continue;
|
|
if ($line[0] == " ") {
|
|
$data[] = [ 0, trim($line) ];
|
|
} else {
|
|
$depth = 0;
|
|
while ($line[0]=="\t") {
|
|
$depth++;
|
|
$line = substr($line,1);
|
|
}
|
|
$data[] = [ $depth, $line ];
|
|
}
|
|
}
|
|
return $data;
|
|
}
|
|
|
|
private function parseRecursive(array $lines, $current=0)
|
|
{
|
|
$ret = [];
|
|
while (count($lines)>0) {
|
|
$line = array_shift($lines);
|
|
$children = [];
|
|
while ((count($lines)>0) && ($lines[0][0]>$current)) {
|
|
$children[] = array_shift($lines);
|
|
}
|
|
if (count($children)>0) {
|
|
$key = trim(str_replace("index: ","", $line[1]),":* ");
|
|
$ret[$key] = $this->parseRecursive($children, $line[0]+1);
|
|
} else {
|
|
if (strpos($line[1]," = ")!==false) {
|
|
list ($k,$v) = array_map("trim", explode("=",$line[1],2));
|
|
$ret[$k] = $this->parseVal($v);
|
|
} elseif (strpos($line[1],": ")!==false) {
|
|
list ($k,$v) = array_map("trim", explode(":",$line[1],2));
|
|
$ret[$k] = $this->parseVal($v);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
}
|
|
return $ret;
|
|
|
|
}
|
|
|
|
private function parseVal($value)
|
|
{
|
|
if ($value=="") {
|
|
return null;
|
|
} elseif ($value=="yes") {
|
|
return true;
|
|
} elseif ($value=="no") {
|
|
return false;
|
|
} elseif ($value[0]=="<") {
|
|
$kvs = trim($value,"<>");
|
|
if (strpos($kvs,"=")===false) {
|
|
return $kvs;
|
|
}
|
|
$kvs = explode(" ",$kvs);
|
|
$val = [];
|
|
foreach ($kvs as $kv) {
|
|
list ($k,$v) = explode("=",$kv,2);
|
|
$val[$k] = $v;
|
|
}
|
|
return $val;
|
|
} elseif ($value[0]=="\"") {
|
|
return trim($value,"\"");
|
|
} else {
|
|
return $value;
|
|
}
|
|
}
|
|
|
|
private function parseKeyVal($kvs)
|
|
{
|
|
$kvs = explode(" ",$kvs,2 );
|
|
$val = [];
|
|
foreach ($kvs as $kv) {
|
|
list ($k,$v) = explode("=",$kv,2);
|
|
$val[$k] = $this->parseKeyVal($v);
|
|
}
|
|
return $val;
|
|
}
|
|
|
|
}
|