forked from coding/coding-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfluence.php
More file actions
91 lines (80 loc) · 2.93 KB
/
Copy pathConfluence.php
File metadata and controls
91 lines (80 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
namespace App;
use JetBrains\PhpStorm\ArrayShape;
use League\HTMLToMarkdown\HtmlConverter;
use phpDocumentor\Reflection\Types\Array_;
class Confluence
{
private \DOMDocument $document;
private HtmlConverter $htmlConverter;
private array $pageTitles;
public function __construct(\DOMDocument $document = null, HtmlConverter $htmlConverter = null)
{
$this->document = $document ?? new \DOMDocument();
$this->htmlConverter = $htmlConverter ?? new HtmlConverter();
$this->htmlConverter->getConfig()->setOption('strip_tags', true);
}
public function parsePageHtml(string $filename, string $spaceName): array
{
libxml_use_internal_errors(true);
$this->document->loadHTMLFile($filename);
$title = trim($this->document->getElementById('title-text')->nodeValue);
$title = str_replace($spaceName . ' : ', '', $title);
$content = trim($this->document->getElementById('main-content')->nodeValue);
return [
'title' => $title,
'content' => $content,
];
}
public function htmlFile2Markdown(string $filename)
{
libxml_use_internal_errors(true);
$this->document->loadHTMLFile($filename);
$html = $this->document->saveHTML($this->document->getElementById('main-content'));
return $this->htmlConverter->convert($html);
}
/**
* @return array ['tree' => "array", 'titles' => "array"]
*/
public function parseAvailablePages(string $filename): array
{
$this->document->loadHTMLFile($filename);
$divElements = $this->document->getElementById('content')->getElementsByTagName('div');
$divElement = null;
foreach ($divElements as $divElement) {
if ($divElement->getAttribute('class') != 'pageSection') {
continue;
}
$h2Element = $divElement->getElementsByTagName('h2')[0];
if (!empty($h2Element) && $h2Element->nodeValue == 'Available Pages:') {
break;
}
}
if (empty($divElement)) {
return [
'tree' => [],
'titles' => [],
];
}
$xpath = new \DOMXPath($this->document);
return [
'tree' => $this->parsePagesTree($xpath, $divElement),
'titles' => $this->pageTitles,
];
}
public function parsePagesTree(\DOMXPath $xpath, \DOMElement $parentElement)
{
$liElements = $xpath->query('ul/li', $parentElement);
if ($liElements->count() == 0) {
return [];
}
$tree = [];
foreach ($liElements as $liElement) {
$aElement = $xpath->query('a', $liElement)->item(0);
$href = $aElement->getAttribute('href');
$this->pageTitles[$href] = $aElement->nodeValue;
$tree[$href] = $this->parsePagesTree($xpath, $liElement);
}
return $tree;
}
}