feat: 完善/优化/新增大批次 + 安全加固 + 性能优化

- 修复再次提交不置顶(排序键改用 last_submit_ts)
- 后端结果缓存 + 并发锁(DataCache / ny_build_data / Roster 指纹失效)
- 导出 xlsx 多表:按最新成绩 / 按班级分表 / 可选列
- 名单管理:新增改弹窗、删除多选+二次确认、登陆账号列
- 安全:CSRF token + 登录失败限流(5次锁10分钟)
- 未匹配答卷一键加入名单(unmatched_map)
- 缺考名单增强:复制学号/姓名、按班统计、打印
- 成绩快照 + 跨卷趋势(Snapshot)
- 异常检测线索(短时长高分/高频重考/雷同成绩)
- 前端性能:虚拟滚动、搜索防抖、后台暂停、失败退避
- 测试沉淀:test-new-features.php + run-all.sh
This commit is contained in:
2026-09-10 17:59:45 +08:00
parent 87750b20c4
commit 0fd880624f
14 changed files with 1784 additions and 196 deletions
+117
View File
@@ -0,0 +1,117 @@
<?php
/**
* 数据结果缓存(短期 TTL)
*
* 目的:拉取卷王全量答卷是重操作(多次 HTTP + 大量 json_decode),
* 多个老师同时查看同一套卷、或页面按 5~15 秒自动刷新时,会重复打卷王。
* 这里把 DataService::build() 的结果按「项目 + 配置 + 名单指纹」缓存一小段时间。
*
* 失效保证:名单变化(Roster::fingerprint)、连接/去重等配置变化都会改变 key。
* 另外可显式 force=1 跳过缓存(前端"立即刷新"按钮使用)。
*/
declare(strict_types=1);
final class DataCache
{
private static function dir(): string
{
return NY_DATA . '/cache';
}
/** 由若干要素拼成缓存 key */
public static function key(array $parts): string
{
return md5(implode("\x1f", array_map(static fn($v) => (string)$v, $parts)));
}
private static function path(string $key): string
{
return self::dir() . '/data_' . $key . '.json';
}
private static function lockPath(string $key): string
{
return self::dir() . '/data_' . $key . '.lock';
}
/**
* 读取缓存;不存在 / 过期 / 损坏都返回 null
* @return array{at:int,result:array}|null
*/
public static function read(string $key, int $ttl): ?array
{
$f = self::path($key);
if (!is_file($f)) {
return null;
}
$raw = @file_get_contents($f);
if ($raw === false || $raw === '') {
return null;
}
$d = json_decode($raw, true);
if (!is_array($d) || !isset($d['at']) || !is_array($d['result'])) {
return null;
}
if ($ttl > 0 && (time() - (int)$d['at']) > $ttl) {
return null;
}
return ['at' => (int)$d['at'], 'result' => $d['result']];
}
public static function write(string $key, array $result): bool
{
if (!is_dir(self::dir())) {
@mkdir(self::dir(), 0775, true);
}
$tmp = self::path($key) . '.tmp';
$ok = @file_put_contents($tmp, json_encode(
['at' => time(), 'result' => $result],
JSON_UNESCAPED_UNICODE
), LOCK_EX);
if ($ok === false) {
return false;
}
return @rename($tmp, self::path($key));
}
/**
* 获取构建锁(防止并发惊群:同一 key 只有一个请求真正去拉卷王)。
*
* @return resource|null 拿到锁返回句柄(需配合 releaseLock 释放);拿不到返回 null
*/
public static function acquireLock(string $key)
{
if (!is_dir(self::dir())) {
@mkdir(self::dir(), 0775, true);
}
$fh = @fopen(self::lockPath($key), 'c');
if ($fh === false) {
return null;
}
if (!flock($fh, LOCK_EX | LOCK_NB)) {
fclose($fh);
return null; // 已有其它请求在构建
}
return $fh;
}
public static function releaseLock($fh): void
{
if (is_resource($fh)) {
@flock($fh, LOCK_UN);
@fclose($fh);
}
}
/** 清空所有数据缓存(名单变更 / 手动清缓存时使用) */
public static function clear(): int
{
$n = 0;
foreach (glob(self::dir() . '/data_*.json') ?: [] as $f) {
if (@unlink($f)) {
$n++;
}
}
return $n;
}
}
+93 -2
View File
@@ -235,8 +235,12 @@ class DataService
$attemptsTotal = $agg['attempts_total'];
// 成绩明细默认按提交时间降序(最新在前),学号作为次级排序
usort($rows, static function (array $x, array $y): int {
$d = ($y['submit_ts'] ?? 0) <=> ($x['submit_ts'] ?? 0);
// 重要:排序键必须用「最近一次提交时间 last_submit_ts」,而不是代表行的 submit_ts。
// 否则当 dedupe=false(代表成绩=最高分)时,学生重考且分数更低,代表行仍是最高分那次,
// submit_ts 不变 → 该行会停在原来的位置只高亮,不会置顶,教师登记时看不到新提交。
$sortTs = static fn(array $r): int => (int)($r['last_submit_ts'] ?? 0) ?: (int)($r['submit_ts'] ?? 0);
usort($rows, static function (array $x, array $y) use ($sortTs): int {
$d = $sortTs($y) <=> $sortTs($x);
if ($d !== 0) {
return $d;
}
@@ -290,6 +294,9 @@ class DataService
'attempts_total'=> $attemptsTotal,
];
// 异常检测(防作弊线索,仅供教师人工判断,不做自动判定)
$anomalies = self::detectAnomalies($rows, $stats);
return [
'project' => [
'id' => ny_str($project['id'] ?? $projectId),
@@ -303,12 +310,96 @@ class DataService
'absent' => $absent,
'unmatched' => $unmatched,
'stats' => $stats,
'anomalies' => $anomalies,
'roster' => $students,
'roster_count' => count($students),
'updated_at' => date('Y-m-d H:i:s'),
];
}
/**
* 异常检测(防作弊线索):基于聚合后的学生行,输出三类线索供教师人工复核。
* 1) 短时长高得分:用时远低于平均(<平均 40% 且 <180s)却接近满分;
* 2) 高频重考:考试次数明显多于多数人(>1 且 >= 平均次数+3);
* 3) 雷同成绩:多人分数完全相同(疑似互抄,需满足该分数下人数 >=3)。
*
* 返回值:['fast_high'=>[], 'frequent'=>[], 'identical'=>[['score'=>x,'count'=>n,'names'=>[...]]]]
*/
public static function detectAnomalies(array $rows, array $stats): array
{
$avgDur = (int)($stats['avg_duration'] ?? 0);
$fullHint = max(1, (float)($stats['max_score'] ?? 100));
$fastHigh = [];
$frequent = [];
$attemptsAll = [];
foreach ($rows as $r) {
$dur = $r['duration'] ?? null;
$score = $r['score'] ?? null;
$attempts = (int)($r['attempts'] ?? 1);
$attemptsAll[] = $attempts;
// 短时长高得分:有时长记录、明显快于平均、分数 >= 满分 85%
if ($dur !== null && $avgDur > 0 && $dur < max(60, (int)($avgDur * 0.4))
&& $score !== null && $score >= $fullHint * 0.85) {
$fastHigh[] = [
'sid' => (string)($r['sid'] ?? ''),
'name' => (string)($r['name'] ?? ''),
'cls' => (string)($r['cls'] ?? ''),
'score' => $score,
'duration' => $dur,
'duration_txt' => (string)($r['duration_txt'] ?? ''),
];
}
// 高频重考:考试次数明显偏多
if ($attempts > 1) {
$frequent[] = [
'sid' => (string)($r['sid'] ?? ''),
'name' => (string)($r['name'] ?? ''),
'cls' => (string)($r['cls'] ?? ''),
'attempts' => $attempts,
'best_score' => $r['best_score'] ?? null,
];
}
}
// 高频重考阈值:平均次数 + 3(且至少 4 次才够"高频")
$avgAttempts = $attemptsAll !== [] ? array_sum($attemptsAll) / count($attemptsAll) : 0;
$freqThreshold = max(4, (int)ceil($avgAttempts + 3));
$frequent = array_values(array_filter($frequent, static fn($f) => $f['attempts'] >= $freqThreshold));
usort($frequent, static fn($a, $b) => $b['attempts'] <=> $a['attempts']);
// 雷同成绩:按分数分组,出现 >=3 人同分(且分数不为 null)视为疑似
$scoreGroups = [];
foreach ($rows as $r) {
$score = $r['score'] ?? null;
if ($score === null) {
continue;
}
$key = (string)$score;
$scoreGroups[$key][] = [
'sid' => (string)($r['sid'] ?? ''),
'name' => (string)($r['name'] ?? ''),
'cls' => (string)($r['cls'] ?? ''),
];
}
$identical = [];
foreach ($scoreGroups as $score => $members) {
if (count($members) >= 3) {
$identical[] = ['score' => (float)$score, 'count' => count($members), 'members' => $members];
}
}
usort($identical, static fn($a, $b) => $b['count'] <=> $a['count']);
return [
'fast_high' => $fastHigh,
'frequent' => $frequent,
'identical' => $identical,
];
}
/**
* 把聚合后的学生行展开为"每次考试一行",用于导出全部考试记录 / 明细内全部展示。
* 每行携带该次考试的成绩、提交时间、时长,以及该学生的总考试次数 attempts 与第几次 idx。
+17
View File
@@ -98,6 +98,23 @@ class Roster
return count(self::all());
}
/**
* 名单指纹:名单内容一变就变,用于数据缓存 key。
* 只取「人数 + 文件修改时间 + 内容的轻量哈希」,避免每次全量序列化。
*/
public static function fingerprint(): string
{
if (self::useDb()) {
return 'db:' . self::count();
}
$f = self::file();
$mt = is_file($f) ? (string)filemtime($f) : '0';
$sz = is_file($f) ? (string)filesize($f) : '0';
$d = ny_read_json($f, null);
$hash = is_array($d) ? md5(json_encode($d['students'] ?? [], JSON_UNESCAPED_UNICODE)) : '0';
return $mt . ':' . $sz . ':' . $hash;
}
/**
* 首次使用时,若名单为空且存在 导入模板.xlsx,自动导入
*/
+164
View File
@@ -0,0 +1,164 @@
<?php
/**
* 成绩快照:把某次「拉取到的成绩」落盘成一份带标签的时间点存档,
* 用于跨时间 / 跨试卷的趋势对比(例如某学生几次考试的分数变化)。
*
* 存储位置:data/snapshots/<projectId>/<unix秒>_<md5(标签)>.json
* 每份快照内容为 { label, at, project:{id,name}, stats, students:[{sid,name,cls,grp,score,best_score,attempts,last_submit_at}] }
*/
declare(strict_types=1);
final class Snapshot
{
private static function dir(string $projectId): string
{
$d = NY_DATA . '/snapshots/' . preg_replace('/[^A-Za-z0-9_-]/', '_', $projectId);
if (!is_dir($d)) {
@mkdir($d, 0777, true);
}
return $d;
}
/** 从聚合结果里抽取轻量学生摘要(只保留趋势对比需要的字段) */
public static function summarize(array $result, string $label): array
{
$students = [];
foreach ((array)($result['rows'] ?? []) as $r) {
$students[] = [
'sid' => (string)($r['sid'] ?? ''),
'name' => (string)($r['name'] ?? ''),
'cls' => (string)($r['cls'] ?? ''),
'grp' => (string)($r['grp'] ?? ''),
'score' => ($r['score'] ?? null) === null ? null : (float)$r['score'],
'best_score' => ($r['best_score'] ?? null) === null ? null : (float)$r['best_score'],
'attempts' => (int)($r['attempts'] ?? 1),
'last_submit_at' => (string)($r['last_submit_at'] ?? ($r['submit_at'] ?? '-')),
];
}
// 按学号排序,保证趋势表行序稳定
usort($students, static function ($a, $b): int {
$sa = $a['sid']; $sb = $b['sid'];
if (is_numeric($sa) && is_numeric($sb)) {
return $sa <=> $sb;
}
return strnatcmp((string)$sa, (string)$sb);
});
return [
'label' => trim($label) === '' ? '快照 ' . date('m-d H:i') : trim($label),
'at' => time(),
'at_txt' => date('Y-m-d H:i:s'),
'project' => [
'id' => (string)($result['project']['id'] ?? ''),
'name' => (string)($result['project']['name'] ?? ''),
],
'stats' => $result['stats'] ?? [],
'students' => $students,
];
}
/** 保存一份快照,返回文件名 */
public static function save(string $projectId, array $snap): string
{
$dir = self::dir($projectId);
$name = time() . '_' . substr(md5($snap['label'] . $snap['at']), 0, 8) . '.json';
@file_put_contents($dir . '/' . $name, json_encode($snap, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), LOCK_EX);
return $name;
}
/** 列出某项目的全部快照(按时间倒序) */
public static function list(string $projectId): array
{
$dir = self::dir($projectId);
$out = [];
foreach (glob($dir . '/*.json') ?: [] as $f) {
$raw = @file_get_contents($f);
if ($raw === false) {
continue;
}
$j = json_decode($raw, true);
if (!is_array($j)) {
continue;
}
$out[] = [
'file' => basename($f),
'label' => (string)($j['label'] ?? basename($f)),
'at' => (int)($j['at'] ?? 0),
'at_txt' => (string)($j['at_txt'] ?? ''),
'project' => $j['project'] ?? [],
'count' => count((array)($j['students'] ?? [])),
];
}
usort($out, static fn($a, $b) => ($b['at'] <=> $a['at']));
return $out;
}
/** 读取单份快照完整内容 */
public static function get(string $projectId, string $file): ?array
{
$file = basename($file); // 防路径穿越
$path = self::dir($projectId) . '/' . $file;
if (!is_file($path)) {
return null;
}
$j = json_decode((string)@file_get_contents($path), true);
return is_array($j) ? $j : null;
}
/** 删除单份快照 */
public static function delete(string $projectId, string $file): bool
{
$file = basename($file);
$path = self::dir($projectId) . '/' . $file;
if (is_file($path)) {
return @unlink($path);
}
return false;
}
/**
* 跨快照趋势:以学号为行、各快照为列,输出每个学生在每份快照里的成绩。
* 用 best_score(真实最高分)作为趋势值,未出现记 null。
*/
public static function trend(array $snapshots): array
{
// 按时间升序排,最早的列在最前
$snaps = $snapshots;
usort($snaps, static fn($a, $b) => ($a['at'] <=> $b['at']));
$cols = [];
$bySid = [];
foreach ($snaps as $sn) {
$colKey = (string)$sn['at'] . ':' . (string)$sn['label'];
$cols[] = ['key' => $colKey, 'label' => (string)$sn['label'], 'at_txt' => (string)($sn['at_txt'] ?? '')];
foreach ((array)($sn['students'] ?? []) as $st) {
$sid = (string)($st['sid'] ?? '');
if ($sid === '') {
continue;
}
if (!isset($bySid[$sid])) {
$bySid[$sid] = [
'sid' => $sid,
'name' => (string)($st['name'] ?? ''),
'cls' => (string)($st['cls'] ?? ''),
'scores' => [],
];
}
$bySid[$sid]['scores'][$colKey] = ($st['best_score'] ?? null) === null
? null
: (float)$st['best_score'];
}
}
$rows = array_values($bySid);
// 按学号排序
usort($rows, static function ($a, $b): int {
if (is_numeric($a['sid']) && is_numeric($b['sid'])) {
return $a['sid'] <=> $b['sid'];
}
return strnatcmp((string)$a['sid'], (string)$b['sid']);
});
return ['columns' => $cols, 'rows' => $rows];
}
}
+138 -46
View File
@@ -15,10 +15,8 @@ final class XlsxWriter
private array $strIndex = [];
/** @var array<int,string> 索引 => 共享字符串 */
private array $strings = [];
/** @var array<int,array<int,string>> 行数据 */
private array $rows = [];
/** @var array<int,float> 列宽(1 基) */
private array $widths = [];
/** @var array<int,array{name:string,rows:array,widths:array}> 工作表(按输出顺序) */
private array $sheets = [];
// 样式索引(见 stylesXml)
private const S_DEFAULT = 0; // 常规
@@ -26,57 +24,132 @@ final class XlsxWriter
private const S_TEXT = 2; // 文本格式(numFmtId=49)
/**
* 生成 xlsx 二进制内容
* 生成单表 xlsx 二进制内容(兼容旧调用)
*
* @param array $rows 二维表,第一行视为表头;每个元素会被强制转成字符串
* @param array $opts ['widths' => [列宽,...], 'title' => 工作表名]
* @return string xlsx 文件二进制
*/
public static function render(array $rows, array $opts = []): string
{
return self::renderMulti([[
'name' => (string)($opts['title'] ?? 'Sheet1'),
'rows' => $rows,
'widths' => array_values((array)($opts['widths'] ?? [])),
]]);
}
/**
* 生成多工作表 xlsx
*
* 说明:所有单元格都写成「共享字符串 + 文本格式(numFmtId=49)」,
* 因此既不会出现长学号被转成科学计数法,也不会把以 = + - @ 开头的内容
* 当成公式执行(天然规避 CSV 公式注入问题)。
*
* @param array $sheets 每个元素:['name'=>工作表名, 'rows'=>二维表, 'widths'=>[列宽...]]
* @return string xlsx 文件二进制
*/
public static function renderMulti(array $sheets): string
{
$w = new self();
$w->rows = array_values($rows);
$w->widths = array_values((array)($opts['widths'] ?? []));
return $w->build((string)($opts['title'] ?? 'Sheet1'));
foreach ($sheets as $sh) {
if (!is_array($sh)) {
continue;
}
$rows = array_values((array)($sh['rows'] ?? []));
if ($rows === []) {
continue; // 空表不输出,避免 Excel 提示修复
}
$w->sheets[] = [
'name' => self::safeSheetName((string)($sh['name'] ?? ''), count($w->sheets) + 1, $w->sheets),
'rows' => $rows,
'widths' => array_values((array)($sh['widths'] ?? [])),
];
}
if ($w->sheets === []) {
// 保底:至少输出一张空表
$w->sheets[] = ['name' => 'Sheet1', 'rows' => [['']], 'widths' => []];
}
return $w->build();
}
/* ---------------- 内部:构建 ---------------- */
private function build(string $title): string
private function build(): string
{
$maxCol = 1;
foreach ($this->rows as $r) {
$maxCol = max($maxCol, count((array)$r));
}
$maxRow = max(1, count($this->rows));
// 先登记所有字符串,生成 sharedStrings 索引
$cells = [];
foreach ($this->rows as $ri => $row) {
$r = (int)$ri + 1;
foreach (array_values((array)$row) as $ci => $val) {
$c = (int)$ci + 1;
$s = $this->intern((string)($val ?? ''));
$cells[$r][$c] = $s;
}
}
$sheet = $this->sheetXml($cells, $maxRow, $maxCol);
$files = [
'[Content_Types].xml' => $this->contentTypesXml(),
'_rels/.rels' => $this->rootRelsXml(),
'docProps/app.xml' => $this->appXml(),
'docProps/core.xml' => $this->coreXml($title),
'xl/workbook.xml' => $this->workbookXml($title),
'xl/_rels/workbook.xml.rels' => $this->workbookRelsXml(),
'xl/styles.xml' => $this->stylesXml(),
'xl/sharedStrings.xml' => $this->sharedStringsXml(),
'xl/worksheets/sheet1.xml' => $sheet,
'[Content_Types].xml' => '', // 占位,下面按表数量生成
];
$sheetXmls = [];
$names = [];
foreach ($this->sheets as $i => $sh) {
$n = $i + 1;
$maxCol = 1;
foreach ($sh['rows'] as $r) {
$maxCol = max($maxCol, count((array)$r));
}
$maxRow = max(1, count($sh['rows']));
// 登记共享字符串并生成单元格索引
$cells = [];
foreach (array_values($sh['rows']) as $ri => $row) {
$r = (int)$ri + 1;
foreach (array_values((array)$row) as $ci => $val) {
$c = (int)$ci + 1;
$cells[$r][$c] = $this->intern((string)($val ?? ''));
}
}
$sheetXmls['xl/worksheets/sheet' . $n . '.xml'] = $this->sheetXml($cells, $maxRow, $maxCol, $sh['widths']);
$names[] = $sh['name'];
}
$count = count($this->sheets);
$files = [
'[Content_Types].xml' => $this->contentTypesXml($count),
'_rels/.rels' => $this->rootRelsXml(),
'docProps/app.xml' => $this->appXml(),
'docProps/core.xml' => $this->coreXml($names[0] ?? 'Sheet1'),
'xl/workbook.xml' => $this->workbookXml($names),
'xl/_rels/workbook.xml.rels' => $this->workbookRelsXml($count),
'xl/styles.xml' => $this->stylesXml(),
'xl/sharedStrings.xml' => $this->sharedStringsXml(),
] + $sheetXmls;
return $this->zip($files);
}
/**
* 工作表名安全化:Excel 限制 31 字符、禁止 []:*?/\、不可重复、不可为空
*/
private static function safeSheetName(string $name, int $seq, array $existing): string
{
$bad = ['\\', '/', '?', '*', '[', ']', ':'];
$n = trim(str_replace($bad, '_', $name));
if ($n === '') {
$n = 'Sheet' . $seq;
}
if (function_exists('mb_substr')) {
$n = mb_substr($n, 0, 31, 'UTF-8');
} else {
$n = substr($n, 0, 31);
}
// 去重
$base = $n;
$i = 2;
$taken = [];
foreach ($existing as $e) {
$taken[strtolower($e['name'])] = true;
}
while (isset($taken[strtolower($n)])) {
$suffix = '(' . $i . ')';
$n = (function_exists('mb_substr') ? mb_substr($base, 0, 31 - strlen($suffix), 'UTF-8') : substr($base, 0, 31 - strlen($suffix))) . $suffix;
$i++;
}
return $n;
}
private function intern(string $s): int
{
if (!array_key_exists($s, $this->strIndex)) {
@@ -87,13 +160,13 @@ final class XlsxWriter
return $this->strIndex[$s];
}
private function sheetXml(array $cells, int $maxRow, int $maxCol): string
private function sheetXml(array $cells, int $maxRow, int $maxCol, array $widths = []): string
{
$dim = 'A1:' . self::colName($maxCol) . $maxRow;
$cols = '';
for ($c = 1; $c <= $maxCol; $c++) {
$w = $this->widths[$c - 1] ?? 16;
$w = $widths[$c - 1] ?? 16;
$cols .= '<col min="' . $c . '" max="' . $c . '" width="' . $w . '" customWidth="1"/>';
}
@@ -126,14 +199,19 @@ final class XlsxWriter
'</worksheet>';
}
private function contentTypesXml(): string
private function contentTypesXml(int $sheetCount): string
{
$overrides = '';
for ($i = 1; $i <= max(1, $sheetCount); $i++) {
$overrides .= '<Override PartName="/xl/worksheets/sheet' . $i . '.xml" ' .
'ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
}
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n" .
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' .
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' .
'<Default Extension="xml" ContentType="application/xml"/>' .
'<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>' .
'<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>' .
$overrides .
'<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>' .
'<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>' .
'<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>' .
@@ -151,22 +229,36 @@ final class XlsxWriter
'</Relationships>';
}
private function workbookXml(string $title): string
/** @param array<int,string> $names 工作表名(已安全化) */
private function workbookXml(array $names): string
{
$sheets = '';
foreach (array_values($names) as $i => $nm) {
$n = (int)$i + 1;
$sheets .= '<sheet name="' . self::xml((string)$nm) . '" sheetId="' . $n . '" r:id="rId' . $n . '"/>';
}
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n" .
'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ' .
'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' .
'<sheets><sheet name="' . self::xml($title) . '" sheetId="1" r:id="rId1"/></sheets>' .
'<sheets>' . $sheets . '</sheets>' .
'</workbook>';
}
private function workbookRelsXml(): string
private function workbookRelsXml(int $sheetCount): string
{
$rels = '';
for ($i = 1; $i <= max(1, $sheetCount); $i++) {
$rels .= '<Relationship Id="rId' . $i . '" ' .
'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" ' .
'Target="worksheets/sheet' . $i . '.xml"/>';
}
$stylesId = max(1, $sheetCount) + 1;
$sstId = max(1, $sheetCount) + 2;
return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n" .
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' .
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>' .
'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' .
'<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>' .
$rels .
'<Relationship Id="rId' . $stylesId . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' .
'<Relationship Id="rId' . $sstId . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>' .
'</Relationships>';
}