Added printer enumeration

This commit is contained in:
Chris 2019-06-16 02:05:36 +02:00
parent 11d642b8a4
commit baa5f4bdb3
2 changed files with 61 additions and 0 deletions

12
examples/printers.php Normal file
View File

@ -0,0 +1,12 @@
<?php
require_once __DIR__."/../vendor/autoload.php";
use NoccyLabs\Lpr\PrinterList;
$printers = new PrinterList();
foreach ($printers as $printer=>$meta) {
printf("%s\n%s\n\n", $printer, json_encode($meta,JSON_PRETTY_PRINT));
}

49
src/PrinterList.php Normal file
View File

@ -0,0 +1,49 @@
<?php
namespace NoccyLabs\Lpr;
use ArrayIterator;
class PrinterList implements \IteratorAggregate
{
const PRINTCAP_FILE = "/etc/printcap";
/** @var array */
private static $printers = [];
private static function update()
{
self::$printers = [];
if (file_exists(self::PRINTCAP_FILE) && is_readable(self::PRINTCAP_FILE)) {
$printcap = file(self::PRINTCAP_FILE, FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES);
foreach ($printcap as $line) {
if (empty($line) || (strpos(trim($line),"#") === 0)) continue;
if (strpos($line, "|") === false) continue;
list ($name, $info) = explode("|", $line, 2);
$meta = explode(":", $info);
$props = [
'name' => $name,
'description' => array_shift($meta),
];
foreach ($meta as $prop) {
if (strpos($prop, "=") === false) continue;
list($key,$value) = explode("=",$prop,2);
$props[$key] = $value;
}
self::$printers[$name] = $props;
}
}
}
public function getIterator()
{
if (empty(self::$printers)) self::update();
return new ArrayIterator(self::$printers);
}
public function getPrinterNames()
{
if (empty(self::$printers)) self::update();
return array_keys(self::$printers);
}
}