1
0
mirror of https://github.com/suk-ws/ph-Bookshelf.git synced 2025-03-15 07:47:30 +08:00
ph-Bookshelf/src/Element/BookCollection.php
Eyre_S 6a5b4937c9
完成了请求链接解析和当前 book 的目录生成
- 基础的请求链接解析实现
  - 当前链接解析将第一个参数(首目录)视为 bookId,剩余视为 pageId
    - 即不支持 bookId中包含“/”
  - 同时实现了 books 的 active 判定
- 实现了通过 ID 进行查询容器中的 Book 或者 Page 的功能
- 实现了通过 Book对象 获取对应的 BookContented 对象
- 实现了 BookContented 的目录表生成
  - 同时也有 active 判定
2021-04-26 22:02:22 +08:00

99 lines
2.4 KiB
PHP

<?php
require_once "./src/Element/Book.php";
class BookCollection {
const ROOT = "%root";
private string $name;
/** @var Book[]|BookCollection[] */
private array $array;
private ?BookCollection $parent;
private function __construct (string $name, ?BookCollection $parent) {
$this->name = $name;
$this->array = array();
$this->parent = $parent;
}
/**
* @param DOMNode $root
* @param ?BookCollection $parent
* @param bool $isRoot
* @return BookCollection
* @throws Exception
*/
public static function parse (DOMNode $root, ?BookCollection $parent, bool $isRoot = false): BookCollection {
$name = BookCollection::ROOT;
if (!$isRoot) {
if ($root->hasAttributes()) {
$attrName = $root->attributes->getNamedItem("name");
if ($attrName == null) throw new Exception("BookCollection (not root) xml data missing attribute \"name\"");
else $name = $attrName->nodeValue;
} else throw new Exception("BookCollection (not root) xml data missing attributes");
}
$node = new BookCollection($name, $parent);
for ($child = $root->firstChild; $child != null; $child = $child->nextSibling) {
switch ($child->nodeName) {
case "Book":
array_push($node->array, Book::parse($child, $node));
break;
case "Collection":
array_push($node->array, BookCollection::parse($child, $node));
break;
case "#text":
break;
default:
throw new Exception("Unsupported element type \"$child->nodeName\" in BookCollection named \"$name\"");
}
}
return $node;
}
public function getName (): string {
return $this->name;
}
/**
* @return Book[]|BookCollection[]
*/
public function getCollection (): array {
return $this->array;
}
/**
* @return BookCollection|null
*/
public function getParent (): BookCollection {
return $this->parent;
}
public function getHtml (): string {
$str = "";
if ($this->name != self::ROOT) $str .= "<li><a class='book-collection' href='#'>$this->name</a><ul class='book-collection summary'>";
foreach ($this->array as $node) {
$str .= $node->getHtml();
}
if ($this->name != self::ROOT) $str .= "</ul></li>";
return $str;
}
public function getBook (string $id): ?Book {
foreach ($this->array as $node) {
if ($node instanceof Book && $node->getId() == $id)
return $node;
else if ($node instanceof BookCollection) {
$got = $node->getBook($id);
if ($got != null) return $got;
}
}
return null;
}
}