Major upgrade v2.0.0

This commit is contained in:
Enes Yakıştır
2026-05-13 09:10:43 +03:00
commit e348025579
41 changed files with 2139 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace YakNet\AccessibilityConsole\AI;
use Gemini;
use YakNet\AccessibilityConsole\Core\Violation;
class GeminiFixer
{
private ?\Gemini\Client $client = null;
public function __construct(private readonly ?string $apiKey)
{
if ($this->apiKey && class_exists(Gemini::class)) {
$this->client = Gemini::client($this->apiKey);
}
}
public function suggestFix(Violation $violation): ?string
{
if (!$this->client) {
return null;
}
$prompt = <<<PROMPT
You are a WCAG 2.1 Accessibility expert.
A scanner found an error in this HTML snippet:
Snippet: {$violation->htmlSnippet}
Error: {$violation->message}
Severity: {$violation->severity->value}
Standard: {$violation->standard->value}
Please provide ONLY the fixed version of the HTML snippet.
Do not explain, do not add markdown code blocks, just return the corrected HTML.
If the error is about missing 'alt' text, add a meaningful alt text based on context.
If it's about ARIA roles, add the correct ones.
PROMPT;
try {
$result = $this->client->geminiPro()->generateContent($prompt);
$suggestion = trim($result->text());
// Clean up if AI included markdown blocks anyway
$suggestion = preg_replace('/^```html\s*|\s*```$/i', '', $suggestion);
return $suggestion;
} catch (\Throwable $e) {
// Log error if needed
return null;
}
}
}
+136
View File
@@ -0,0 +1,136 @@
<?php
namespace YakNet\AccessibilityConsole\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\AI\GeminiFixer;
use YakNet\AccessibilityConsole\Core\Config;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Rules\StandardRuleSet;
use YakNet\AccessibilityConsole\Source\SourceLocator;
class FixCommand extends Command
{
protected function configure(): void
{
$this
->setName('fix')
->setDescription('Automatically fix accessibility violations using AI')
->addArgument('target', InputArgument::REQUIRED, 'The URL or file path to scan')
->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping')
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Show what would be fixed without modifying files');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$target = $input->getArgument('target');
$projectPath = $input->getOption('project-path') ?? getcwd();
$dryRun = $input->getOption('dry-run');
$config = new Config();
$apiKey = $config->getGeminiApiKey();
if (!$apiKey) {
$io->error("GEMINI_API_KEY not found in .env or environment variables. AI fixing requires an API key.");
return Command::FAILURE;
}
$io->title("AI Self-Healing Mode - Fixing: $target");
// 1. Fetch HTML
$html = @file_get_contents($target);
if (!$html) {
$io->error("Could not read target: $target");
return Command::FAILURE;
}
// 2. Scan
$scanner = new Scanner();
foreach (StandardRuleSet::all() as $rule) {
$scanner->addRule($rule);
}
$violations = $scanner->scan($html);
if (empty($violations)) {
$io->success("Everything looks good! No violations to fix.");
return Command::SUCCESS;
}
$io->note("Found " . count($violations) . " violations. Starting AI analysis...");
$fixer = new GeminiFixer($apiKey);
$locator = new SourceLocator($projectPath);
$fixedCount = 0;
foreach ($violations as $violation) {
$io->write("Analyzing <fg=yellow>{$violation->ruleId}</>... ");
// Locate source
$location = $locator->locate($violation->htmlSnippet);
if (!$location) {
$io->writeln("<fg=red>Skipped (Source not found)</>");
continue;
}
// Get AI Suggestion
$suggestion = $fixer->suggestFix($violation);
if (!$suggestion) {
$io->writeln("<fg=red>Skipped (AI could not generate fix)</>");
continue;
}
$io->writeln("<fg=green>Fix Found!</>");
$io->writeln(" <fg=gray>Original:</> <fg=red>" . htmlspecialchars(trim($violation->htmlSnippet)) . "</>");
$io->writeln(" <fg=gray>AI Fix: </> <fg=green>" . htmlspecialchars(trim($suggestion)) . "</>");
if ($dryRun) {
$io->writeln(" <fg=blue>[DRY RUN] File modification skipped.</>");
continue;
}
// Apply Fix
if ($this->applyFix($location['file'], $violation->htmlSnippet, $suggestion)) {
$io->writeln(" <fg=bright-green>✔ Applied to {$location['file']}:{$location['line']}</>");
$fixedCount++;
} else {
$io->writeln(" <fg=red>✘ Failed to apply fix to file.</>");
}
$io->writeln("");
}
if ($fixedCount > 0) {
$io->success("Self-healing complete! $fixedCount violations were automatically fixed.");
} else {
$io->warning("No files were modified. Check error logs for details.");
}
return Command::SUCCESS;
}
private function applyFix(string $filePath, string $originalSnippet, string $fixedSnippet): bool
{
$content = file_get_contents($filePath);
if ($content === false) return false;
// Try exact replacement first
if (str_contains($content, $originalSnippet)) {
$newContent = str_replace($originalSnippet, $fixedSnippet, $content);
} else {
// Fallback: Fuzzy replacement (simplified for this demo)
// In a real professional lib, we'd use more advanced regex or DOM patching
$newContent = str_replace(trim($originalSnippet), trim($fixedSnippet), $content);
}
if ($newContent === $content) {
return false;
}
return file_put_contents($filePath, $newContent) !== false;
}
}
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace YakNet\AccessibilityConsole\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\AI\GeminiFixer;
use YakNet\AccessibilityConsole\Core\Config;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Rules\StandardRuleSet;
use YakNet\AccessibilityConsole\Source\SourceLocator;
class ScanCommand extends Command
{
protected static $defaultName = 'scan';
protected function configure(): void
{
$this
->setName('scan')
->setDescription('Scan a URL or file for accessibility violations')
->addArgument('target', InputArgument::REQUIRED, 'The URL or file path to scan')
->addOption('ai', null, InputOption::VALUE_NONE, 'Enable AI-powered fix suggestions')
->addOption('report', null, InputOption::VALUE_REQUIRED, 'Save report to file (html or json)')
->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$target = $input->getArgument('target');
$enableAi = $input->getOption('ai');
$projectPath = $input->getOption('project-path') ?? getcwd();
$io->title("Accessibility Console - Scanning: $target");
// 1. Fetch HTML
$html = @file_get_contents($target);
if (!$html) {
$io->error("Could not read target: $target");
return Command::FAILURE;
}
// 2. Setup Scanner
$scanner = new Scanner();
foreach (StandardRuleSet::all() as $rule) {
$scanner->addRule($rule);
}
// 3. Scan
$violations = $scanner->scan($html);
if (empty($violations)) {
$io->success("No violations found!");
return Command::SUCCESS;
}
$io->section("Found " . count($violations) . " violations");
// 4. Setup Helpers
$locator = new SourceLocator($projectPath);
$config = new Config();
$fixer = $enableAi ? new GeminiFixer($config->getGeminiApiKey()) : null;
foreach ($violations as $violation) {
$io->writeln("<fg=white;bg=red;options=bold> {$violation->ruleId} </>\t<fg=red>{$violation->message}</>");
// Show Snippet
$io->writeln(" <fg=gray>Snippet:</> <fg=yellow>" . htmlspecialchars($violation->htmlSnippet) . "</>");
// Source Mapping
$location = $locator->locate($violation->htmlSnippet);
if ($location) {
$io->writeln(" <fg=gray>Source:</> <fg=cyan>{$location['file']}:{$location['line']}</>");
}
// AI Fixer
if ($enableAi && $fixer) {
$io->write(" <fg=gray>AI Fix Suggestion:</> ");
$suggestion = $fixer->suggestFix($violation);
if ($suggestion) {
$io->writeln("<fg=green>" . htmlspecialchars($suggestion) . "</>");
} else {
$io->writeln("<fg=red>Could not generate suggestion (check API key)</>");
}
}
$io->writeln("");
}
$io->warning("Scanned " . count($violations) . " errors. Use --ai to get fix suggestions.");
// Export Report
$reportPath = $input->getOption('report');
if ($reportPath) {
$extension = pathinfo($reportPath, PATHINFO_EXTENSION);
if ($extension === 'json') {
$data = array_map(fn($v) => $v->toArray(), $violations);
file_put_contents($reportPath, json_encode($data, JSON_PRETTY_PRINT));
} else {
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
file_put_contents($reportPath, $reporter->render($violations, $target));
}
$io->success("Report saved to: $reportPath");
}
return Command::SUCCESS;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace YakNet\AccessibilityConsole\Core;
class Config
{
private array $settings = [];
public function __construct(array $settings = [])
{
$this->settings = $settings;
}
public static function fromYaml(string $path): self
{
// Placeholder for YAML loading logic
return new self([]);
}
public function get(string $key, mixed $default = null): mixed
{
return $this->settings[$key] ?? $default;
}
public function getGeminiApiKey(): ?string
{
return $this->get('gemini_api_key') ?? $_ENV['GEMINI_API_KEY'] ?? getenv('GEMINI_API_KEY') ?: null;
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace YakNet\AccessibilityConsole\Core;
use YakNet\AccessibilityConsole\Rules\RuleInterface;
class RuleEngine
{
/** @var RuleInterface[] */
private array $rules = [];
public function addRule(RuleInterface $rule): void
{
$this->rules[] = $rule;
}
/**
* @return RuleInterface[]
*/
public function getRules(): array
{
return $this->rules;
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace YakNet\AccessibilityConsole\Core;
use DOMDocument;
use YakNet\AccessibilityConsole\Rules\RuleInterface;
class Scanner
{
private array $rules = [];
public function __construct(
private readonly ?RuleEngine $engine = null
) {
if ($this->engine) {
$this->rules = $this->engine->getRules();
}
}
public function addRule(RuleInterface $rule): void
{
$this->rules[] = $rule;
}
/**
* @return Violation[]
*/
public function scan(string $html): array
{
if (trim($html) === '') {
return [];
}
$dom = new DOMDocument();
$previousState = libxml_use_internal_errors(true);
$loaded = $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html, LIBXML_NOERROR | LIBXML_NOWARNING);
libxml_clear_errors();
libxml_use_internal_errors($previousState);
if (!$loaded) {
return [];
}
$violations = [];
$elements = $dom->getElementsByTagName('*');
foreach ($elements as $element) {
if (!$element instanceof \DOMElement) continue;
foreach ($this->rules as $rule) {
try {
$violation = $rule->check($element);
if ($violation) {
$violations[] = $violation;
}
} catch (\Throwable) {
continue;
}
}
}
return $violations;
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace YakNet\AccessibilityConsole\Core;
enum Severity: string
{
case INFO = 'info';
case WARNING = 'warning';
case ERROR = 'error';
case CRITICAL = 'critical';
public function color(): string
{
return match($this) {
self::INFO => 'info',
self::WARNING => 'comment',
self::ERROR => 'error',
self::CRITICAL => 'error',
};
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace YakNet\AccessibilityConsole\Core;
readonly class Violation
{
public function __construct(
public string $ruleId,
public string $message,
public Severity $severity,
public WCAGStandard $standard,
public string $htmlSnippet,
public ?array $location = null, // ['file' => '...', 'line' => 0]
public ?string $fixSuggestion = null
) {}
public function toArray(): array
{
return [
'ruleId' => $this->ruleId,
'message' => $this->message,
'severity' => $this->severity->value,
'standard' => $this->standard->value,
'htmlSnippet' => $this->htmlSnippet,
'location' => $this->location,
'fixSuggestion' => $this->fixSuggestion,
];
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace YakNet\AccessibilityConsole\Core;
enum WCAGStandard: string
{
case A = 'A';
case AA = 'AA';
case AAA = 'AAA';
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace YakNet\AccessibilityConsole\Reporting;
use YakNet\AccessibilityConsole\Core\Violation;
class HtmlDashboardReporter
{
/**
* @param Violation[] $violations
*/
public function render(array $violations, string $target): string
{
$count = count($violations);
$date = date('Y-m-d H:i:s');
$rows = '';
foreach ($violations as $v) {
$severityClass = strtolower($v->severity->value);
$rows .= "
<tr class='severity-{$severityClass}'>
<td><span class='badge'>{$v->ruleId}</span></td>
<td>{$v->message}</td>
<td><pre><code>" . htmlspecialchars($v->htmlSnippet) . "</code></pre></td>
<td>" . ($v->location ? "{$v->location['file']}:{$v->location['line']}" : 'N/A') . "</td>
</tr>";
}
return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A11y Report - {$target}</title>
<style>
body { font-family: 'Inter', sans-serif; background: #f4f7f6; color: #333; margin: 0; padding: 20px; }
.container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
h1 { color: #2c3e50; margin-top: 0; }
.summary { display: flex; gap: 20px; margin-bottom: 30px; }
.card { background: #3498db; color: white; padding: 20px; border-radius: 8px; flex: 1; text-align: center; }
.card.error { background: #e74c3c; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { text-align: left; padding: 12px; border-bottom: 1px solid #eee; }
th { background: #f8f9fa; }
pre { background: #272822; color: #f8f8f2; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 12px; }
.badge { background: #34495e; color: white; padding: 4px 8px; border-radius: 4px; font-size: 11px; }
.severity-error { background: #fff5f5; }
</style>
</head>
<body>
<div class="container">
<h1>Accessibility Report</h1>
<p>Target: <strong>{$target}</strong> | Generated: {$date}</p>
<div class="summary">
<div class="card error">
<h2>{$count}</h2>
<p>Violations Found</p>
</div>
<div class="card">
<h2>WCAG 2.1</h2>
<p>Standard Level</p>
</div>
</div>
<table>
<thead>
<tr>
<th>Rule ID</th>
<th>Issue</th>
<th>Code Snippet</th>
<th>Source Location</th>
</tr>
</thead>
<tbody>
{$rows}
</tbody>
</table>
</div>
</body>
</html>
HTML;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
abstract class AbstractRule implements RuleInterface
{
abstract public function getId(): string;
abstract public function getDescription(): string;
abstract public function getStandard(): WCAGStandard;
abstract public function getSeverity(): Severity;
protected function createViolation(DOMElement $element, string $message, ?string $suggestion = null): Violation
{
return new Violation(
ruleId: $this->getId(),
message: $message,
severity: $this->getSeverity(),
standard: $this->getStandard(),
htmlSnippet: $element->ownerDocument->saveHTML($element),
fixSuggestion: $suggestion
);
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class ButtonName extends AbstractRule
{
public function getId(): string { return 'WCAG_4_1_2_BUTTON'; }
public function getDescription(): string { return 'Buttons must have discernible text.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'button') {
return null;
}
$text = trim($element->textContent);
if ($text === '' && !$element->hasAttribute('aria-label') && !$element->hasAttribute('title')) {
return $this->createViolation($element, $this->getDescription(), 'Add text or an aria-label to the button.');
}
return null;
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class EmptyLink extends AbstractRule
{
public function getId(): string { return 'WCAG_2_4_4_LINK_TEXT'; }
public function getDescription(): string { return 'Links must have discernible text.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'a') {
return null;
}
$text = trim($element->textContent);
if ($text === '' && !$element->hasAttribute('aria-label') && !$element->hasAttribute('title')) {
// Check for images inside
$imgs = $element->getElementsByTagName('img');
foreach ($imgs as $img) {
if ($img->hasAttribute('alt') && trim($img->getAttribute('alt')) !== '') {
return null;
}
}
return $this->createViolation($element, $this->getDescription(), 'Add text content or an aria-label to the link.');
}
return null;
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class FieldsetLegend extends AbstractRule
{
public function getId(): string { return 'WCAG_1_3_1_FIELDSET'; }
public function getDescription(): string { return 'Fieldsets should have a legend.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::WARNING; }
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'fieldset') {
return null;
}
$legends = $element->getElementsByTagName('legend');
if ($legends->length === 0) {
return $this->createViolation($element, $this->getDescription(), 'Add a <legend> inside the fieldset.');
}
return null;
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class FormLabel extends AbstractRule
{
public function getId(): string { return 'WCAG_1_3_1_LABEL'; }
public function getDescription(): string { return 'Form inputs must have an associated label.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function check(DOMElement $element): ?Violation
{
$tags = ['input', 'select', 'textarea'];
if (!in_array(strtolower($element->tagName), $tags)) {
return null;
}
// Skip hidden inputs and buttons
$type = strtolower($element->getAttribute('type'));
if ($type === 'hidden' || $type === 'submit' || $type === 'button' || $type === 'reset') {
return null;
}
if ($element->hasAttribute('id')) {
$id = $element->getAttribute('id');
$xpath = new \DOMXPath($element->ownerDocument);
$labels = $xpath->query("//label[@for='$id']");
if ($labels->length > 0) {
return null;
}
}
// Check for aria-label or aria-labelledby
if ($element->hasAttribute('aria-label') || $element->hasAttribute('aria-labelledby')) {
return null;
}
// Check if wrapped in label
$parent = $element->parentNode;
while ($parent) {
if ($parent instanceof DOMElement && strtolower($parent->tagName) === 'label') {
return null;
}
$parent = $parent->parentNode;
}
return $this->createViolation($element, $this->getDescription(), 'Add a <label for="..."> or an aria-label attribute.');
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class HeadingOrder extends AbstractRule
{
private static int $lastLevel = 0;
public function getId(): string { return 'WCAG_1_3_1_HEADING'; }
public function getDescription(): string { return 'Headings should follow a logical nesting order.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::WARNING; }
public function check(DOMElement $element): ?Violation
{
if (!preg_match('/^h([1-6])$/i', $element->tagName, $matches)) {
return null;
}
$currentLevel = (int)$matches[1];
// This rule is a bit complex in a per-element check without global state,
// but we can at least check if an h2 comes before an h1 in some cases or jumps.
// For simplicity in this engine, we warn if it's not starting with H1 or jumps too many levels.
if ($currentLevel > self::$lastLevel + 1 && self::$lastLevel !== 0) {
$violation = $this->createViolation($element, "Heading level h$currentLevel jumps from h" . self::$lastLevel, "Ensure headings follow a logical order (h1, then h2, etc.)");
self::$lastLevel = $currentLevel;
return $violation;
}
self::$lastLevel = $currentLevel;
return null;
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class HtmlHasLang extends AbstractRule
{
public function getId(): string { return 'WCAG_3_1_1_LANG'; }
public function getDescription(): string { return 'The html element must have a lang attribute.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'html') {
return null;
}
if (!$element->hasAttribute('lang') || trim($element->getAttribute('lang')) === '') {
return $this->createViolation($element, $this->getDescription(), 'Add lang="en" (or your language) to the html tag.');
}
return null;
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class ImgAltText extends AbstractRule
{
public function getId(): string { return 'WCAG_1_1_1_ALT'; }
public function getDescription(): string { return 'Images must have an alt attribute.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'img') {
return null;
}
if (!$element->hasAttribute('alt')) {
// Check for decorative roles
$role = $element->getAttribute('role');
if ($role === 'presentation' || $role === 'none') {
return null;
}
return $this->createViolation($element, $this->getDescription(), 'Add an alt attribute. Use alt="" for decorative images.');
}
return null;
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class MetaViewport extends AbstractRule
{
public function getId(): string { return 'A11Y_VIEWPORT'; }
public function getDescription(): string { return 'Viewport meta tag should not disable zooming.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::AA; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'meta' || $element->getAttribute('name') !== 'viewport') {
return null;
}
$content = $element->getAttribute('content');
if (str_contains($content, 'user-scalable=no') || str_contains($content, 'maximum-scale=1')) {
return $this->createViolation($element, $this->getDescription(), 'Remove user-scalable=no or maximum-scale=1 to allow users to zoom.');
}
return null;
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Violation;
interface RuleInterface
{
public function getId(): string;
public function check(DOMElement $element): ?Violation;
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
class StandardRuleSet
{
/**
* @return RuleInterface[]
*/
public static function all(): array
{
return [
new HtmlHasLang(),
new ImgAltText(),
new EmptyLink(),
new ButtonName(),
new FormLabel(),
new FieldsetLegend(),
new HeadingOrder(),
new MetaViewport(),
];
}
}
+158
View File
@@ -0,0 +1,158 @@
<?php
namespace YakNet\AccessibilityConsole\Source;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
class SourceLocator
{
private array $extensions = ['php', 'html', 'twig', 'blade.php'];
public function __construct(
private readonly string $searchPath
) {}
public function locate(string $snippet): ?array
{
if (!is_dir($this->searchPath) || !is_readable($this->searchPath)) {
return null;
}
$cleanSnippet = trim(preg_replace('/\s+/', ' ', $snippet));
if ($cleanSnippet === '') {
return null;
}
$searchSnippet = mb_strlen($cleanSnippet) > 150 ? mb_substr($cleanSnippet, 0, 150) : $cleanSnippet;
try {
$directory = new RecursiveDirectoryIterator($this->searchPath, \FilesystemIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
} catch (\UnexpectedValueException) {
return null;
}
$bestFuzzyMatch = null;
$highestScore = 0;
foreach ($iterator as $file) {
/** @var SplFileInfo $file */
if ($file->isDir()) {
continue;
}
if (!$this->isValidExtension($file->getFilename())) {
continue;
}
try {
$result = $this->searchInFile($file->getPathname(), $searchSnippet, $cleanSnippet);
if ($result['type'] === 'exact') {
return $result['location'];
}
if ($result['type'] === 'fuzzy' && $result['score'] > $highestScore) {
$highestScore = $result['score'];
$bestFuzzyMatch = $result['location'];
}
} catch (\Throwable) {
continue;
}
}
return ($bestFuzzyMatch && $highestScore >= 2) ? $bestFuzzyMatch : null;
}
private function isValidExtension(string $filename): bool
{
foreach ($this->extensions as $ext) {
if (str_ends_with($filename, $ext)) {
return true;
}
}
return false;
}
private function searchInFile(string $filepath, string $searchSnippet, string $fullSnippet): array
{
$content = file_get_contents($filepath);
if ($content === false) {
return ['type' => 'none'];
}
$lines = explode("\n", $content);
$parsedSnippet = $this->parseSnippet($fullSnippet);
$bestLine = 0;
$maxScore = 0;
foreach ($lines as $index => $line) {
$lineNumber = $index + 1;
$cleanLine = trim(preg_replace('/\s+/', ' ', $line));
if (str_contains($cleanLine, $searchSnippet)) {
return [
'type' => 'exact',
'location' => ['file' => $filepath, 'line' => $lineNumber]
];
}
$score = $this->calculateFuzzyScore($cleanLine, $parsedSnippet);
if ($score > $maxScore) {
$maxScore = $score;
$bestLine = $lineNumber;
}
}
if ($maxScore > 0) {
return [
'type' => 'fuzzy',
'score' => $maxScore,
'location' => ['file' => $filepath, 'line' => $bestLine]
];
}
return ['type' => 'none'];
}
private function parseSnippet(string $snippet): array
{
preg_match('/<([a-zA-Z0-9]+)/', $snippet, $matches);
$tagName = $matches[1] ?? null;
preg_match_all('/([a-zA-Z0-9-]+)=["\']([^"\']*)["\']/', $snippet, $matches, PREG_SET_ORDER);
$attributes = [];
foreach ($matches as $match) {
$attributes[$match[1]] = $match[2];
}
return ['tag' => $tagName, 'attributes' => $attributes];
}
private function calculateFuzzyScore(string $line, array $parsed): float
{
if (!$parsed['tag'] || !str_contains(strtolower($line), '<' . strtolower($parsed['tag']))) {
return 0;
}
$score = 1.0;
if (in_array(strtolower($parsed['tag']), ['html', 'head', 'body', 'title'])) {
$score += 1.0;
}
foreach ($parsed['attributes'] as $name => $value) {
if (str_contains($line, "$name=\"$value\"") || str_contains($line, "$name='$value'")) {
$score += 2.0;
} elseif (str_contains($line, $name . '=')) {
$score += 0.5;
}
}
return $score;
}
}