nulib-base/php/src/file/tab/TAbstractReader.php

56 lines
1.4 KiB
PHP

<?php
namespace nulib\file\tab;
use nulib\cl;
use nulib\exceptions;
use nulib\file\csv\CsvReader;
use nulib\file\web\Upload;
use nulib\os\path;
trait TAbstractReader {
/** @param Upload|string|array $reader */
static function with($reader, ?array $params=null): IReader {
if ($reader instanceof self) return $reader;
$class = null;
if ($reader instanceof Upload) {
if ($reader->isExt(".csv")) {
$class = CsvReader::class;
} else {
$class = static::class;
if ($reader->isExt(".ods")) {
$params["ss_type"] = "ods";
} else {
$params["ss_type"] = "xlsx";
}
}
return new $class($reader->getFile(), $params);
}
if (is_string($reader)) {
$params["input"] = $reader;
} elseif (is_array($reader)) {
$params = cl::merge($reader, $params);
} elseif ($reader !== null) {
throw exceptions::invalid_type($reader, "reader", self::class);
}
$input = $params["input"] ?? null;
$ssType = null;
if (is_string($input)) {
$ext = path::ext($input);
if ($input === "-" || $ext === ".csv") {
$class = CsvReader::class;
} elseif ($ext === ".ods") {
$ssType = "ods";
} elseif ($ext === ".xlsx") {
$ssType = "xlsx";
} else {
$ssType = "xlsx";
}
}
$params["ss_type"] = $ssType;
if ($class === null) $class = static::class;
return new $class(null, $params);
}
}