@@ -35,12 +35,44 @@ public function isCurrent(Chapter $other): bool
3535
3636 public function getSubChapters (): array
3737 {
38- preg_match_all ('/<h2.*>.*<a.*href="(?<uri>.*?)".*<\/span>(?<title>.*)<\/a><\/h2>/ ' , $ this ->currentChapter ->body , $ matches );
38+ // TODO: clean up
39+ preg_match_all ('/<h2.*>.*<a.*href="(?<uri>.*?)".*<\/span>(?<title>.*)<\/a><\/h2>/ ' , $ this ->currentChapter ->body , $ h2Matches );
40+ preg_match_all ('/<h3.*>.*<a.*href="(?<h3uri>.*?)".*<\/span>(?<h3title>.*)<\/a><\/h3>/ ' , $ this ->currentChapter ->body , $ h3Matches );
3941
4042 $ subChapters = [];
4143
42- foreach ($ matches [0 ] as $ key => $ match ) {
43- $ subChapters [$ matches ['uri ' ][$ key ]] = $ matches ['title ' ][$ key ];
44+ foreach ($ h2Matches [0 ] as $ key => $ match ) {
45+ $ h2Uri = $ h2Matches ['uri ' ][$ key ];
46+ $ h2Title = $ h2Matches ['title ' ][$ key ];
47+ $ subChapters [$ h2Uri ] = [
48+ 'title ' => $ h2Title ,
49+ 'children ' => [],
50+ ];
51+ }
52+
53+ foreach ($ h3Matches [0 ] as $ key => $ match ) {
54+ $ h3Uri = $ h3Matches ['h3uri ' ][$ key ];
55+ $ h3Title = $ h3Matches ['h3title ' ][$ key ];
56+ $ parentH2Uri = null ;
57+ $ h3Position = strpos ($ this ->currentChapter ->body , $ match );
58+
59+ foreach ($ h2Matches [0 ] as $ h2Key => $ h2Match ) {
60+ $ h2Position = strpos ($ this ->currentChapter ->body , $ h2Match );
61+ if ($ h2Position < $ h3Position ) {
62+ $ parentH2Uri = $ h2Matches ['uri ' ][$ h2Key ];
63+ } else {
64+ break ;
65+ }
66+ }
67+
68+ if ($ parentH2Uri !== null && isset ($ subChapters [$ parentH2Uri ])) {
69+ $ subChapters [$ parentH2Uri ]['children ' ][$ h3Uri ] = $ h3Title ;
70+ } else {
71+ $ subChapters [$ h3Uri ] = [
72+ 'title ' => $ h3Title ,
73+ 'children ' => [],
74+ ];
75+ }
4476 }
4577
4678 return $ subChapters ;
0 commit comments