|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace TwigA11y\Rules\Structure; |
| 6 | + |
| 7 | +use TwigA11y\Rules\AbstractA11yRule; |
| 8 | +use TwigCsFixer\Token\Token; |
| 9 | +use TwigCsFixer\Token\Tokens; |
| 10 | + |
| 11 | +final class LandmarkRule extends AbstractA11yRule |
| 12 | +{ |
| 13 | + public function evaluate(Tokens $tokens, int $tokenIndex, callable $emit): void |
| 14 | + { |
| 15 | + $token = $tokens->get($tokenIndex); |
| 16 | + |
| 17 | + if (!$token->isMatching(Token::TEXT_TYPE)) { |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + $value = $token->getValue(); |
| 22 | + |
| 23 | + // Detect presence of main landmark or role="main" |
| 24 | + if (str_contains($value, '<main') || str_contains($value, 'role="main"') || str_contains($value, "role='main'")) { |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + // If we encounter the end of head/body start, and haven't seen |
| 29 | + // a main landmark previously, emit a missing landmark warning. |
| 30 | + if (str_contains($value, '<body') || str_contains($value, '</head>')) { |
| 31 | + // Simple approach: scan a small window ahead to see if a main is present |
| 32 | + $look = $this->collectUntil($tokenIndex, $tokens, '<main', 200); |
| 33 | + if (!str_contains($look, '<main') && !preg_match('/role\s*=\s*["\']main["\']/i', $look)) { |
| 34 | + // Emit at the start of the file for consistency with other |
| 35 | + // page-level rules (tests expect line 1:1 identifiers). |
| 36 | + $first = $tokens->get(0); |
| 37 | + $emit('Page should include a main landmark', $first, 'Landmark.MissingMain'); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + protected function process(int $tokenIndex, Tokens $tokens): void |
| 43 | + { |
| 44 | + $emit = function (string $message, Token $token, ?string $id = null): void { |
| 45 | + $this->addError($message, $token, $id); |
| 46 | + }; |
| 47 | + |
| 48 | + $this->evaluate($tokens, $tokenIndex, $emit); |
| 49 | + } |
| 50 | +} |
0 commit comments