-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBreadcrumbsHelper.php
349 lines (316 loc) · 11.4 KB
/
BreadcrumbsHelper.php
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
<?php
declare(strict_types=1);
namespace BumbleDocGen\Core\Renderer\Breadcrumbs;
use BumbleDocGen\Core\Cache\LocalCache\Exception\ObjectNotFoundException;
use BumbleDocGen\Core\Cache\LocalCache\LocalObjectCache;
use BumbleDocGen\Core\Configuration\Configuration;
use BumbleDocGen\Core\Configuration\Exception\InvalidConfigurationParameterException;
use BumbleDocGen\Core\Plugin\Event\Renderer\OnGetProjectTemplatesDirs;
use BumbleDocGen\Core\Plugin\PluginEventDispatcher;
use BumbleDocGen\Core\Renderer\TemplateFile;
use DI\DependencyException;
use DI\NotFoundException;
use Symfony\Component\Finder\Finder;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
/**
* Helper entity for working with breadcrumbs
*/
final class BreadcrumbsHelper
{
/**
* The name template of the file that will be the entry point when switching between pages
*/
public const DEFAULT_PREV_PAGE_NAME_TEMPLATE = '/^((readme|index)\.(rst|md)\.twig)/i';
private array $keyUsageCount = [];
/**
* @param string $prevPageNameTemplate Index page for each child section
*/
public function __construct(
private Configuration $configuration,
private LocalObjectCache $localObjectCache,
private BreadcrumbsTwigEnvironment $breadcrumbsTwig,
private PluginEventDispatcher $pluginEventDispatcher,
private string $prevPageNameTemplate = self::DEFAULT_PREV_PAGE_NAME_TEMPLATE
) {
}
/**
* @throws InvalidConfigurationParameterException
*/
private function loadTemplateContent(string $templateName): string
{
$filePath = TemplateFile::getTemplatePathByRelativeDocPath(
$templateName,
$this->configuration,
$this->pluginEventDispatcher
);
try {
return $this->localObjectCache->getMethodCachedResult(__METHOD__, $filePath);
} catch (ObjectNotFoundException) {
}
$templateContent = file_get_contents($filePath) ?: '';
$this->localObjectCache->cacheMethodResult(__METHOD__, $filePath, $templateContent);
return $templateContent;
}
/**
* @throws NotFoundException
* @throws DependencyException
* @throws InvalidConfigurationParameterException
*/
private function getPrevPage(string $templateName): ?string
{
try {
return $this->localObjectCache->getMethodCachedResult(__METHOD__, $templateName);
} catch (ObjectNotFoundException) {
}
$code = $this->loadTemplateContent($templateName);
if (preg_match_all('/({%)( ?)(set)( )(prevPage)([ =]+)([\'"])(.*)(\'|")( %})/', $code, $matches)) {
$prevPageKey = array_reverse($matches[8])[0];
$prevPage = $this->getPageDocFileByKey($prevPageKey);
if ($prevPage) {
$this->localObjectCache->cacheMethodResult(__METHOD__, $templateName, $prevPage);
return $prevPage;
}
}
$pathParts = explode('/', $templateName);
array_pop($pathParts);
array_pop($pathParts);
$prevPage = null;
if ($pathParts) {
$subPath = count($pathParts) > 1 ? implode('/', $pathParts) : '';
$indexFile = $this->getFindIndexFileByRelativePath($subPath);
if ($indexFile) {
$prevPage = $subPath . "/{$indexFile}";
}
}
$this->localObjectCache->cacheMethodResult(__METHOD__, $templateName, $prevPage);
return $prevPage;
}
/**
* @throws InvalidConfigurationParameterException
*/
public function getNearestIndexFile(string $templateName): string
{
$pathParts = explode('/', $templateName);
array_pop($pathParts);
$subPath = implode('/', $pathParts);
$indexFile = $this->getFindIndexFileByRelativePath($subPath);
if (is_null($indexFile)) {
return $templateName;
}
return "{$subPath}/{$indexFile}";
}
/**
* @throws InvalidConfigurationParameterException
*/
private function getFindIndexFileByRelativePath(string $relativePath): ?string
{
$finder = Finder::create()
->name('*.twig')
->ignoreVCS(true)
->ignoreDotFiles(true)
->ignoreUnreadableDirs()
->depth(0)
->in($this->configuration->getTemplatesDir() . '/' . $relativePath);
$indexFile = null;
foreach ($finder->files() as $file) {
$indexFile = $file->getFileName();
if (preg_match($this->prevPageNameTemplate, $indexFile)) {
break;
}
}
return $indexFile;
}
/**
* Get the name of a template by its URL.
* Only templates with .twig extension are processed.
* The title is parsed from the `title` variable in the template
*
* @throws InvalidConfigurationParameterException
* @example
* // variable in template:
* // {% set title = 'Some template title' %}
*
* $breadcrumbsHelper->getTemplateTitle() == 'Some template title'; // is true
*/
public function getTemplateTitle(string $templateName): string
{
$code = $this->loadTemplateContent($templateName);
if (preg_match_all('/({%)( ?)(set)( )(title)([ =]+)([\'"])(.*)(\'|")( %})/', $code, $matches)) {
return array_reverse($matches[8])[0];
}
return pathinfo($templateName, PATHINFO_FILENAME);
}
/**
* @throws InvalidConfigurationParameterException
*/
public function getTemplateLinkKey(string $templateName): ?string
{
$code = $this->loadTemplateContent($templateName);
if (preg_match_all('/({%)( ?)(set)( )(linkKey)([ =]+)([\'"])(.*)(\'|")( %})/', $code, $matches)) {
return array_reverse($matches[8])[0];
}
return null;
}
/**
* Get breadcrumbs as an array
*
* @param string $filePatch
* @param bool $fromCurrent
*
* @return array<int, array{url: string, title: string}>
* @throws NotFoundException
* @throws DependencyException
* @throws InvalidConfigurationParameterException
*/
public function getBreadcrumbs(string $filePatch, bool $fromCurrent = true): array
{
$breadcrumbs = [];
do {
if (!$fromCurrent) {
$fromCurrent = true;
continue;
}
$filePatch = str_replace('.twig', '', $filePatch);
$breadcrumbs[] = [
'url' => $this->configuration->getPageLinkProcessor()->getAbsoluteUrl($filePatch),
'title' => $this->getTemplateTitle($filePatch),
];
} while ($filePatch = $this->getPrevPage($filePatch));
return array_reverse($breadcrumbs);
}
/**
* @throws NotFoundException
* @throws DependencyException
* @throws InvalidConfigurationParameterException
*/
public function getBreadcrumbsForTemplates(string $filePatch, bool $fromCurrent = true): array
{
$breadcrumbs = [];
do {
if (!$fromCurrent) {
$fromCurrent = true;
continue;
}
$filePatch = str_replace('.twig', '', $filePatch);
$templateFilePatch = TemplateFile::getTemplatePathByRelativeDocPath(
$filePatch,
$this->configuration,
$this->pluginEventDispatcher
);
$breadcrumbs[] = [
'template' => $templateFilePatch,
'title' => $this->getTemplateTitle($filePatch),
];
} while ($filePatch = $this->getPrevPage($filePatch));
return array_reverse($breadcrumbs);
}
/**
* @throws NotFoundException
* @throws DependencyException
* @throws InvalidConfigurationParameterException
*/
public function getAllPageLinks(): array
{
try {
return $this->localObjectCache->getMethodCachedResult(__METHOD__, '');
} catch (ObjectNotFoundException) {
}
$pageLinks = [];
$templatesDir = $this->configuration->getTemplatesDir();
$event = $this->pluginEventDispatcher->dispatch(new OnGetProjectTemplatesDirs([$templatesDir]));
$templatesDirs = $event->getTemplatesDirs();
$addLinkKey = function (string $key, $value) use (&$pageLinks) {
$pageLinks[$key] = $value;
$this->keyUsageCount[$key] ??= 0;
++$this->keyUsageCount[$key];
if (str_starts_with($key, '/')) {
$key = ltrim($key, '/');
$pageLinks[$key] = $value;
$this->keyUsageCount[$key] ??= 0;
++$this->keyUsageCount[$key];
}
};
$finder = Finder::create()
->ignoreVCS(true)
->ignoreDotFiles(true)
->ignoreUnreadableDirs()
->sortByName()
->in($event->getTemplatesDirs());
foreach ($finder->files() as $file) {
$filePatch = str_replace($templatesDirs, '', $file->getRealPath());
if (!str_ends_with($filePatch, '.twig')) {
continue;
}
$docFilePatch = str_replace('.twig', '', $filePatch);
$url = $this->configuration->getPageLinkProcessor()->getAbsoluteUrl($docFilePatch);
$title = $this->getTemplateTitle($filePatch);
$value = [
'url' => $url,
'title' => $title,
'doc_file' => $docFilePatch,
];
$addLinkKey($filePatch, $value);
$addLinkKey($docFilePatch, $value);
$addLinkKey($url, $value);
$addLinkKey($title, $value);
$linkKey = $this->getTemplateLinkKey($filePatch);
if ($linkKey) {
$addLinkKey($linkKey, $value);
}
}
$this->localObjectCache->cacheMethodResult(__METHOD__, '', $pageLinks);
return $pageLinks;
}
/**
* @throws DependencyException
* @throws InvalidConfigurationParameterException
* @throws NotFoundException
*/
public function getPageDataByKey(string $key): ?array
{
$pageLinks = $this->getAllPageLinks();
if (!isset($pageLinks[$key])) {
return null;
}
return $pageLinks[$key];
}
/**
* @throws DependencyException
* @throws InvalidConfigurationParameterException
* @throws NotFoundException
*/
public function getPageLinkByKey(string $key): ?string
{
$pageData = $this->getPageDataByKey($key);
return $pageData['url'] ?? null;
}
/**
* @throws DependencyException
* @throws InvalidConfigurationParameterException
* @throws NotFoundException
*/
public function getPageDocFileByKey(string $key): ?string
{
$pageData = $this->getPageDataByKey($key);
return $pageData['doc_file'] ?? null;
}
/**
* Returns an HTML string with rendered breadcrumbs
*
* @throws SyntaxError
* @throws NotFoundException
* @throws RuntimeError
* @throws DependencyException
* @throws LoaderError
* @throws InvalidConfigurationParameterException
*/
public function renderBreadcrumbs(string $currentPageTitle, string $filePatch, bool $fromCurrent = true): string
{
return $this->breadcrumbsTwig->render('breadcrumbs.html.twig', [
'currentPageTitle' => $currentPageTitle,
'breadcrumbs' => $this->getBreadcrumbs($filePatch, $fromCurrent),
]);
}
}