|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com> |
| 5 | + * SPDX-License-Identifier: MIT |
| 6 | + */ |
| 7 | + |
| 8 | +declare(strict_types=1); |
| 9 | + |
| 10 | +namespace Respect\Dev\Markdown\Linters; |
| 11 | + |
| 12 | +use Respect\Dev\Markdown\Content; |
| 13 | +use Respect\Dev\Markdown\File; |
| 14 | +use Respect\Dev\Markdown\Linter; |
| 15 | + |
| 16 | +use function array_keys; |
| 17 | +use function array_unique; |
| 18 | +use function basename; |
| 19 | +use function dirname; |
| 20 | +use function file_get_contents; |
| 21 | +use function in_array; |
| 22 | +use function preg_match_all; |
| 23 | +use function sort; |
| 24 | +use function sprintf; |
| 25 | +use function str_contains; |
| 26 | +use function str_ends_with; |
| 27 | + |
| 28 | +final readonly class ValidatorRelatedLinter implements Linter |
| 29 | +{ |
| 30 | + public function lint(File $file): File |
| 31 | + { |
| 32 | + if (!str_contains($file->filename, '/validators/') || str_ends_with($file->filename, '/validators/index.md')) { |
| 33 | + return $file; |
| 34 | + } |
| 35 | + |
| 36 | + $validator = basename($file->filename, '.md'); |
| 37 | + $relatedValidators = $this->getRelatedValidators($validator); |
| 38 | + |
| 39 | + if ($relatedValidators === []) { |
| 40 | + return $file; |
| 41 | + } |
| 42 | + |
| 43 | + $content = new Content(); |
| 44 | + $content->paragraph('See also:'); |
| 45 | + $content->emptyLine(); |
| 46 | + foreach ($relatedValidators as $relatedValidator) { |
| 47 | + $content->anchorListItem($relatedValidator, $relatedValidator . '.md'); |
| 48 | + } |
| 49 | + |
| 50 | + $content->emptyLine(); |
| 51 | + |
| 52 | + return $file->withContent($file->content->withSection($content)); |
| 53 | + } |
| 54 | + |
| 55 | + /** @return array<string> */ |
| 56 | + private function getRelatedValidators(string $validator): array |
| 57 | + { |
| 58 | + $docsDirectory = dirname(__DIR__, 3) . '/docs'; |
| 59 | + $filename = sprintf('%s/validators/%s.md', $docsDirectory, $validator); |
| 60 | + $content = file_get_contents($filename); |
| 61 | + if ($content === false) { |
| 62 | + return []; |
| 63 | + } |
| 64 | + |
| 65 | + $relatedValidators = []; |
| 66 | + |
| 67 | + preg_match_all('/\[([^\]]+)\]\(([^\)]+\.md)\)/', $content, $matches); |
| 68 | + foreach (array_keys($matches[0]) as $key) { |
| 69 | + $related = $matches[1][$key]; |
| 70 | + $document = $matches[2][$key]; |
| 71 | + if (str_contains($document, '/') || in_array($related, $relatedValidators)) { |
| 72 | + continue; |
| 73 | + } |
| 74 | + |
| 75 | + $relatedValidators[] = $related; |
| 76 | + } |
| 77 | + |
| 78 | + $relatedValidators = array_unique($relatedValidators); |
| 79 | + sort($relatedValidators); |
| 80 | + |
| 81 | + return $relatedValidators; |
| 82 | + } |
| 83 | +} |
0 commit comments