diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..be263b5 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,35 @@ +# Changelog + +All notable changes to **YakNet Accessibility Console** are documented in this file. +This project adheres to [Semantic Versioning](https://semver.org/). + +## [4.0.0] - 2026-11-21 + +### Added +- **45 New Accessibility Rules (130 → 175 Total Rules):** + - WCAG 2.2 & interaction rules: `FocusAppearance` (2.4.13), `ConsistentHelp` (3.2.6), `MotionAnimationReduced` (2.3.3), `OrientationLockBanned` (1.3.4), `HoverFocusContentDismissible` (1.4.13), `CharacterKeyShortcuts` (2.1.4), `PointerCancellation` (2.5.2), `TimeoutWarning` (2.2.1), `FlashingContentBanned` (2.3.1), `TargetSpacingMinimum` (2.5.8). + - WAI-ARIA 1.2 & APG widget rules: `AriaTablistPattern`, `AriaComboboxPattern`, `AriaSwitchState`, `AriaSliderAttributes`, `AriaMenuPattern`, `AriaTreePattern`, `AriaBreadcrumbPattern`, `AriaModalBackdrop`, `AriaLivePoliteMisuse`, `AriaOwnsValidTarget`, `AriaActivedescendantValid`, `AriaDeprecatedRoles`. + - Semantic HTML5 & landmark rules: `ArticleAccessibleHeading`, `SectionAccessibleName`, `NavAccessibleName`, `HeaderMainNestedInvalid`, `HeadingLengthConcise`, `AbbreviationExpansion`, `BlockquoteCiteValid`, `TimeDatetimeValid`, `IframeSandboxAccessibility`, `DocumentHasH1`. + - Forms & cognitive rules: `InputTypeValidation`, `FormErrorSummary`, `CheckboxGroupFieldset`, `SelectOptionNotEmpty`, `TextareaAccessibleName`, `OutputForValid`, `ButtonTypeExplicit`, `LinkDownloadContext`. + - Typography & visual rules: `ColorContrastAAA` (1.4.6), `FontSizeMinimum`, `AllCapsLongText`, `JustifiedTextBanned`, `SvgFocusableIeEdge`. +- **VPAT 2.5 / ACR Generator (`src/Compliance/VpatReportGenerator.php` & `a11y vpat`):** Markdown, HTML, and JSON conformance reports aligned with WCAG 2.1/2.2, Revised Section 508, and EN 301 549. +- **8 New Regulatory & Sectoral Presets (3 → 11 Total):** `wcag22-aa`, `wcag22-aaa`, `eaa2025`, `bitv2`, `government`, `healthcare`, `banking`, `education`. +- **Policy Governance Engine (`src/Policy/PolicyEngine.php`):** Enforces `min_score`, `max_critical`, `max_errors`, `max_warnings`, `required_standards`, `banned_rules`, `severity_overrides`, and `principle_limits` from `a11y.yaml`. +- **Inline Suppression Directives (`src/Core/Suppression/InlineSuppressionParser.php`):** Supports `a11y-disable-next-line`, `a11y-disable-line`, `a11y-disable` / `a11y-enable`, and `a11y-disable-file` with audit trail logging. +- **Incremental Content-Hash Cache (`src/Cache/ScanCache.php`):** `--cache` & `--clear-cache` flags skip unchanged templates on repeat scans. +- **CI/CD Workflow Generator (`src/CI/CiWorkflowGenerator.php`):** `a11y init --ci=github|gitlab|azure|bitbucket` generates ready-to-use CI pipelines. +- **PHPUnit Testing Trait (`src/Testing/AccessibilityAssertions.php`):** Drop-in assertions (`assertHtmlAccessible`, `assertAccessibilityScoreAtLeast`, `assertMeetsAccessibilityPreset`, `assertNoAccessibilityRuleViolation`). +- **History Tracking & Regression Diff (`src/Analytics/HistoryTracker.php` & `a11y compare`):** Trend snapshots (`--save-history`) and PR regression comparisons (`--fail-on-regression`). +- **Vue SFC & React JSX/TSX Parsers (`VueParser`, `JsxParser`):** Native support for `.vue`, `.jsx`, and `.tsx` templates with 1:1 line mapping. +- **New CLI Commands (5 → 10 Total):** `vpat`, `compare`, `doctor`, `explain`, `presets`. +- **Checkstyle XML Formatter & Expanded Webhooks:** `CheckstyleFormatter`, `MicrosoftTeamsNotifier`, and HMAC-SHA256 signed `GenericWebhookNotifier`. +- **Expanded Offline Self-Healing:** 32 deterministic offline auto-fixes in `LocalHealer`. +- **Rule Execution Profiling:** `--profile` option powered by `RuleExecutionStats` inside `RuleEngine`. + +### Changed +- Standardized open-source organization metadata to **YakNet** across documentation, license, and report exporters. +- Fixed preset rule filtering in `ScanCommand` so preset-included and preset-excluded rules are fully enforced. +- Expanded `WcagDatabase` with WCAG 2.1/2.2 guidance and automatic prefix fallback lookup. + +## [3.3.0] - 2026-04-01 +- Added `LabelInName`, `RedundantEntry`, `TextSpacing` rules, SVG badges, initial presets, and Slack/Discord notifiers. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..abad434 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,42 @@ +# Contributing to YakNet Accessibility Console + +Thank you for your interest in contributing to **YakNet Accessibility Console**, an open-source accessibility analysis library maintained by **YakNet**. + +## Development Setup + +```bash +git clone https://github.com/y-packages/accessibility-console.git +cd accessibility-console +composer install +``` + +## Running Tests & Static Analysis + +All pull requests must pass both the full PHPUnit test suite and PHPStan Level 9 with zero errors: + +```bash +vendor/bin/phpunit +vendor/bin/phpstan analyse -l 9 src/ +php bin/a11y doctor +``` + +## Adding a New Accessibility Rule + +1. Create a rule class under `src/Rules/` extending `YakNet\AccessibilityConsole\Rules\AbstractRule` (element-level) or `YakNet\AccessibilityConsole\Core\AbstractRule` (document-level). +2. Assign a unique `getId()` following the `WCAG_

___` convention. +3. Provide accurate `getDescription()`, `getStandard()`, `getSeverity()`, and `getLevel()` metadata. +4. Add unit tests covering both non-compliant and compliant markup in `tests/Rules/`. +5. Verify rule registry integrity with `php bin/a11y doctor`. + +## Coding Standards + +- PHP 8.2+ with `declare(strict_types=1);` in new files. +- Full type annotations compatible with PHPStan Level 9. +- Keep documentation and user-facing messages clear, open-source friendly, and free of vendor lock-in. + +## Pull Request Process + +1. Fork the repository and create a feature branch (`git checkout -b feature/my-improvement`). +2. Write clear, focused commits. +3. Ensure `phpunit`, `phpstan`, and `bin/a11y doctor` all pass cleanly. +4. Open a Pull Request describing the motivation and test coverage. diff --git a/LICENSE b/LICENSE index 288f9dd..752b2dc 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 YakNet Bilişim +Copyright (c) 2026 YakNet Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 73be8ba..afa06c1 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,53 @@ -# YakNet Accessibility Console 3.3 (AI-Powered Static Analysis & WCAG 2.2 Linter) +# YakNet Accessibility Console 4.0 [![PHP Version](https://img.shields.io/badge/php-%5E8.2-blue.svg)](https://php.net) [![PHPStan](https://img.shields.io/badge/PHPStan-Level%209-brightgreen.svg)](https://phpstan.org) -[![Tests](https://img.shields.io/badge/PHPUnit-230%20passed-success.svg)](https://phpunit.de) -[![Rules](https://img.shields.io/badge/WCAG%20Rules-130%20Active-purple.svg)](https://www.w3.org/WAI/standards-guidelines/wcag/) +[![Rules](https://img.shields.io/badge/WCAG%20%26%20ARIA%20Rules-175%20Active-purple.svg)](https://www.w3.org/WAI/standards-guidelines/wcag/) +[![Presets](https://img.shields.io/badge/Compliance%20Presets-11-teal.svg)](#-mevzuat-ve-sektörel-ön-ayarlar-presets) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) -[![AI Powered](https://img.shields.io/badge/AI%20Self--Healing-Google%20Gemini-orange.svg)](https://ai.google.dev) +[![Open Source](https://img.shields.io/badge/Open%20Source-YakNet-orange.svg)](https://forum.yak.net.tr) -**YakNet Accessibility Console**, web projelerinizdeki erişilebilirlik (WCAG 2.1, 2.2 ve WAI-ARIA) ve HTML söz dizimi hatalarını statik olarak analiz eden, **130 benzersiz kural setiyle** denetleyen, kurumsal CI/CD kalite kapısı (Quality Gates) sunan ve **Yapay Zeka (Google Gemini AI) ile Çevrimdışı Deterministik Motor** desteğiyle kaynak kodunuzu otomatik tamir edebilen (Self-Healing) kurumsal düzeyde bir PHP statik analiz ve linter kütüphanesidir. +**YakNet Accessibility Console**, web uygulamalarındaki erişilebilirlik (WCAG 2.1, WCAG 2.2, WAI-ARIA 1.2, ARIA APG) ve HTML söz dizimi sorunlarını statik ve DOM tabanlı olarak analiz eden, **175 benzersiz kural**, **11 mevzuat/sektör uyumluluk profili**, **VPAT 2.5 (ACR) rapor üreticisi**, **politika yönetim motoru (Policy Engine)** ve **otomatik onarım (Offline & AI Self-Healing)** yetenekleri sunan açık kaynaklı bir PHP erişilebilirlik analiz platformudur. -PHPStan ve PHP-CS-Fixer esintili modern mimarisiyle; Laravel Blade (`.blade.php`), Twig (`.twig`), PHP (`.php`) ve standart HTML şablonlarınızı doğrudan tarar, baseline desteğiyle mevcut teknik borcu yönetir ve CI/CD pipeline süreçlerinize sıfır yapılandırmayla entegre olur. +**YakNet** tarafından açık kaynak topluluğu ve büyük ölçekli organizasyonların, kamu portallarının, üniversitelerin ve ürün ekiplerinin ortak standartlarla erişilebilir web yazılımları üretebilmesi için geliştirilmektedir. + +Laravel Blade (`.blade.php`), Twig (`.twig`), **Vue SFC (`.vue`)**, **React JSX/TSX (`.jsx`, `.tsx`)**, PHP (`.php`) ve standart HTML şablonlarını doğrudan tarar; satır içi gizleme yönergelerini (``), baseline yönetimini ve CI/CD kalite kapılarını sıfır ek kurulumla destekler. --- ## 🌟 Öne Çıkan Özellikler -- **🛡️ 130 Benzersiz WCAG 2.1 / 2.2 & WAI-ARIA Kuralı:** Algılanabilir (Perceivable), Çalıştırılabilir (Operable), Anlaşılabilir (Understandable) ve Sağlam (Robust) prensiplerine göre yapılandırılmış 5 kademeli kural havuzu. (Yeni: `LabelInName` WCAG 2.5.3, `RedundantEntry` WCAG 3.3.7, `TextSpacing` WCAG 1.4.12). -- **🏛️ Sektörel ve Mevzuat Ön Ayarları (Presets):** US Section 508, Avrupa Birliği EN 301 549 ve E-Ticaret (`--preset=section508|en301549|ecommerce`) profilleriyle hedeflenmiş standart denetimi. -- **🏷️ Dinamik SVG Rozet Üretimi (Badges):** Tarama tamamlandığında sağlık skoruna göre (yeşil/sarı/kırmızı) canlı SVG rozet (`--badge=public/a11y-badge.svg`) üretir. -- **📢 CI/CD Webhook Bildirimleri (Notifications):** Tarama sonuçlarını Slack ve Discord webhook kanallarına otomatik formatlanmış zengin mesajlarla iletir. -- **⚙️ Programatik Kural Denetleyicisi & İstatistikler:** `RuleController` ile DOM elementleri üzerinde doğrudan tekil kural yürütme ve `RuleExecutionStats` ile kural performans/yürütme süresi izleme. -- **⏱️ Gerçek Zamanlı İzleme Modu (`watch`):** Şablon dosyalarını (`.blade.php`, `.twig`, `.html`) arka planda izler, dosya kaydedildiğinde anında hızlı analiz yapıp konsolda canlı skor ve geri bildirim sunar. -- **🚦 CI/CD Kalite Kapısı Eşikleri (Quality Gates):** `--min-score=90`, `--max-warnings=5`, `--fail-on=error` seçenekleriyle pipeline süreçlerinde esnek kalite denetimi sağlar. -- **🔍 HTML & Şablon Söz Dizimi (Syntax/AST) Linter'ı:** - - Aynı etiket üzerinde yinelenen nitelikler (`Duplicate Attributes` - HTML5 3.2.4 ihlali) - - Kapanmamış veya çapraz kapanmış yapısal etiketler (`Mismatched / Unclosed Tags`) - - Void olmayan etiketlerde geçersiz self-closing kullanımı (`

`, ``, `

`) - - Boşluksuz bitişik nitelik söz dizimi (``) - - Kapanmamış HTML yorum blokları (``, ` ... `, `` yönergelerini destekler ve her gizlemeyi gerekçesiyle birlikte denetim kaydına (`suppressedAuditLog`) işler. +- **📈 Geçmiş Takibi ve Regresyon Karşılaştırması (`compare` & `--save-history`):** + - Tarama sonuçlarını zaman damgalı geçmiş dosyasında saklar, sağlık skoru trendini (`improving` / `stable` / `regressing`) hesaplar ve iki JSON rapor arasındaki yeni eklenen regresyonlar ile çözülen sorunları kıyaslar. +- **🧩 Çoklu Şablon ve Modern Frontend Desteği:** + - Laravel Blade (`.blade.php`), Twig (`.twig`), **Vue SFC (`.vue`)**, **React JSX/TSX (`.jsx`, `.tsx`)**, PHP (`.php`), Latte (`.latte`) ve HTML (`.html`, `.htm`, `.xhtml`) dosyalarını 1:1 satır numarası koruyarak tarar. +- **🩺 Sistem Tanılama (`doctor`) & Kural Rehberi (`explain`):** + - `a11y doctor` ile PHP ortamını, 175 kuralın kayıt tutarlılığını ve opsiyonel bağımlılıkları doğrulayın; `a11y explain ` ile herhangi bir kuralın W3C bağlantısını, kötü/iyi kod örneklerini ve otomatik onarım durumunu görün. +- **⚡ Tek Geçişli Kural Motoru, Artımlı Önbellek (`--cache`) ve Profilleme (`--profile`):** + - DOM ağacını tek geçişte tarar; içerik özeti tabanlı önbellek (`ScanCache`) ile değişmeyen dosyaları atlar ve `--profile` ile en yavaş çalışan kuralların milisaniye bazında istatistiklerini raporlar. +- **🧪 PHPUnit Erişilebilirlik Doğrulama Trait'i (`AccessibilityAssertions`):** + - Laravel, Symfony ve PHP test sınıflarınıza `use AccessibilityAssertions;` ekleyerek `$this->assertHtmlAccessible($html)` ve `$this->assertMeetsAccessibilityPreset($html, 'wcag22-aa')` kontrollerini doğrudan yazın. +- **🛠️ Otomatik CI/CD Pipeline Üretici (`init --ci=...`):** + - GitHub Actions, GitLab CI, Azure Pipelines ve Bitbucket Pipelines için hazır erişilebilirlik iş akışı dosyaları üretir. +- **🤖 Gelişmiş Çevrimdışı & Yapay Zeka Otomatik Onarım (`fix`):** + - **32+ deterministik çevrimdışı (offline) kural onarımı** (API anahtarı gerekmeden) ve karmaşık şablonlar için **Google Gemini AI** desteği. +- **🔌 Zengin Çıktı, Rapor ve Bildirim Ekosistemi:** + - Çıktı formatları: `console`, `json`, `github`, `gitlab`, `sarif` (OASIS SARIF 2.1.0), `junit`, `checkstyle`, `markdown`, `csv`, `xml`. + - Dosya dışa aktarımları: HTML Dashboard (`.html`), PDF (`.pdf`), Excel (`.xlsx`), VPAT 2.5 (`.md`, `.html`, `.json`), SARIF (`.sarif`), JUnit/Checkstyle (`.xml`), SVG Rozet (`--badge`). + - Bildirimler: **Slack**, **Discord**, **Microsoft Teams** ve **HMAC-SHA256 imzalı genel JSON Webhook** (`--webhook-url`). +- **🏆 PHPStan Level 9 & Tam Test Kapsamı:** Kod tabanı en üst seviye PHPStan Level 9 statik tip analizi (0 hata) ile doğrulanmıştır. --- @@ -57,171 +63,204 @@ composer require --dev yaknet/accessibility-console ## 🚀 Komut Satırı (CLI) Kullanımı -### 1. Yapılandırma Dosyası Oluşturma (`init`) -Projenizin kök dizininde varsayılan bir `a11y.yaml` konfigürasyon dosyası oluşturur: +YakNet Accessibility Console **10 komut** sunar: `scan`, `fix`, `vpat`, `compare`, `rules`, `explain`, `presets`, `doctor`, `watch`, `init`. + +### 1. Yapılandırma Oluşturma (`init`) ve Sistem Kontrolü (`doctor`) ```bash +# Kapsamlı varsayılan a11y.yaml dosyası oluşturur bin/a11y init + +# Ortam, 175 kural bütünlüğü ve entegrasyon durumunu doğrular +bin/a11y doctor ``` -### 2. Projeyi veya Dizinleri Tarama (`scan`) -Yapılandırma dosyasındaki yollara göre tüm projeyi tarar: +### 2. Proje, Şablon veya Canlı URL Tarama (`scan`) ```bash +# a11y.yaml yapılandırmasına göre projeyi tara bin/a11y scan -``` -Belirli bir dizini veya şablon klasörünü hedef göstererek taramak için: -```bash + +# Belirli bir dizini (Blade, Twig, Vue, JSX/TSX, HTML) tara bin/a11y scan resources/views -bin/a11y scan templates/ -``` -Canlı bir web sitesini crawler desteğiyle taramak için: -```bash -bin/a11y scan https://siteniz.com --crawl +bin/a11y scan src/components + +# Mevzuat / sektör ön ayarıyla tara ve VPAT 2.5 + SVG rozet üret +bin/a11y scan resources/views --preset=wcag22-aa --vpat=reports/vpat-2.5.md --badge=public/a11y.svg + +# Performans profillemesi ve geçmiş kaydıyla tara +bin/a11y scan resources/views --profile --save-history=.a11y-history.json + +# Canlı bir web sitesini crawler ve opsiyonel Headless Chrome ile tara +bin/a11y scan https://ornek.org --crawl --depth=3 --max-pages=25 ``` -### 3. CI/CD Kalite Kapısı Eşikleri (Quality Gates) -Pipeline süreçlerinde derlemenin kırılma şartlarını belirleyin: +### 3. VPAT 2.5 Uyumluluk Raporu Üretme (`vpat`) ```bash -# Sağlık skoru 90'ın altındaysa derlemeyi başarısız yap: -bin/a11y scan --min-score=90 +# Markdown formatında VPAT 2.5 raporu üret +bin/a11y vpat resources/views --product="Açık Portal" --product-version="2.4.0" --output=VPAT-2.5.md -# En fazla 3 uyarıya izin ver: -bin/a11y scan --max-warnings=3 - -# Yalnızca kritik ve hata seviyesindeki ihlallerde kırıl (uyarıları göz ardı et): -bin/a11y scan --fail-on=error +# Bağımsız HTML veya JSON VPAT 2.5 raporu üret +bin/a11y vpat resources/views --format=html --output=reports/vpat.html +bin/a11y vpat resources/views --format=json --output=reports/vpat.json ``` -### 4. Gerçek Zamanlı İzleme Modu (`watch`) -Geliştirme yaparken şablon dosyalarınızı izleyin ve dosya kaydedildiğinde anında otomatik re-scan çalıştırın: +### 4. Regresyon Karşılaştırması (`compare`) +PR veya sürüm öncesi iki tarama raporunu kıyaslayıp yeni eklenen ihlallerde derlemeyi durdurun: ```bash -bin/a11y watch resources/views +bin/a11y compare reports/before.json reports/after.json --fail-on-regression ``` -### 5. Format ve Raporlama Seçenekleri -- **GitHub Code Scanning / SARIF 2.1.0 formatı:** - ```bash - bin/a11y scan --format=sarif - ``` -- **JUnit XML formatı (Jenkins, GitLab CI):** - ```bash - bin/a11y scan --format=junit - ``` -- **GitHub Actions bildirim formatı:** - ```bash - bin/a11y scan --format=github - ``` -- **JSON formatında çıktı:** - ```bash - bin/a11y scan --format=json - ``` -- **Çoklu Dışa Aktarım Formatları (`--report`):** - ```bash - bin/a11y scan --report=rapor.html # İnteraktif HTML Dashboard - bin/a11y scan --report=rapor.pdf # PDF Sertifika ve Denetim Raporu - bin/a11y scan --report=rapor.xlsx # Microsoft Excel Çalışma Kitabı - bin/a11y scan --report=rapor.sarif # SARIF 2.1.0 Dosyası - bin/a11y scan --report=rapor.xml # JUnit XML Raporu - ``` - -### 6. Mevzuat Ön Ayarları (`--preset`) ve Rozet Üretimi (`--badge`) -Mevzuat veya sektörel kurallara göre hedeflenmiş tarama yapın ve canlı SVG rozet oluşturun: +### 5. Kuralları Keşfetme (`rules`), Açıklama (`explain`) ve Ön Ayarlar (`presets`) ```bash -# US Section 508 federal uyumluluk profiliyle tara: -bin/a11y scan --preset=section508 - -# Avrupa Birliği EN 301 549 kamu web standardı profiliyle tara: -bin/a11y scan --preset=en301549 - -# E-Ticaret ödeme ve sepet akışları profiliyle tara: -bin/a11y scan --preset=ecommerce - -# Tarama sonucunu SVG rozet olarak kaydet (README veya CI/CD artifact için): -bin/a11y scan --badge=public/badges/a11y.svg -``` - -### 7. Otomatik Düzeltme (`fix`) -Yapay zeka veya çevrimdışı yerel motor ile kaynak dosyalarınızı onarın: -```bash -# Gemini AI desteğiyle otomatik onarım: -bin/a11y fix - -# Gemini API anahtarı olmadan tamamen çevrimdışı (offline) yerel motorla onarım: -bin/a11y fix --offline - -# Dosyaları değiştirmeden yapılacak düzeltmeleri önizleme: -bin/a11y fix --offline --dry-run -``` - -### 8. Kuralları Listeleme ve Filtreleme (`rules`) -Kütüphanede tanımlı 130 kuralı listeleyin, arayın ve filtreleyin: -```bash -# Tüm kuralları listele: +# Tüm 175 kuralı listele bin/a11y rules -# Kural adına veya açıklamasına göre ara: -bin/a11y rules --search=contrast +# POUR ilkesine, seviyeye veya çevrimdışı onarım desteğine göre filtrele +bin/a11y rules --principle=Operable --standard=AA +bin/a11y rules --healable -# Seviye ve standarda göre filtrele: -bin/a11y rules --standard=AA --level=3 +# Belirli bir kuralın W3C rehberini ve kod örneklerini incele +bin/a11y explain WCAG_4_1_2_ARIA_TABLIST + +# Tüm 11 mevzuat ve sektörel ön ayarı listele +bin/a11y presets +``` + +### 6. CI/CD Çıktı Formatları, Raporlar ve Bildirimler +```bash +bin/a11y scan --format=sarif --report=a11y.sarif +bin/a11y scan --format=checkstyle --report=a11y.checkstyle +bin/a11y scan --format=junit --report=a11y.xml +bin/a11y scan --report=rapor.html +bin/a11y scan --report=rapor.pdf +bin/a11y scan --report=rapor.xlsx + +# Slack, Discord, Microsoft Teams veya genel webhook bildirimleri +bin/a11y scan --webhook-slack="$SLACK_WEBHOOK" --webhook-teams="$TEAMS_WEBHOOK" +``` + +### 7. Otomatik Onarım (`fix`) ve Canlı İzleme (`watch`) +```bash +# Çevrimdışı (API anahtarsız) deterministik onarım önizleme & uygulama +bin/a11y fix --offline --dry-run +bin/a11y fix --offline + +# Gemini AI destekli onarım +bin/a11y fix + +# Dosya değişikliklerini canlı izleme +bin/a11y watch resources/views ``` --- -## ⚙️ Yapılandırma Dosyası (`a11y.yaml`) +## 🏛️ Mevzuat ve Sektörel Ön Ayarlar (Presets) -Projenizin ihtiyaçlarına göre `a11y.yaml` dosyasını özelleştirebilirsiniz: +| Ön Ayar (`--preset`) | Seviye | Kapsam | +| :--- | :---: | :--- | +| `wcag22-aa` | 4 | W3C WCAG 2.2 Level A & AA tam uyumluluk profili | +| `wcag22-aaa` | 5 | En katı W3C WCAG 2.2 Level AAA profili (tüm 175 kural) | +| `en301549` | 4 | Avrupa Birliği EN 301 549 kamu dijital erişilebilirlik standardı | +| `eaa2025` | 4 | European Accessibility Act (Direktif EU 2019/882) dijital hizmet profili | +| `section508` | 3 | ABD Revised Section 508 erişilebilirlik profili | +| `bitv2` | 5 | Almanya BITV 2.0 kamu erişilebilirlik standardı | +| `government` | 5 | Kamu portalları ve e-Devlet hizmetleri profili | +| `healthcare` | 5 | Sağlık ve hasta portalları profili (okunabilirlik ve hareket güvenliği odaklı) | +| `banking` | 4 | Dijital bankacılık ve finansal hizmetler profili | +| `education` | 4 | Üniversite, LMS ve akademik portallar (ADA Title II uyumlu) | +| `ecommerce` | 4 | E-Ticaret mağaza ve ödeme akışları profili | + +--- + +## ⚙️ Yapılandırma (`a11y.yaml`) ve Politika Motoru ```yaml -# Tarama yapılacak dizin veya şablon yolları paths: - resources/views - - templates - - public/partials + - src/components -# Hariç tutulacak klasörler exclude_paths: - vendor - node_modules - storage - - tests/fixtures + - tests -# Kural Seviyesi (1: Kritik A -> 5: Kapsamlı AA/AAA) level: 4 - -# Varsayılan çıktı formatı (console, json, github) +preset: wcag22-aa format: console - -# Baseline dosyası yolu baseline: a11y-baseline.json -# Kural istisnaları ve özel kurallar +extensions: + - php + - html + - twig + - blade.php + - vue + - jsx + - tsx + +# Organizasyon geneli yönetişim politikaları +policy: + min_score: 90 + max_critical: 0 + max_errors: 0 + max_warnings: 10 + required_standards: + - A + banned_rules: + - WCAG_1_1_1_ALT + - WCAG_2_3_1_FLASHING_CONTENT + severity_overrides: + WCAG_2_5_8_TARGET_SIZE: error + principle_limits: + Perceivable: 0 + +notifications: + slack_webhook: "" + discord_webhook: "" + teams_webhook: "" + webhook_url: "" + webhook_secret: "" + rules: exclude: - - WCAG_1_3_1_FIELDSET # Belirli bir kuralı devre dışı bırak + - WCAG_1_3_1_FIELDSET include: - - App\Rules\CustomBrandAccessibilityRule # Özel proje kuralı ekle + - App\Rules\CustomAccessibilityRule ``` --- -## 📐 Kural Seviyeleri (Rule Levels) +## 🔇 Satır İçi Gizleme Yönergeleri (Inline Suppressions) -| Seviye | Adı | Kapsam | Örnek Kurallar | -| :--- | :--- | :--- | :--- | -| **Level 1** | Essential | Temel WCAG 2.1 A | `ImageAlt`, `ButtonName`, `HtmlHasLang`, `PageTitle` | -| **Level 2** | Standard | Standart WCAG 2.1/2.2 A & Söz Dizimi | `HtmlSyntaxValid`, `FormLabel`, `HeadingOrder`, `TrackValidation` | -| **Level 3** | Enhanced | Gelişmiş WAI-ARIA & Formlar | `DuplicateId`, `NestedInteractive`, `AriaCurrentValid`, `AccessibleAuth` | -| **Level 4** | Advanced | Kapsamlı WCAG 2.2 AA & UX | `TargetSizeMinimum`, `DraggingMovements`, `FocusNotObscured`, `ColorContrast` | -| **Level 5** | Strict | Çok Katı AAA & Best Practices | `FocusTrapping`, `ColorBlindnessContrast`, `NoFocusOutline` | +İstisnai durumlarda belirli satır veya bloklarda kuralı gerekçesiyle birlikte gizleyebilirsiniz; tüm gizlemeler denetim kaydına alınır: + +```html + + + + +

Resmi belge metni...

+ +``` --- -## 🔐 Yapay Zeka (AI) API Yapılandırması +## 🧩 PHP Programatik API -AI Self-Healing ve otomatik kod onarım özelliklerini kullanabilmek için projenizin kök dizinindeki `.env` dosyasına **Google Gemini API** anahtarınızı ekleyin: +```php +// 1. Hızlı tarama ve skor hesaplama +$violations = a11y_scan($html, level: 4); +$score = a11y_score($html, level: 4); -```env -GEMINI_API_KEY=AIzaSyA...your_api_key_here +// 2. Mevzuat ön ayarıyla tarama +$govViolations = a11y_scan_preset($html, 'government'); + +// 3. VPAT 2.5 raporu ve POUR uyumluluk matrisi üretme +$vpatMarkdown = a11y_vpat($html, format: 'markdown', productName: 'YakNet Portal'); +$matrix = a11y_compliance_matrix($html, level: 5); + +// 4. Çevrimdışı deterministik hızlı onarım +$fixedHtml = a11y_quick_fix($html); ``` --- @@ -240,14 +279,15 @@ vendor/bin/phpstan analyse -l 9 src/ ## 🤝 Katkıda Bulunma -1. Bu depoyu forklayın (`fork`). -2. Yeni bir özellik dalı açın (`git checkout -b feature/harika-kural`). -3. Değişikliklerinizi commit edin (`git commit -m 'feat: Yeni WCAG kuralı eklendi'`). -4. Dalınıza push yapın (`git push origin feature/harika-kural`). -5. Bir **Pull Request** açın. +Bu proje açık kaynaklıdır ve her türlü katkıya açıktır: + +1. Depoyu forklayın (`fork`). +2. Yeni bir özellik dalı açın (`git checkout -b feature/yeni-kural`). +3. Değişikliklerinizi ve testlerinizi ekleyin (`vendor/bin/phpunit` ve `vendor/bin/phpstan analyse -l 9 src/` ile doğrulayın). +4. Bir **Pull Request** açın. --- ## 📜 Lisans -Bu proje **YakNet Bilişim** tarafından geliştirilmiştir ve **MIT Lisansı** altında lisanslanmıştır. Detaylar için [LICENSE](LICENSE) dosyasına göz atabilirsiniz. \ No newline at end of file +Bu proje **YakNet** tarafından geliştirilmiştir ve **MIT Lisansı** altında lisanslanmıştır. Detaylar için [LICENSE](LICENSE) dosyasına göz atabilirsiniz. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..5031bfd --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| :--- | :---: | +| 4.x | Yes | +| 3.x | Security fixes only | +| < 3.0 | No | + +## Reporting a Vulnerability + +**YakNet** takes the security of open-source packages seriously. If you discover a security vulnerability in **YakNet Accessibility Console** (for example, in HTML/XML parsing, URL crawling, Headless Chrome rendering, webhook signing, or report generation): + +1. **Do not** disclose the issue publicly in an open GitHub issue before it has been reviewed. +2. Report it privately by emailing `info@yakhub.com.tr` or opening a private security advisory on the repository. +3. Include a clear description, reproduction steps, affected version, and potential impact. + +We aim to acknowledge reports within 48 hours and provide a coordinated fix and release advisory promptly. diff --git a/bin/a11y b/bin/a11y index 50775b8..06e642d 100644 --- a/bin/a11y +++ b/bin/a11y @@ -12,14 +12,19 @@ if (file_exists(__DIR__ . '/../vendor/autoload.php')) { use Symfony\Component\Console\Application; use YakNet\AccessibilityConsole\Core\Container\ContainerFactory; -use YakNet\AccessibilityConsole\Console\Command\ScanCommand; +use YakNet\AccessibilityConsole\Console\Command\CompareCommand; +use YakNet\AccessibilityConsole\Console\Command\DoctorCommand; +use YakNet\AccessibilityConsole\Console\Command\ExplainCommand; use YakNet\AccessibilityConsole\Console\Command\FixCommand; use YakNet\AccessibilityConsole\Console\Command\InitCommand; +use YakNet\AccessibilityConsole\Console\Command\PresetsCommand; use YakNet\AccessibilityConsole\Console\Command\RulesCommand; +use YakNet\AccessibilityConsole\Console\Command\ScanCommand; +use YakNet\AccessibilityConsole\Console\Command\VpatCommand; use YakNet\AccessibilityConsole\Console\Command\WatchCommand; $container = ContainerFactory::create(); -$application = new Application('YakNet Accessibility Console', '3.3.0'); +$application = new Application('YakNet Accessibility Console', '4.0.0'); // Add commands resolved via DI Container $application->addCommand($container->get(ScanCommand::class)); @@ -27,5 +32,10 @@ $application->addCommand($container->get(FixCommand::class)); $application->addCommand($container->get(InitCommand::class)); $application->addCommand($container->get(RulesCommand::class)); $application->addCommand($container->get(WatchCommand::class)); +$application->addCommand($container->get(VpatCommand::class)); +$application->addCommand($container->get(CompareCommand::class)); +$application->addCommand($container->get(DoctorCommand::class)); +$application->addCommand($container->get(ExplainCommand::class)); +$application->addCommand($container->get(PresetsCommand::class)); $application->run(); diff --git a/composer.json b/composer.json index b4b2939..f55e159 100644 --- a/composer.json +++ b/composer.json @@ -1,25 +1,31 @@ { "name": "yaknet/accessibility-console", - "description": "A professional AI-powered WCAG 2.1 accessibility scanner with self-healing capabilities.", + "description": "An open-source, comprehensive WCAG 2.1/2.2 & WAI-ARIA 1.2 accessibility analysis, VPAT 2.5 reporting, policy governance, and self-healing platform by YakNet.", "keywords": [ "accessibility", "wcag", + "wcag22", + "wai-aria", + "vpat", + "en301549", + "section508", "a11y", "scanner", + "linter", + "static-analysis", "ai", - "gemini", "self-healing", "yaknet" ], "homepage": "https://forum.yak.net.tr", - "version": "3.3.0", + "version": "4.0.0", "type": "library", "license": "MIT", "authors": [ { - "name": "YakNet Bilişim", + "name": "YakNet", "email": "info@yakhub.com.tr", - "role": "Developer" + "role": "Organization" } ], "require": { diff --git a/dashboard/public/index.html b/dashboard/public/index.html index 5cad2c4..10665e8 100644 --- a/dashboard/public/index.html +++ b/dashboard/public/index.html @@ -18,10 +18,10 @@
♿

- YakNet Accessibility Engine - v3.2 Enterprise + YakNet Accessibility Console + v4.0 Open Source

-

Gerçek Zamanlı Canlı Web Dashboard & WCAG 2.1 İzleyici

+

Gerçek Zamanlı Canlı Web Dashboard & WCAG 2.1 / 2.2 İzleyici

diff --git a/src/AI/GeminiFixer.php b/src/AI/GeminiFixer.php index 29b4686..2fb56c1 100644 --- a/src/AI/GeminiFixer.php +++ b/src/AI/GeminiFixer.php @@ -44,11 +44,18 @@ EXPLANATION: [A short explanation of what you fixed and why] FIX: [Only the corrected HTML snippet] PROMPT; - try { - $result = $this->client->generativeModel('gemini-3.1-flash-lite')->generateContent($prompt); - return trim($result->text()); - } catch (\Throwable $e) { - return "AI Düzeltme Hatası: " . $e->getMessage(); + $models = ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-1.5-pro', 'gemini-1.5-flash']; + $lastError = null; + + foreach ($models as $model) { + try { + $result = $this->client->generativeModel($model)->generateContent($prompt); + return trim($result->text()); + } catch (\Throwable $e) { + $lastError = $e; + } } + + return "AI Düzeltme Hatası: " . $lastError->getMessage(); } } diff --git a/src/AI/Providers/GeminiProvider.php b/src/AI/Providers/GeminiProvider.php index 0520e5e..32cc8a1 100644 --- a/src/AI/Providers/GeminiProvider.php +++ b/src/AI/Providers/GeminiProvider.php @@ -35,11 +35,18 @@ class GeminiProvider implements AiProviderInterface $prompt = PromptBuilder::build($violation); - try { - $result = $this->client->generativeModel('gemini-3.1-flash-lite')->generateContent($prompt); - return trim($result->text()); - } catch (\Throwable $e) { - return "Gemini Error: " . $e->getMessage(); + $models = ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-1.5-pro', 'gemini-1.5-flash']; + $lastError = null; + + foreach ($models as $model) { + try { + $result = $this->client->generativeModel($model)->generateContent($prompt); + return trim($result->text()); + } catch (\Throwable $e) { + $lastError = $e; + } } + + return "Gemini Error: " . $lastError->getMessage(); } } diff --git a/src/Analytics/ComplianceMatrixGenerator.php b/src/Analytics/ComplianceMatrixGenerator.php index 354cc54..c748fd9 100644 --- a/src/Analytics/ComplianceMatrixGenerator.php +++ b/src/Analytics/ComplianceMatrixGenerator.php @@ -26,7 +26,7 @@ class ComplianceMatrixGenerator * levels: array * } */ - public function generate(array $violations, int $totalActiveRules = 127): array + public function generate(array $violations, int $totalActiveRules = 175): array { $principles = [ 'Perceivable' => ['violations' => 0, 'status' => 'Pass'], @@ -47,6 +47,10 @@ class ComplianceMatrixGenerator $principleNumber = 4; if (preg_match('/WCAG_([1-4])_/', $v->ruleId, $m)) { $principleNumber = (int)$m[1]; + } elseif (in_array($v->ruleId, ['HeadingOrder', 'BannedSelectors', 'A11Y_VIEWPORT', 'WCAG_FONT_TAG_BANNED'], true)) { + $principleNumber = 1; + } elseif (in_array($v->ruleId, ['AccesskeyDuplicate', 'WCAG_LINK_TARGET_BLANK'], true)) { + $principleNumber = 2; } $pName = self::$principleMap[$principleNumber] ?? 'Robust'; $principles[$pName]['violations']++; diff --git a/src/Analytics/HistoryTracker.php b/src/Analytics/HistoryTracker.php new file mode 100644 index 0000000..736a88a --- /dev/null +++ b/src/Analytics/HistoryTracker.php @@ -0,0 +1,245 @@ + The newly recorded snapshot + */ + public function record( + array $violations, + string $historyFile, + string $target = '.', + ?string $preset = null + ): array { + $entries = $this->load($historyFile); + $metrics = AccessibilityScoreCalculator::calculate($violations); + $matrix = (new ComplianceMatrixGenerator())->generate($violations); + + $counts = ['critical' => 0, 'error' => 0, 'warning' => 0, 'info' => 0]; + $ruleBreakdown = []; + + foreach ($violations as $v) { + $counts[$v->severity->value]++; + $ruleBreakdown[$v->ruleId] = ($ruleBreakdown[$v->ruleId] ?? 0) + 1; + } + + $snapshot = [ + 'timestamp' => date('Y-m-d\TH:i:sP'), + 'target' => $target, + 'preset' => $preset, + 'score' => $metrics['score'], + 'total_violations' => count($violations), + 'severity' => $counts, + 'principles' => $matrix['principles'], + 'rules' => $ruleBreakdown, + ]; + + $entries[] = $snapshot; + $dir = dirname($historyFile); + if (!is_dir($dir) && $dir !== '.' && $dir !== '') { + @mkdir($dir, 0775, true); + } + file_put_contents($historyFile, (string)json_encode($entries, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); + + return $snapshot; + } + + /** + * Load all recorded snapshots from a JSON history file. + * + * @return array> + */ + public function load(string $historyFile): array + { + if (!file_exists($historyFile)) { + return []; + } + $raw = @file_get_contents($historyFile); + if ($raw === false || trim($raw) === '') { + return []; + } + $decoded = json_decode($raw, true); + if (!is_array($decoded)) { + return []; + } + + $result = []; + foreach ($decoded as $item) { + if (is_array($item)) { + /** @var array $item */ + $result[] = $item; + } + } + return $result; + } + + /** + * Compute overall accessibility health trend across historical runs. + * + * @param array> $entries + * @return array{runs: int, latest_score: int, previous_score: int|null, score_delta: int, trend: string} + */ + public function computeTrend(array $entries): array + { + $runs = count($entries); + if ($runs === 0) { + return [ + 'runs' => 0, + 'latest_score' => 100, + 'previous_score' => null, + 'score_delta' => 0, + 'trend' => 'stable', + ]; + } + + $latest = $entries[$runs - 1]; + $latestScore = is_numeric($latest['score'] ?? null) ? (int)$latest['score'] : 0; + + if ($runs === 1) { + return [ + 'runs' => 1, + 'latest_score' => $latestScore, + 'previous_score' => null, + 'score_delta' => 0, + 'trend' => 'baseline', + ]; + } + + $prev = $entries[$runs - 2]; + $prevScore = is_numeric($prev['score'] ?? null) ? (int)$prev['score'] : 0; + $delta = $latestScore - $prevScore; + + $trend = $delta > 0 ? 'improving' : ($delta < 0 ? 'regressing' : 'stable'); + + return [ + 'runs' => $runs, + 'latest_score' => $latestScore, + 'previous_score' => $prevScore, + 'score_delta' => $delta, + 'trend' => $trend, + ]; + } + + /** + * Compare two serialized violation arrays (from JSON scan reports) and compute + * regressions (newly introduced issues), resolved issues, and score delta. + * + * @param array> $beforeViolations + * @param array> $afterViolations + * @return array{ + * before_count: int, + * after_count: int, + * before_score: int, + * after_score: int, + * score_delta: int, + * new_violations: array>, + * resolved_violations: array>, + * unchanged_count: int + * } + */ + public function compareReports(array $beforeViolations, array $afterViolations): array + { + $beforeMap = []; + foreach ($beforeViolations as $idx => $v) { + $fp = $this->fingerprint($v) . '#' . $idx; + $baseFp = $this->fingerprint($v); + $beforeMap[$baseFp][] = $v; + } + + $afterMap = []; + foreach ($afterViolations as $v) { + $baseFp = $this->fingerprint($v); + $afterMap[$baseFp][] = $v; + } + + $newViolations = []; + $resolvedViolations = []; + $unchangedCount = 0; + + $allKeys = array_unique(array_merge(array_keys($beforeMap), array_keys($afterMap))); + + foreach ($allKeys as $key) { + $bList = $beforeMap[$key] ?? []; + $aList = $afterMap[$key] ?? []; + $bCount = count($bList); + $aCount = count($aList); + + $common = min($bCount, $aCount); + $unchangedCount += $common; + + if ($aCount > $bCount) { + for ($i = $bCount; $i < $aCount; $i++) { + $newViolations[] = $aList[$i]; + } + } elseif ($bCount > $aCount) { + for ($i = $aCount; $i < $bCount; $i++) { + $resolvedViolations[] = $bList[$i]; + } + } + } + + $beforeScore = $this->estimateScoreFromRaw($beforeViolations); + $afterScore = $this->estimateScoreFromRaw($afterViolations); + + return [ + 'before_count' => count($beforeViolations), + 'after_count' => count($afterViolations), + 'before_score' => $beforeScore, + 'after_score' => $afterScore, + 'score_delta' => $afterScore - $beforeScore, + 'new_violations' => $newViolations, + 'resolved_violations' => $resolvedViolations, + 'unchanged_count' => $unchangedCount, + ]; + } + + /** + * @param array $violation + */ + private function fingerprint(array $violation): string + { + $ruleId = is_scalar($violation['ruleId'] ?? null) ? (string)$violation['ruleId'] : ''; + $snippet = is_scalar($violation['htmlSnippet'] ?? null) ? trim((string)$violation['htmlSnippet']) : ''; + $file = ''; + if (isset($violation['location']) && is_array($violation['location']) && is_scalar($violation['location']['file'] ?? null)) { + $file = (string)$violation['location']['file']; + } + return hash('sha256', $file . '|' . $ruleId . '|' . preg_replace('/\s+/', ' ', $snippet)); + } + + /** + * @param array> $rawViolations + */ + private function estimateScoreFromRaw(array $rawViolations): int + { + $score = 100; + foreach ($rawViolations as $v) { + $sev = strtolower(is_scalar($v['severity'] ?? null) ? (string)$v['severity'] : 'warning'); + $deduction = match ($sev) { + Severity::CRITICAL->value => 15, + Severity::ERROR->value => 8, + default => 3, + }; + $score -= $deduction; + } + return max(0, $score); + } +} diff --git a/src/CI/CiWorkflowGenerator.php b/src/CI/CiWorkflowGenerator.php new file mode 100644 index 0000000..3ad3393 --- /dev/null +++ b/src/CI/CiWorkflowGenerator.php @@ -0,0 +1,184 @@ + '.github/workflows/accessibility.yml', + 'gitlab' => '.gitlab-ci.a11y.yml', + 'azure' => 'azure-pipelines.a11y.yml', + 'bitbucket' => 'bitbucket-pipelines.a11y.yml', + default => throw new \InvalidArgumentException("Unsupported CI platform '{$platform}'."), + }; + } + + /** + * Generate CI workflow YAML content for the specified platform. + */ + public function generate( + string $platform, + string $preset = 'wcag22-aa', + int $minScore = 90, + string $targetPath = 'resources/views' + ): string { + return match (strtolower($platform)) { + 'github' => $this->generateGitHubActions($preset, $minScore, $targetPath), + 'gitlab' => $this->generateGitLabCi($preset, $minScore, $targetPath), + 'azure' => $this->generateAzurePipelines($preset, $minScore, $targetPath), + 'bitbucket' => $this->generateBitbucketPipelines($preset, $minScore, $targetPath), + default => throw new \InvalidArgumentException(sprintf( + "Unsupported CI platform '%s'. Supported platforms: %s.", + $platform, + implode(', ', self::getSupportedPlatforms()) + )), + }; + } + + private function generateGitHubActions(string $preset, int $minScore, string $targetPath): string + { + return << gl-a11y-codequality.json + - vendor/bin/a11y vpat {$targetPath} --preset={$preset} --format=html --output=vpat-2.5.html + artifacts: + when: always + reports: + codequality: gl-a11y-codequality.json + paths: + - vpat-2.5.html +YAML; + } + + private function generateAzurePipelines(string $preset, int $minScore, string $targetPath): string + { + return <<>}> + */ + private array $entries = []; + + private string $rulesSignature = ''; + private int $hits = 0; + private int $misses = 0; + + public function __construct( + private string $cacheFile = '.a11y-cache.json', + string $rulesSignature = '' + ) { + $this->rulesSignature = $rulesSignature; + } + + public function setRulesSignature(string $signature): void + { + if ($this->rulesSignature !== '' && $this->rulesSignature !== $signature) { + $this->entries = []; + } + $this->rulesSignature = $signature; + } + + public function load(): void + { + if (!file_exists($this->cacheFile)) { + return; + } + + $raw = @file_get_contents($this->cacheFile); + if ($raw === false || trim($raw) === '') { + return; + } + + $decoded = json_decode($raw, true); + if (!is_array($decoded)) { + return; + } + + $storedSig = is_scalar($decoded['rules_signature'] ?? null) ? (string)$decoded['rules_signature'] : ''; + if ($this->rulesSignature !== '' && $storedSig !== $this->rulesSignature) { + $this->entries = []; + return; + } + + if (isset($decoded['entries']) && is_array($decoded['entries'])) { + foreach ($decoded['entries'] as $path => $entry) { + if (!is_string($path) || !is_array($entry)) { + continue; + } + if (!is_string($entry['hash'] ?? null) || !is_array($entry['violations'] ?? null)) { + continue; + } + /** @var array> $violationsList */ + $violationsList = array_values(array_filter($entry['violations'], 'is_array')); + $this->entries[$path] = [ + 'hash' => $entry['hash'], + 'violations' => $violationsList, + ]; + } + } + } + + /** + * Retrieve cached violations for a file if its content hash matches; otherwise return null. + * + * @return Violation[]|null + */ + public function get(string $relativePath, string $content): ?array + { + $hash = hash('sha256', $content); + if (!isset($this->entries[$relativePath]) || $this->entries[$relativePath]['hash'] !== $hash) { + $this->misses++; + return null; + } + + $this->hits++; + $violations = []; + foreach ($this->entries[$relativePath]['violations'] as $row) { + $ruleId = is_scalar($row['ruleId'] ?? null) ? (string)$row['ruleId'] : ''; + $message = is_scalar($row['message'] ?? null) ? (string)$row['message'] : ''; + $sevRaw = is_scalar($row['severity'] ?? null) ? (string)$row['severity'] : 'error'; + $stdRaw = is_scalar($row['standard'] ?? null) ? (string)$row['standard'] : 'A'; + $snippet = is_scalar($row['htmlSnippet'] ?? null) ? (string)$row['htmlSnippet'] : ''; + $fix = is_string($row['fixSuggestion'] ?? null) ? $row['fixSuggestion'] : null; + + $location = null; + if (isset($row['location']) && is_array($row['location'])) { + $locLine = is_numeric($row['location']['line'] ?? null) ? (int)$row['location']['line'] : 1; + $location = ['line' => $locLine]; + if (is_string($row['location']['file'] ?? null)) { + $location['file'] = $row['location']['file']; + } + if (is_numeric($row['location']['column'] ?? null)) { + $location['column'] = (int)$row['location']['column']; + } + } + + $violations[] = new Violation( + ruleId: $ruleId, + message: $message, + severity: Severity::tryFrom($sevRaw) ?? Severity::ERROR, + standard: WCAGStandard::tryFrom($stdRaw) ?? WCAGStandard::A, + htmlSnippet: $snippet, + location: $location, + fixSuggestion: $fix + ); + } + + return $violations; + } + + /** + * Store violations for a scanned file. + * + * @param Violation[] $violations + */ + public function put(string $relativePath, string $content, array $violations): void + { + $this->entries[$relativePath] = [ + 'hash' => hash('sha256', $content), + 'violations' => array_map(static fn(Violation $v): array => $v->toArray(), $violations), + ]; + } + + public function save(): bool + { + $dir = dirname($this->cacheFile); + if (!is_dir($dir) && $dir !== '.') { + @mkdir($dir, 0775, true); + } + + $payload = [ + 'version' => '4.0.0', + 'updated_at' => date('Y-m-d\TH:i:sP'), + 'rules_signature' => $this->rulesSignature, + 'entries' => $this->entries, + ]; + + return file_put_contents( + $this->cacheFile, + (string)json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) + ) !== false; + } + + public function clear(): bool + { + $this->entries = []; + $this->hits = 0; + $this->misses = 0; + if (file_exists($this->cacheFile)) { + return @unlink($this->cacheFile); + } + return true; + } + + /** + * @return array{hits: int, misses: int, entries: int, hit_rate: float} + */ + public function getStats(): array + { + $total = $this->hits + $this->misses; + $rate = $total > 0 ? round(($this->hits / $total) * 100, 1) : 0.0; + return [ + 'hits' => $this->hits, + 'misses' => $this->misses, + 'entries' => count($this->entries), + 'hit_rate' => $rate, + ]; + } +} diff --git a/src/Compliance/VpatReportGenerator.php b/src/Compliance/VpatReportGenerator.php new file mode 100644 index 0000000..37a761f --- /dev/null +++ b/src/Compliance/VpatReportGenerator.php @@ -0,0 +1,381 @@ + [Title, Level, Version, Automated]). + * + * @var array + */ + private const CRITERIA_CATALOG = [ + '1.1.1' => ['title' => 'Non-text Content', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '1.2.1' => ['title' => 'Audio-only and Video-only (Prerecorded)', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '1.2.2' => ['title' => 'Captions (Prerecorded)', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '1.3.1' => ['title' => 'Info and Relationships', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '1.3.2' => ['title' => 'Meaningful Sequence', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '1.3.4' => ['title' => 'Orientation', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + '1.3.5' => ['title' => 'Identify Input Purpose', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + '1.4.1' => ['title' => 'Use of Color', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '1.4.2' => ['title' => 'Audio Control', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '1.4.3' => ['title' => 'Contrast (Minimum)', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + '1.4.4' => ['title' => 'Resize Text', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + '1.4.6' => ['title' => 'Contrast (Enhanced)', 'level' => 'AAA', 'version' => '2.1', 'automated' => true], + '1.4.8' => ['title' => 'Visual Presentation', 'level' => 'AAA', 'version' => '2.1', 'automated' => true], + '1.4.10' => ['title' => 'Reflow', 'level' => 'AA', 'version' => '2.1', 'automated' => false], + '1.4.11' => ['title' => 'Non-text Contrast', 'level' => 'AA', 'version' => '2.1', 'automated' => false], + '1.4.12' => ['title' => 'Text Spacing', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + '1.4.13' => ['title' => 'Content on Hover or Focus', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + '2.1.1' => ['title' => 'Keyboard', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.1.2' => ['title' => 'No Keyboard Trap', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.1.4' => ['title' => 'Character Key Shortcuts', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.2.1' => ['title' => 'Timing Adjustable', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.2.2' => ['title' => 'Pause, Stop, Hide', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.3.1' => ['title' => 'Three Flashes or Below Threshold', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.3.3' => ['title' => 'Animation from Interactions', 'level' => 'AAA', 'version' => '2.1', 'automated' => true], + '2.4.1' => ['title' => 'Bypass Blocks', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.4.2' => ['title' => 'Page Titled', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.4.3' => ['title' => 'Focus Order', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.4.4' => ['title' => 'Link Purpose (In Context)', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.4.6' => ['title' => 'Headings and Labels', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + '2.4.7' => ['title' => 'Focus Visible', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + '2.4.8' => ['title' => 'Location', 'level' => 'AAA', 'version' => '2.1', 'automated' => true], + '2.4.11' => ['title' => 'Focus Not Obscured (Minimum)', 'level' => 'AA', 'version' => '2.2', 'automated' => true], + '2.4.13' => ['title' => 'Focus Appearance', 'level' => 'AAA', 'version' => '2.2', 'automated' => true], + '2.5.2' => ['title' => 'Pointer Cancellation', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.5.3' => ['title' => 'Label in Name', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '2.5.7' => ['title' => 'Dragging Movements', 'level' => 'AA', 'version' => '2.2', 'automated' => true], + '2.5.8' => ['title' => 'Target Size (Minimum)', 'level' => 'AA', 'version' => '2.2', 'automated' => true], + '3.1.1' => ['title' => 'Language of Page', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '3.1.2' => ['title' => 'Language of Parts', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + '3.1.4' => ['title' => 'Abbreviations', 'level' => 'AAA', 'version' => '2.1', 'automated' => true], + '3.1.5' => ['title' => 'Reading Level', 'level' => 'AAA', 'version' => '2.1', 'automated' => true], + '3.2.2' => ['title' => 'On Input', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '3.2.6' => ['title' => 'Consistent Help', 'level' => 'A', 'version' => '2.2', 'automated' => true], + '3.3.1' => ['title' => 'Error Identification', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '3.3.2' => ['title' => 'Labels or Instructions', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '3.3.7' => ['title' => 'Redundant Entry', 'level' => 'A', 'version' => '2.2', 'automated' => true], + '3.3.8' => ['title' => 'Accessible Authentication (Minimum)', 'level' => 'AA', 'version' => '2.2', 'automated' => true], + '4.1.1' => ['title' => 'Parsing', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '4.1.2' => ['title' => 'Name, Role, Value', 'level' => 'A', 'version' => '2.1', 'automated' => true], + '4.1.3' => ['title' => 'Status Messages', 'level' => 'AA', 'version' => '2.1', 'automated' => true], + ]; + + /** + * Build structured VPAT 2.5 data model from violations. + * + * @param Violation[] $violations + * @param string $productName + * @param string $productVersion + * @param string $evaluator + * @return array{ + * vpat_version: string, + * generated_at: string, + * product_name: string, + * product_version: string, + * evaluator: string, + * tool: string, + * health_score: int, + * total_violations: int, + * active_rules_count: int, + * summary: array{supports: int, partially_supports: int, does_not_support: int, not_evaluated: int}, + * criteria: array + * } + */ + public function buildReportData( + array $violations, + string $productName = 'Web Application', + string $productVersion = '1.0.0', + string $evaluator = 'YakNet Accessibility Console Automated Evaluation' + ): array { + /** @var array $byCriterion */ + $byCriterion = []; + + foreach ($violations as $violation) { + $code = $this->extractCriterionCode($violation->ruleId); + $byCriterion[$code][] = $violation; + } + + $summary = [ + 'supports' => 0, + 'partially_supports' => 0, + 'does_not_support' => 0, + 'not_evaluated' => 0, + ]; + + $criteriaRows = []; + foreach (self::CRITERIA_CATALOG as $code => $meta) { + $matched = $byCriterion[$code] ?? []; + $count = count($matched); + + if (!$meta['automated'] && $count === 0) { + $conformance = 'Not Evaluated'; + $remarks = 'Requires manual human/assistive-technology verification.'; + $summary['not_evaluated']++; + } elseif ($count === 0) { + $conformance = 'Supports'; + $remarks = 'No automated violations detected during static & DOM evaluation.'; + $summary['supports']++; + } else { + $hasSevere = false; + $ruleIds = []; + foreach ($matched as $v) { + $ruleIds[$v->ruleId] = true; + if ($v->severity === Severity::CRITICAL || $v->severity === Severity::ERROR) { + $hasSevere = true; + } + } + if ($hasSevere) { + $conformance = 'Does Not Support'; + $summary['does_not_support']++; + } else { + $conformance = 'Partially Supports'; + $summary['partially_supports']++; + } + $remarks = sprintf( + '%d violation(s) detected across rule(s): %s.', + $count, + implode(', ', array_keys($ruleIds)) + ); + } + + $criteriaRows[$code] = [ + 'code' => $code, + 'title' => $meta['title'], + 'level' => $meta['level'], + 'version' => $meta['version'], + 'conformance' => $conformance, + 'violations_count' => $count, + 'remarks' => $remarks, + ]; + } + + $metrics = AccessibilityScoreCalculator::calculate($violations); + + return [ + 'vpat_version' => '2.5 (WCAG / Revised 508 / EN 301 549)', + 'generated_at' => date('Y-m-d\TH:i:sP'), + 'product_name' => $productName, + 'product_version' => $productVersion, + 'evaluator' => $evaluator, + 'tool' => 'YakNet Accessibility Console v4.0.0', + 'health_score' => $metrics['score'], + 'total_violations' => count($violations), + 'active_rules_count' => count(RuleLevels::getRulesForLevel(9)), + 'summary' => $summary, + 'criteria' => $criteriaRows, + ]; + } + + /** + * Render VPAT 2.5 Accessibility Conformance Report in Markdown format. + * + * @param Violation[] $violations + */ + public function renderMarkdown( + array $violations, + string $productName = 'Web Application', + string $productVersion = '1.0.0', + string $evaluator = 'YakNet Accessibility Console Automated Evaluation' + ): string { + $data = $this->buildReportData($violations, $productName, $productVersion, $evaluator); + + $md = []; + $md[] = '# Accessibility Conformance Report (VPAT 2.5)'; + $md[] = ''; + $md[] = '**WCAG 2.1 / 2.2, Revised Section 508 & EN 301 549 Edition**'; + $md[] = ''; + $md[] = '| Field | Value |'; + $md[] = '| :--- | :--- |'; + $md[] = '| **Product Name** | ' . $data['product_name'] . ' |'; + $md[] = '| **Product Version** | ' . $data['product_version'] . ' |'; + $md[] = '| **Report Date** | ' . $data['generated_at'] . ' |'; + $md[] = '| **Evaluator** | ' . $data['evaluator'] . ' |'; + $md[] = '| **Evaluation Tool** | ' . $data['tool'] . ' |'; + $md[] = '| **Health Score** | ' . $data['health_score'] . '/100 |'; + $md[] = '| **Total Automated Violations** | ' . $data['total_violations'] . ' |'; + $md[] = ''; + $md[] = '## Executive Conformance Summary'; + $md[] = ''; + $md[] = sprintf( + '- **Supports:** %d criteria | **Partially Supports:** %d | **Does Not Support:** %d | **Not Evaluated (Manual):** %d', + $data['summary']['supports'], + $data['summary']['partially_supports'], + $data['summary']['does_not_support'], + $data['summary']['not_evaluated'] + ); + $md[] = ''; + + foreach (['A', 'AA', 'AAA'] as $level) { + $md[] = "## Table: WCAG 2.1 / 2.2 Level {$level}"; + $md[] = ''; + $md[] = '| Criteria | WCAG | Conformance Level | Remarks and Explanations |'; + $md[] = '| :--- | :---: | :--- | :--- |'; + foreach ($data['criteria'] as $row) { + if ($row['level'] !== $level) { + continue; + } + $md[] = sprintf( + '| %s %s | %s | **%s** | %s |', + $row['code'], + $row['title'], + $row['version'], + $row['conformance'], + $row['remarks'] + ); + } + $md[] = ''; + } + + $md[] = '---'; + $md[] = '_Generated by [YakNet Accessibility Console](https://forum.yak.net.tr) (Open Source, MIT License). Automated results should be paired with manual screen-reader and keyboard testing for complete legal attestation._'; + $md[] = ''; + + return implode("\n", $md); + } + + /** + * Render VPAT 2.5 Accessibility Conformance Report in standalone HTML format. + * + * @param Violation[] $violations + */ + public function renderHtml( + array $violations, + string $productName = 'Web Application', + string $productVersion = '1.0.0', + string $evaluator = 'YakNet Accessibility Console Automated Evaluation' + ): string { + $data = $this->buildReportData($violations, $productName, $productVersion, $evaluator); + + $tablesHtml = ''; + foreach (['A', 'AA', 'AAA'] as $level) { + $rowsHtml = ''; + foreach ($data['criteria'] as $row) { + if ($row['level'] !== $level) { + continue; + } + $badgeColor = match ($row['conformance']) { + 'Supports' => '#059669', + 'Partially Supports' => '#d97706', + 'Does Not Support' => '#dc2626', + default => '#475569', + }; + $rowsHtml .= sprintf( + '%s %s WCAG %s%s%s', + htmlspecialchars($row['code']), + htmlspecialchars($row['title']), + htmlspecialchars($row['version']), + $badgeColor, + htmlspecialchars($row['conformance']), + htmlspecialchars($row['remarks']) + ); + } + + $tablesHtml .= "

WCAG 2.1 / 2.2 Level {$level}

" + . '' + . $rowsHtml + . '
Success CriterionConformance LevelRemarks and Explanations
'; + } + + $productEsc = htmlspecialchars($data['product_name']); + $versionEsc = htmlspecialchars($data['product_version']); + $evalEsc = htmlspecialchars($data['evaluator']); + $dateEsc = htmlspecialchars($data['generated_at']); + + return << + + + + +VPAT 2.5 Accessibility Conformance Report — {$productEsc} + + + +
+

VPAT 2.5 Accessibility Conformance Report

+

WCAG 2.1 / 2.2, Revised Section 508 & EN 301 549 Evaluation

+
+
Product{$productEsc} ({$versionEsc})
+
Health Score{$data['health_score']} / 100
+
Evaluator{$evalEsc}
+
Date{$dateEsc}
+
+

+ Supports: {$data['summary']['supports']}  |  + Partially Supports: {$data['summary']['partially_supports']}  |  + Does Not Support: {$data['summary']['does_not_support']}  |  + Not Evaluated (Manual): {$data['summary']['not_evaluated']} +

+ {$tablesHtml} +
+ Generated by YakNet Accessibility Console v4.0.0 (Open Source, MIT License). +
+
+ + +HTML; + } + + /** + * Render VPAT 2.5 Accessibility Conformance Report in JSON format. + * + * @param Violation[] $violations + */ + public function renderJson( + array $violations, + string $productName = 'Web Application', + string $productVersion = '1.0.0', + string $evaluator = 'YakNet Accessibility Console Automated Evaluation' + ): string { + $data = $this->buildReportData($violations, $productName, $productVersion, $evaluator); + return (string)json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } + + private function extractCriterionCode(string $ruleId): string + { + if (preg_match('/WCAG_(\d+)_(\d+)_(\d+)/', $ruleId, $m)) { + return $m[1] . '.' . $m[2] . '.' . $m[3]; + } + + // Map legacy non-numeric rule IDs to their canonical WCAG Success Criteria + return match ($ruleId) { + 'HtmlSyntaxValid', 'DuplicateId' => '4.1.1', + 'HeadingOrder', 'BannedSelectors' => '1.3.1', + 'AccesskeyDuplicate' => '2.1.1', + 'A11Y_VIEWPORT' => '1.4.4', + 'WCAG_LINK_TARGET_BLANK' => '3.2.2', + 'WCAG_FONT_TAG_BANNED' => '1.3.1', + 'AriaRole' => '4.1.2', + 'MetaCharsetPresent' => '4.1.1', + default => '4.1.2', + }; + } +} diff --git a/src/Console/Command/CompareCommand.php b/src/Console/Command/CompareCommand.php new file mode 100644 index 0000000..312a638 --- /dev/null +++ b/src/Console/Command/CompareCommand.php @@ -0,0 +1,124 @@ +setName('compare') + ->setDescription('Compare two JSON accessibility scan reports to detect regressions and resolved violations') + ->addArgument('before', InputArgument::REQUIRED, 'Path to the baseline/previous JSON report') + ->addArgument('after', InputArgument::REQUIRED, 'Path to the new/current JSON report') + ->addOption('fail-on-regression', null, InputOption::VALUE_NONE, 'Return non-zero exit code if new violations were introduced') + ->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (console, json)', 'console'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + + $beforePath = $input->getArgument('before'); + $afterPath = $input->getArgument('after'); + if (!is_string($beforePath) || !is_string($afterPath)) { + $io->error('Both "before" and "after" JSON report paths are required.'); + return Command::FAILURE; + } + + $beforeData = $this->loadViolations($beforePath); + $afterData = $this->loadViolations($afterPath); + + if ($beforeData === null) { + $io->error("Could not read or parse JSON report: {$beforePath}"); + return Command::FAILURE; + } + if ($afterData === null) { + $io->error("Could not read or parse JSON report: {$afterPath}"); + return Command::FAILURE; + } + + $tracker = new HistoryTracker(); + $diff = $tracker->compareReports($beforeData, $afterData); + + $format = strtolower(is_string($input->getOption('format')) ? $input->getOption('format') : 'console'); + if ($format === 'json') { + $output->writeln((string)json_encode($diff, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); + } else { + $io->title('YakNet Accessibility Console - Regression Comparison'); + $deltaSign = $diff['score_delta'] > 0 ? '+' : ''; + $deltaColor = $diff['score_delta'] > 0 ? 'green' : ($diff['score_delta'] < 0 ? 'red' : 'gray'); + + $table = new Table($output); + $table->setHeaders(['Metric', 'Before', 'After', 'Delta']); + $table->addRows([ + ['Health Score', $diff['before_score'] . '/100', $diff['after_score'] . '/100', "{$deltaSign}{$diff['score_delta']}"], + ['Total Violations', (string)$diff['before_count'], (string)$diff['after_count'], (string)($diff['after_count'] - $diff['before_count'])], + ['New Regressions', '-', (string)count($diff['new_violations']), count($diff['new_violations']) > 0 ? 'REGRESSION' : 'NONE'], + ['Resolved Issues', '-', (string)count($diff['resolved_violations']), count($diff['resolved_violations']) > 0 ? 'IMPROVED' : '-'], + ['Unchanged Issues', '-', (string)$diff['unchanged_count'], '-'], + ]); + $table->render(); + $io->newLine(); + + if (!empty($diff['new_violations'])) { + $io->section('Newly Introduced Violations (' . count($diff['new_violations']) . ')'); + foreach ($diff['new_violations'] as $v) { + $ruleId = is_scalar($v['ruleId'] ?? null) ? (string)$v['ruleId'] : 'UNKNOWN'; + $msg = is_scalar($v['message'] ?? null) ? (string)$v['message'] : ''; + $loc = (isset($v['location']) && is_array($v['location']) && is_scalar($v['location']['file'] ?? null)) + ? (string)$v['location']['file'] . ':' . (is_numeric($v['location']['line'] ?? null) ? (int)$v['location']['line'] : 0) + : 'unknown'; + $io->writeln(" + [{$ruleId}] ({$loc}) {$msg}"); + } + } + } + + if ($input->getOption('fail-on-regression') && !empty($diff['new_violations'])) { + return Command::FAILURE; + } + + return Command::SUCCESS; + } + + /** + * @return array>|null + */ + private function loadViolations(string $path): ?array + { + if (!file_exists($path)) { + return null; + } + $raw = @file_get_contents($path); + if ($raw === false) { + return null; + } + $decoded = json_decode($raw, true); + if (!is_array($decoded)) { + return null; + } + + // Support both flat violation arrays and { violations: [...] } wrapped JSON formatters + $list = (isset($decoded['violations']) && is_array($decoded['violations'])) ? $decoded['violations'] : $decoded; + + $result = []; + foreach ($list as $item) { + if (is_array($item)) { + /** @var array $item */ + $result[] = $item; + } + } + return $result; + } +} diff --git a/src/Console/Command/DoctorCommand.php b/src/Console/Command/DoctorCommand.php new file mode 100644 index 0000000..0cc984e --- /dev/null +++ b/src/Console/Command/DoctorCommand.php @@ -0,0 +1,113 @@ +setName('doctor') + ->setDescription('Diagnose environment, rule registry integrity, optional integrations, and configuration health') + ->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to a11y.yaml configuration file'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + $io->title('YakNet Accessibility Console - System & Integrity Doctor'); + + $hasFailures = false; + $rows = []; + + // 1. PHP Version + $phpOk = version_compare(PHP_VERSION, '8.2.0', '>='); + $rows[] = ['PHP Runtime', PHP_VERSION, $phpOk ? 'OK' : 'FAIL (>= 8.2 required)']; + if (!$phpOk) { + $hasFailures = true; + } + + // 2. Required Extensions + foreach (['dom', 'libxml', 'mbstring', 'json'] as $ext) { + $loaded = extension_loaded($ext); + $rows[] = ["PHP ext-{$ext}", $loaded ? 'Loaded' : 'Missing', $loaded ? 'OK' : 'FAIL']; + if (!$loaded) { + $hasFailures = true; + } + } + + // 3. Rule Registry Validation + $rules = RuleLevels::getRulesForLevel(9); + $validation = RuleRegistry::validate($rules); + $rows[] = [ + 'Rule Registry Integrity', + sprintf('%d rules registered', $validation['count']), + $validation['valid'] ? 'VALID (0 conflicts)' : 'ERRORS (' . count($validation['errors']) . ')', + ]; + if (!$validation['valid']) { + $hasFailures = true; + } + + // 4. Compliance Presets + $presets = (new PresetRegistry())->all(); + $rows[] = ['Compliance Presets', sprintf('%d profiles available', count($presets)), 'OK']; + + // 5. Offline Self-Healing Coverage + $healableCount = count(LocalHealer::getSupportedRuleIds()); + $rows[] = ['Offline Self-Healer', sprintf('%d deterministic auto-fixes', $healableCount), 'OK']; + + // 6. Optional Exporters & Renderers + $hasDompdf = class_exists(\Dompdf\Dompdf::class); + $rows[] = ['PDF Report Generator (dompdf)', $hasDompdf ? 'Installed' : 'Not installed', $hasDompdf ? 'READY' : 'OPTIONAL']; + + $hasSpreadsheet = class_exists(\PhpOffice\PhpSpreadsheet\Spreadsheet::class); + $rows[] = ['Excel Exporter (phpspreadsheet)', $hasSpreadsheet ? 'Installed' : 'Not installed', $hasSpreadsheet ? 'READY' : 'OPTIONAL']; + + $hasChrome = class_exists(\HeadlessChromium\BrowserFactory::class); + $rows[] = ['Headless Chrome Renderer', $hasChrome ? 'Installed' : 'Not installed', $hasChrome ? 'READY' : 'OPTIONAL']; + + // 7. Configuration & AI Key + $configOption = $input->getOption('config'); + $configPath = is_string($configOption) ? $configOption : getcwd() . '/a11y.yaml'; + $configExists = file_exists($configPath); + $config = Config::fromYaml($configPath); + $rows[] = ['Configuration (a11y.yaml)', $configExists ? $configPath : 'Using built-in defaults', 'OK']; + + $hasAiKey = $config->getGeminiApiKey() !== null && $config->getGeminiApiKey() !== ''; + $rows[] = ['AI Self-Healing (GEMINI_API_KEY)', $hasAiKey ? 'Configured' : 'Not set (offline healer active)', $hasAiKey ? 'READY' : 'OFFLINE MODE']; + + $table = new Table($output); + $table->setHeaders(['Component', 'Details', 'Status']); + $table->setRows($rows); + $table->render(); + $io->newLine(); + + if (!$validation['valid']) { + foreach ($validation['errors'] as $err) { + $io->error($err); + } + } + + if ($hasFailures) { + $io->error('One or more critical system checks failed.'); + return Command::FAILURE; + } + + $io->success('All critical checks passed. YakNet Accessibility Console is ready.'); + return Command::SUCCESS; + } +} diff --git a/src/Console/Command/ExplainCommand.php b/src/Console/Command/ExplainCommand.php new file mode 100644 index 0000000..98ee58a --- /dev/null +++ b/src/Console/Command/ExplainCommand.php @@ -0,0 +1,106 @@ +setName('explain') + ->setDescription('Display detailed documentation, WCAG reference, and code examples for a specific rule ID') + ->addArgument('rule', InputArgument::REQUIRED, 'Rule ID or class short name (e.g. WCAG_2_5_8_TARGET_SIZE)'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + $query = $input->getArgument('rule'); + if (!is_string($query) || trim($query) === '') { + $io->error('Please provide a rule ID to explain.'); + return Command::FAILURE; + } + + $controller = new RuleController(); + $rule = $controller->getRule($query); + + // Case-insensitive or short-name fallback lookup + if ($rule === null) { + foreach (\YakNet\AccessibilityConsole\Rules\RuleLevels::getRulesForLevel(9) as $candidate) { + $meta = RuleRegistry::getMetadata($candidate); + $candId = is_scalar($meta['id'] ?? null) ? (string)$meta['id'] : ''; + $candShort = is_scalar($meta['shortName'] ?? null) ? (string)$meta['shortName'] : ''; + if (strcasecmp($candId, $query) === 0 || strcasecmp($candShort, $query) === 0) { + $rule = $candidate; + break; + } + } + } + + if ($rule === null) { + $io->error("Rule '{$query}' not found. Run `a11y rules --search={$query}` to search available rules."); + return Command::FAILURE; + } + + $meta = RuleRegistry::getMetadata($rule); + $ruleId = is_scalar($meta['id'] ?? null) ? (string)$meta['id'] : ''; + $className = is_scalar($meta['class'] ?? null) ? (string)$meta['class'] : ''; + $type = is_scalar($meta['type'] ?? null) ? (string)$meta['type'] : 'element'; + $standard = is_scalar($meta['standard'] ?? null) ? (string)$meta['standard'] : 'A'; + $severity = is_scalar($meta['severity'] ?? null) ? (string)$meta['severity'] : 'error'; + $level = is_scalar($meta['level'] ?? null) ? (string)$meta['level'] : '4'; + $description = is_scalar($meta['description'] ?? null) ? (string)$meta['description'] : ''; + + $wcag = WcagDatabase::get($ruleId); + $isHealable = in_array($ruleId, LocalHealer::getSupportedRuleIds(), true); + + $principle = 'Robust'; + if (preg_match('/WCAG_([1-4])_/', $ruleId, $m)) { + $principle = match ((int)$m[1]) { + 1 => 'Perceivable', + 2 => 'Operable', + 3 => 'Understandable', + default => 'Robust', + }; + } + + $io->title("Rule Reference: {$ruleId}"); + $io->definitionList( + ['Class' => $className], + ['Type' => ucfirst($type) . '-level rule'], + ['WCAG Level' => 'Level ' . $standard], + ['POUR Principle' => $principle], + ['Severity' => strtoupper($severity)], + ['Scan Level' => 'Level ' . $level], + ['Offline Auto-Fix' => $isHealable ? 'Supported (`a11y fix --offline`)' : 'Manual / AI (`a11y fix`)'], + ['Description' => $description] + ); + + if ($wcag !== null) { + $io->section('W3C WCAG Guidance'); + $io->writeln("Criterion: {$wcag->title} (Level {$wcag->level})"); + $io->writeln("Reference: {$wcag->url}"); + $io->newLine(); + $io->writeln("Non-Compliant Example:"); + $io->writeln(" " . $wcag->badExample); + $io->newLine(); + $io->writeln("Compliant Example:"); + $io->writeln(" " . $wcag->goodExample); + $io->newLine(); + } + + return Command::SUCCESS; + } +} diff --git a/src/Console/Command/FixCommand.php b/src/Console/Command/FixCommand.php index a81a5ad..3099681 100644 --- a/src/Console/Command/FixCommand.php +++ b/src/Console/Command/FixCommand.php @@ -151,7 +151,7 @@ class FixCommand extends Command continue; } - if (is_string($rawSuggestion) && $suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) { + if ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) { $io->writeln("Skipped (AI could not generate a clean fix)"); continue; } @@ -278,7 +278,7 @@ class FixCommand extends Command continue; } - if (is_string($rawSuggestion) && $suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) { + if ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) { $io->writeln("Skipped (AI could not generate a clean fix)"); continue; } diff --git a/src/Console/Command/InitCommand.php b/src/Console/Command/InitCommand.php index d2a2d35..db84cb0 100644 --- a/src/Console/Command/InitCommand.php +++ b/src/Console/Command/InitCommand.php @@ -4,8 +4,10 @@ namespace YakNet\AccessibilityConsole\Console\Command; use Symfony\Component\Console\Command\Command; 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\CI\CiWorkflowGenerator; class InitCommand extends Command { @@ -13,12 +15,36 @@ class InitCommand extends Command { $this ->setName('init') - ->setDescription('Initialize a default a11y.yaml configuration file'); + ->setDescription('Initialize a default a11y.yaml configuration file and optional CI/CD workflow') + ->addOption('ci', null, InputOption::VALUE_REQUIRED, 'Generate CI/CD workflow template (github, gitlab, azure, bitbucket)') + ->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Default compliance preset for generated CI workflow', 'wcag22-aa'); } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); + + // Optional CI/CD pipeline workflow scaffolding + $ciOption = $input->getOption('ci'); + if (is_string($ciOption) && $ciOption !== '') { + $preset = is_string($input->getOption('preset')) ? $input->getOption('preset') : 'wcag22-aa'; + try { + $generator = new CiWorkflowGenerator(); + $yaml = $generator->generate($ciOption, $preset); + $relPath = CiWorkflowGenerator::getDefaultPath($ciOption); + $fullPath = getcwd() . '/' . $relPath; + $dir = dirname($fullPath); + if (!is_dir($dir)) { + @mkdir($dir, 0775, true); + } + file_put_contents($fullPath, $yaml); + $io->success("Generated CI/CD workflow ({$ciOption}) at: {$relPath}"); + } catch (\InvalidArgumentException $e) { + $io->error($e->getMessage()); + return Command::FAILURE; + } + } + $configPath = getcwd() . '/a11y.yaml'; if (file_exists($configPath)) { @@ -42,15 +68,55 @@ exclude_paths: - storage - .git -# Accessibility scanning level (1-9, default 4) +# Accessibility scanning level (1-5, default 4) level: 4 -# Output format (console, json, html, github) +# Optional regulatory or sectoral compliance preset +# Available: section508, en301549, eaa2025, bitv2, wcag22-aa, wcag22-aaa, +# government, healthcare, banking, education, ecommerce +# preset: wcag22-aa + +# Output format (console, json, github, gitlab, sarif, junit, checkstyle, markdown, csv, xml) format: console +# File extensions to analyse (Blade, Twig, Vue, JSX/TSX, PHP, HTML) +extensions: + - php + - html + - htm + - twig + - blade.php + - vue + - jsx + - tsx + # Path to the baseline file for ignoring existing violations # baseline: a11y-baseline.json +# Governance policy thresholds (enforced automatically during `a11y scan`) +# policy: +# min_score: 90 +# max_critical: 0 +# max_errors: 0 +# max_warnings: 10 +# required_standards: +# - A +# banned_rules: +# - WCAG_1_1_1_ALT +# - WCAG_2_3_1_FLASHING_CONTENT +# severity_overrides: +# WCAG_2_5_8_TARGET_SIZE: error +# principle_limits: +# Perceivable: 0 + +# Optional CI/CD webhook notifications +# notifications: +# slack_webhook: "" +# discord_webhook: "" +# teams_webhook: "" +# webhook_url: "" +# webhook_secret: "" + # Rule adjustments rules: # Rules to exclude from analysis diff --git a/src/Console/Command/PresetsCommand.php b/src/Console/Command/PresetsCommand.php new file mode 100644 index 0000000..ac9e475 --- /dev/null +++ b/src/Console/Command/PresetsCommand.php @@ -0,0 +1,49 @@ +setName('presets') + ->setDescription('List all available regulatory and sectoral compliance presets'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + $io->title('YakNet Accessibility Console - Compliance Presets'); + + $registry = new PresetRegistry(); + $presets = $registry->all(); + + $table = new Table($output); + $table->setHeaders(['Preset Name', 'Rule Level', 'Priority Rules', 'Description']); + + foreach ($presets as $preset) { + $table->addRow([ + '' . $preset->getName() . '', + 'Level ' . $preset->getLevel(), + (string)count($preset->getIncludedRules()), + $preset->getDescription(), + ]); + } + + $table->render(); + $io->newLine(); + $io->note(sprintf('Total compliance presets available: %d. Use with `a11y scan --preset=`.', count($presets))); + + return Command::SUCCESS; + } +} diff --git a/src/Console/Command/RulesCommand.php b/src/Console/Command/RulesCommand.php index 335bc92..367e032 100644 --- a/src/Console/Command/RulesCommand.php +++ b/src/Console/Command/RulesCommand.php @@ -7,6 +7,7 @@ use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; +use YakNet\AccessibilityConsole\Core\SelfHealing\LocalHealer; use YakNet\AccessibilityConsole\Rules\RuleLevels; use Symfony\Component\Console\Input\InputOption; @@ -21,7 +22,9 @@ class RulesCommand extends Command ->addOption('search', 's', InputOption::VALUE_REQUIRED, 'Search rules by ID or description') ->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Filter rules by maximum level (1-5)') ->addOption('standard', null, InputOption::VALUE_REQUIRED, 'Filter rules by standard (A, AA, AAA)') - ->addOption('severity', null, InputOption::VALUE_REQUIRED, 'Filter rules by severity (error, warning, info)'); + ->addOption('severity', null, InputOption::VALUE_REQUIRED, 'Filter rules by severity (critical, error, warning, info)') + ->addOption('principle', null, InputOption::VALUE_REQUIRED, 'Filter rules by POUR principle (Perceivable, Operable, Understandable, Robust)') + ->addOption('healable', null, InputOption::VALUE_NONE, 'Show only rules with deterministic offline auto-fix support'); } protected function execute(InputInterface $input, OutputInterface $output): int @@ -33,6 +36,9 @@ class RulesCommand extends Command $levelFilter = $input->getOption('level'); $standardFilter = $input->getOption('standard'); $severityFilter = $input->getOption('severity'); + $principleFilter = $input->getOption('principle'); + $healableOnly = (bool)$input->getOption('healable'); + $healableIds = LocalHealer::getSupportedRuleIds(); $maxLevel = is_numeric($levelFilter) ? (int)$levelFilter : 9; $rules = RuleLevels::getRulesForLevel($maxLevel); @@ -42,9 +48,7 @@ class RulesCommand extends Command $matchedCount = 0; foreach ($rules as $rule) { - $ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface) - ? $rule->getId() - : (new \ReflectionClass($rule))->getShortName(); + $ruleId = $rule->getId(); $description = method_exists($rule, 'getDescription') ? $rule->getDescription() : ''; $standard = method_exists($rule, 'getStandard') ? $rule->getStandard()->value : ''; @@ -72,6 +76,27 @@ class RulesCommand extends Command continue; } } + + // Principle filter + if (is_string($principleFilter) && $principleFilter !== '') { + $rulePrinciple = 'Robust'; + if (preg_match('/WCAG_([1-4])_/', $ruleId, $m)) { + $rulePrinciple = match ((int)$m[1]) { + 1 => 'Perceivable', + 2 => 'Operable', + 3 => 'Understandable', + default => 'Robust', + }; + } + if (strcasecmp($rulePrinciple, $principleFilter) !== 0) { + continue; + } + } + + // Healable filter + if ($healableOnly && !in_array($ruleId, $healableIds, true)) { + continue; + } $table->addRow([ "$ruleId", @@ -86,7 +111,10 @@ class RulesCommand extends Command $table->render(); $io->newLine(); - if (is_string($searchQuery) || $levelFilter !== null || is_string($standardFilter) || is_string($severityFilter)) { + $hasFilter = is_string($searchQuery) || $levelFilter !== null || is_string($standardFilter) + || is_string($severityFilter) || is_string($principleFilter) || $healableOnly; + + if ($hasFilter) { $io->note(sprintf("Showing %d matching rules (out of %d total rules).", $matchedCount, count(RuleLevels::getRulesForLevel(9)))); } else { $io->note("Total rules available: " . count($rules)); diff --git a/src/Console/Command/ScanCommand.php b/src/Console/Command/ScanCommand.php index 8d91ace..cee5f5d 100644 --- a/src/Console/Command/ScanCommand.php +++ b/src/Console/Command/ScanCommand.php @@ -10,12 +10,24 @@ 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\Analytics\HistoryTracker; +use YakNet\AccessibilityConsole\Cache\ScanCache; +use YakNet\AccessibilityConsole\Compliance\VpatReportGenerator; use YakNet\AccessibilityConsole\Core\Analyser; use YakNet\AccessibilityConsole\Core\BaselineManager; use YakNet\AccessibilityConsole\Core\Config; use YakNet\AccessibilityConsole\Core\Scanner; use YakNet\AccessibilityConsole\Core\Severity; +use YakNet\AccessibilityConsole\Notifications\DiscordNotifier; +use YakNet\AccessibilityConsole\Notifications\GenericWebhookNotifier; +use YakNet\AccessibilityConsole\Notifications\MicrosoftTeamsNotifier; +use YakNet\AccessibilityConsole\Notifications\NotificationDispatcher; +use YakNet\AccessibilityConsole\Notifications\NotificationPayload; +use YakNet\AccessibilityConsole\Notifications\SlackNotifier; +use YakNet\AccessibilityConsole\Policy\PolicyEngine; +use YakNet\AccessibilityConsole\Rules\RuleExecutionStats; use YakNet\AccessibilityConsole\Rules\RuleLevels; +use YakNet\AccessibilityConsole\Reporting\CheckstyleFormatter; use YakNet\AccessibilityConsole\Reporting\ConsoleFormatter; use YakNet\AccessibilityConsole\Reporting\GithubFormatter; use YakNet\AccessibilityConsole\Reporting\JsonFormatter; @@ -42,8 +54,8 @@ class ScanCommand extends Command ->addArgument('target', InputArgument::OPTIONAL, 'The URL, file, or directory path to scan') ->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to the configuration file (default: a11y.yaml)') ->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-9)') - ->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Use a pre-configured audit profile (section508, en301549, ecommerce)') - ->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (console, json, github, xml, markdown, csv, gitlab, sarif, junit)') + ->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Use a compliance preset (section508, en301549, eaa2025, bitv2, wcag22-aa, wcag22-aaa, government, healthcare, banking, education, ecommerce)') + ->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (console, json, github, xml, markdown, csv, gitlab, sarif, junit, checkstyle)') ->addOption('min-score', null, InputOption::VALUE_REQUIRED, 'Minimum required accessibility health score (0-100) to pass the quality gate') ->addOption('max-warnings', null, InputOption::VALUE_REQUIRED, 'Maximum allowed warnings before failing the quality gate') ->addOption('fail-on', null, InputOption::VALUE_REQUIRED, 'Minimum severity to fail on (error, warning, info)') @@ -51,7 +63,16 @@ class ScanCommand extends Command ->addOption('baseline', null, InputOption::VALUE_REQUIRED, 'Path to the baseline file') ->addOption('no-progress', null, InputOption::VALUE_NONE, 'Disable progress bar') ->addOption('ai', null, InputOption::VALUE_NONE, 'Enable AI-powered fix suggestions') - ->addOption('report', null, InputOption::VALUE_REQUIRED, 'Save report to file (html, json, sarif, xml, junit, pdf, xlsx)') + ->addOption('report', null, InputOption::VALUE_REQUIRED, 'Save report to file (html, json, sarif, xml, junit, checkstyle, pdf, xlsx)') + ->addOption('vpat', null, InputOption::VALUE_REQUIRED, 'Export a VPAT 2.5 Conformance Report to file (.md, .html, or .json)') + ->addOption('save-history', null, InputOption::VALUE_REQUIRED, 'Append scan snapshot to a JSON history file for trend tracking') + ->addOption('cache', null, InputOption::VALUE_REQUIRED, 'Path to incremental content-hash cache file (e.g. .a11y-cache.json)') + ->addOption('clear-cache', null, InputOption::VALUE_NONE, 'Clear the incremental scan cache before scanning') + ->addOption('profile', null, InputOption::VALUE_NONE, 'Display rule execution timing profile (top slowest rules)') + ->addOption('webhook-slack', null, InputOption::VALUE_REQUIRED, 'Send scan summary to a Slack Incoming Webhook URL') + ->addOption('webhook-discord', null, InputOption::VALUE_REQUIRED, 'Send scan summary to a Discord Webhook URL') + ->addOption('webhook-teams', null, InputOption::VALUE_REQUIRED, 'Send scan summary to a Microsoft Teams Webhook URL') + ->addOption('webhook-url', null, InputOption::VALUE_REQUIRED, 'Send JSON payload to a generic webhook URL') ->addOption('badge', null, InputOption::VALUE_REQUIRED, 'Save SVG accessibility health badge to file (e.g. a11y-badge.svg)') ->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping (URL scans only)') ->addOption('crawl', null, InputOption::VALUE_NONE, 'Crawl internal links recursively (URL scans only)') @@ -74,14 +95,15 @@ class ScanCommand extends Command $level = is_numeric($levelOption) ? (int)$levelOption : $config->getLevel(); $presetOption = $input->getOption('preset'); + $presetName = (is_string($presetOption) && $presetOption !== '') ? $presetOption : $config->getPreset(); $activePreset = null; - if (is_string($presetOption) && $presetOption !== '') { + if (is_string($presetName) && $presetName !== '') { $presetRegistry = new PresetRegistry(); - $activePreset = $presetRegistry->get($presetOption); + $activePreset = $presetRegistry->get($presetName); if ($activePreset !== null) { $level = $activePreset->getLevel(); } else { - $io->warning("Preset '{$presetOption}' not found. Using default rules."); + $io->warning("Preset '{$presetName}' not found. Using default rules."); } } @@ -120,30 +142,53 @@ class ScanCommand extends Command // Setup Analyser $scanner = new Scanner(); + $enableProfile = (bool)$input->getOption('profile'); + $executionStats = $enableProfile ? new RuleExecutionStats() : null; + if ($executionStats !== null) { + $scanner->getEngine()->setStats($executionStats); + } + $rules = RuleLevels::getRulesForLevel($level); - // Filter rules based on config + // Filter rules based on config and active preset $rulesConfig = $config->getRulesConfig(); + $excludedIds = $rulesConfig['exclude']; + if ($activePreset !== null) { + $excludedIds = array_values(array_unique(array_merge($excludedIds, $activePreset->getExcludedRules()))); + } + $activeRules = []; foreach ($rules as $rule) { - $ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface) - ? $rule->getId() - : (new \ReflectionClass($rule))->getShortName(); + $ruleId = $rule->getId(); - if (in_array($ruleId, $rulesConfig['exclude'], true)) { + if (in_array($ruleId, $excludedIds, true)) { continue; } $activeRules[$ruleId] = $rule; } + // Ensure preset-included priority rules are active even if they belong to a higher scan level + if ($activePreset !== null && !empty($activePreset->getIncludedRules())) { + $allRulesById = []; + foreach (RuleLevels::getRulesForLevel(9) as $candidateRule) { + $cid = $candidateRule->getId(); + $allRulesById[$cid] = $candidateRule; + } + foreach ($activePreset->getIncludedRules() as $priorityRuleId) { + if (!isset($activeRules[$priorityRuleId]) && isset($allRulesById[$priorityRuleId]) && !in_array($priorityRuleId, $excludedIds, true)) { + $activeRules[$priorityRuleId] = $allRulesById[$priorityRuleId]; + } + } + } + foreach ($rulesConfig['include'] as $customRuleClass) { if (class_exists($customRuleClass)) { try { $reflection = new \ReflectionClass($customRuleClass); if ($reflection->isInstantiable()) { $rule = $reflection->newInstance(); - $ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface) - ? $rule->getId() + $ruleId = method_exists($rule, 'getId') + ? $rule->getId() : $reflection->getShortName(); $activeRules[$ruleId] = $rule; } @@ -161,7 +206,20 @@ class ScanCommand extends Command $baselineManager->load(getcwd() . '/' . $baselinePath); } - $analyser = new Analyser($config, $scanner, $baselineManager); + // Setup Incremental Scan Cache (if --cache is passed) + $scanCache = null; + $cachePathOption = $input->getOption('cache'); + if (is_string($cachePathOption) && $cachePathOption !== '') { + $rulesSig = hash('sha256', implode('|', array_keys($activeRules))); + $scanCache = new ScanCache($cachePathOption, $rulesSig); + if ($input->getOption('clear-cache')) { + $scanCache->clear(); + } else { + $scanCache->load(); + } + } + + $analyser = new Analyser($config, $scanner, $baselineManager, null, null, null, $scanCache); // Progress bar setup $progressBar = null; @@ -229,6 +287,10 @@ class ScanCommand extends Command } } + // Apply governance policy severity overrides before formatting & scoring + $policyEngine = new PolicyEngine($config->getPolicyConfig()); + $policyEngine->applySeverityOverrides($violations); + // Select formatter $formatter = new ConsoleFormatter(); if ($format === 'json') { @@ -247,12 +309,15 @@ class ScanCommand extends Command $formatter = new SarifFormatter(); } elseif ($format === 'junit') { $formatter = new JunitFormatter(); + } elseif ($format === 'checkstyle') { + $formatter = new CheckstyleFormatter(); } $exitCode = $formatter->format($violations, $baselinedCount, $io); $metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations); $score = $metrics['score']; + $suppressedLog = $analyser->getSuppressedAuditLog(); if ($format === 'console') { $io->section("Accessibility Ratings"); @@ -261,10 +326,34 @@ class ScanCommand extends Command $io->writeln(sprintf(" - Screen Reader / Visual Impact: %d%%", $metrics['visualImpact'])); $io->writeln(sprintf(" - Keyboard / Motor Impact: %d%%", $metrics['motorImpact'])); $io->writeln(sprintf(" - Cognitive / Distraction Impact: %d%%", $metrics['cognitiveImpact'])); + if (!empty($suppressedLog)) { + $io->writeln(sprintf(" - Inline Suppressed Violations: %d", count($suppressedLog))); + } $io->newLine(); } - // Quality Gate evaluation + // Execution profiling summary (--profile) + if ($executionStats !== null && $format === 'console') { + $slowest = $executionStats->getSlowestRules(10); + if (!empty($slowest)) { + $io->section('Rule Execution Profile (Top 10 Slowest)'); + $profileTable = new \Symfony\Component\Console\Helper\Table($output); + $profileTable->setHeaders(['Rule ID', 'Invocations', 'Total (ms)', 'Avg (ms)', 'Violations']); + foreach ($slowest as $rId => $stat) { + $profileTable->addRow([ + $rId, + (string)$stat['invocations'], + sprintf('%.3f', $stat['total_time_ms']), + sprintf('%.4f', $stat['avg_time_ms']), + (string)$stat['violations'], + ]); + } + $profileTable->render(); + $io->newLine(); + } + } + + // Quality Gate & Policy Engine evaluation $minScoreOption = $input->getOption('min-score'); $maxWarningsOption = $input->getOption('max-warnings'); $failOnOption = $input->getOption('fail-on'); @@ -283,6 +372,14 @@ class ScanCommand extends Command /** @var string[] $gateFailures */ $gateFailures = []; + if ($policyEngine->hasPolicies()) { + $policyResult = $policyEngine->evaluate($violations); + if (!$policyResult->passed) { + $qualityGateFailed = true; + $gateFailures = array_merge($gateFailures, $policyResult->failures); + } + } + if ($minScoreOption !== null && is_numeric($minScoreOption)) { $minScore = (int)$minScoreOption; if ($score < $minScore) { @@ -320,6 +417,32 @@ class ScanCommand extends Command $this->exportReport($reportPath, $violations, 'Static Analysis', $io); } + // Export VPAT 2.5 report if --vpat is specified + $vpatPath = $input->getOption('vpat'); + if (is_string($vpatPath) && $vpatPath !== '') { + $vpatGenerator = new VpatReportGenerator(); + $vpatExt = strtolower(pathinfo($vpatPath, PATHINFO_EXTENSION)); + $vpatContent = match ($vpatExt) { + 'html', 'htm' => $vpatGenerator->renderHtml($violations, basename((string)getcwd()) ?: 'Web Application'), + 'json' => $vpatGenerator->renderJson($violations, basename((string)getcwd()) ?: 'Web Application'), + default => $vpatGenerator->renderMarkdown($violations, basename((string)getcwd()) ?: 'Web Application'), + }; + file_put_contents($vpatPath, $vpatContent); + $io->success("VPAT 2.5 Conformance Report saved to: $vpatPath"); + } + + // Save history snapshot if --save-history is specified + $historyPath = $input->getOption('save-history'); + if (is_string($historyPath) && $historyPath !== '') { + $tracker = new HistoryTracker(); + $tracker->record($violations, $historyPath, implode(', ', $paths), $activePreset?->getName()); + $trend = $tracker->computeTrend($tracker->load($historyPath)); + if ($format === 'console') { + $deltaStr = $trend['score_delta'] > 0 ? '+' . $trend['score_delta'] : (string)$trend['score_delta']; + $io->note(sprintf('History saved (%d total runs, trend: %s, delta: %s).', $trend['runs'], $trend['trend'], $deltaStr)); + } + } + // Export SVG badge if --badge is specified $badgePath = $input->getOption('badge'); if (is_string($badgePath) && $badgePath !== '') { @@ -327,6 +450,9 @@ class ScanCommand extends Command $io->success("SVG Badge saved to: $badgePath"); } + // Dispatch webhook notifications (CLI flags or a11y.yaml notifications block) + $this->dispatchNotifications($input, $config, implode(', ', $paths), $score, $violations, $errorCount, $warningCount); + return $exitCode; } @@ -561,6 +687,9 @@ class ScanCommand extends Command } elseif ($extension === 'sarif') { $sarifFormatter = new SarifFormatter(); file_put_contents($reportPath, $sarifFormatter->render($violations)); + } elseif ($extension === 'checkstyle') { + $checkstyleFormatter = new CheckstyleFormatter(); + file_put_contents($reportPath, $checkstyleFormatter->render($violations)); } elseif ($extension === 'xml' || $extension === 'junit') { $junitFormatter = new JunitFormatter(); file_put_contents($reportPath, $junitFormatter->render($violations)); @@ -594,5 +723,76 @@ class ScanCommand extends Command $io->success("Report saved to: $reportPath"); } + + /** + * Dispatch configured webhook notifications (Slack, Discord, Microsoft Teams, generic JSON webhook). + * + * @param \YakNet\AccessibilityConsole\Core\Violation[] $violations + */ + private function dispatchNotifications( + InputInterface $input, + Config $config, + string $target, + int $score, + array $violations, + int $errorCount, + int $warningCount + ): void { + $notifConfig = $config->getNotificationsConfig(); + $dispatcher = new NotificationDispatcher(); + + $slackUrl = $input->getOption('webhook-slack'); + if (!is_string($slackUrl) || $slackUrl === '') { + $slackUrl = is_string($notifConfig['slack_webhook'] ?? null) ? $notifConfig['slack_webhook'] : ''; + } + if ($slackUrl !== '') { + $dispatcher->addNotifier('slack', new SlackNotifier($slackUrl)); + } + + $discordUrl = $input->getOption('webhook-discord'); + if (!is_string($discordUrl) || $discordUrl === '') { + $discordUrl = is_string($notifConfig['discord_webhook'] ?? null) ? $notifConfig['discord_webhook'] : ''; + } + if ($discordUrl !== '') { + $dispatcher->addNotifier('discord', new DiscordNotifier($discordUrl)); + } + + $teamsUrl = $input->getOption('webhook-teams'); + if (!is_string($teamsUrl) || $teamsUrl === '') { + $teamsUrl = is_string($notifConfig['teams_webhook'] ?? null) ? $notifConfig['teams_webhook'] : ''; + } + if ($teamsUrl !== '') { + $dispatcher->addNotifier('teams', new MicrosoftTeamsNotifier($teamsUrl)); + } + + $genericUrl = $input->getOption('webhook-url'); + if (!is_string($genericUrl) || $genericUrl === '') { + $genericUrl = is_string($notifConfig['webhook_url'] ?? null) ? $notifConfig['webhook_url'] : ''; + } + $secret = is_string($notifConfig['webhook_secret'] ?? null) ? $notifConfig['webhook_secret'] : null; + if ($genericUrl !== '') { + $dispatcher->addNotifier('webhook', new GenericWebhookNotifier($genericUrl, $secret)); + } + + if (!$dispatcher->hasNotifiers()) { + return; + } + + $topViolations = array_map( + static fn($v): array => $v->toArray(), + array_slice($violations, 0, 5) + ); + + $payload = new NotificationPayload( + target: $target, + healthScore: $score, + totalViolations: count($violations), + errorCount: $errorCount, + warningCount: $warningCount, + topViolations: $topViolations + ); + + $dispatcher->dispatch($payload); + } } diff --git a/src/Console/Command/VpatCommand.php b/src/Console/Command/VpatCommand.php new file mode 100644 index 0000000..f123b4d --- /dev/null +++ b/src/Console/Command/VpatCommand.php @@ -0,0 +1,96 @@ +setName('vpat') + ->setDescription('Generate a VPAT 2.5 Accessibility Conformance Report (WCAG 2.1/2.2, Section 508, EN 301 549)') + ->addArgument('target', InputArgument::OPTIONAL, 'Target file or directory path to evaluate') + ->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to a11y.yaml configuration file') + ->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Rule level (1-5)', '5') + ->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Compliance preset (e.g. wcag22-aa, en301549, section508, government)') + ->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (markdown, html, json)', 'markdown') + ->addOption('output', 'o', InputOption::VALUE_REQUIRED, 'Write the VPAT 2.5 report to a file path') + ->addOption('product', null, InputOption::VALUE_REQUIRED, 'Product or application name', 'Web Application') + ->addOption('product-version', null, InputOption::VALUE_REQUIRED, 'Product version string', '1.0.0') + ->addOption('evaluator', null, InputOption::VALUE_REQUIRED, 'Evaluator name or team', 'YakNet Accessibility Console'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $io = new SymfonyStyle($input, $output); + + $configOption = $input->getOption('config'); + $configPath = is_string($configOption) ? $configOption : getcwd() . '/a11y.yaml'; + $config = Config::fromYaml($configPath); + + $levelOption = $input->getOption('level'); + $level = is_numeric($levelOption) ? (int)$levelOption : 5; + + $presetOption = $input->getOption('preset'); + if (is_string($presetOption) && $presetOption !== '') { + $preset = (new PresetRegistry())->get($presetOption); + if ($preset !== null) { + $level = $preset->getLevel(); + } + } + + $target = $input->getArgument('target'); + $paths = is_string($target) && $target !== '' ? [$target] : $config->getPaths(); + + $scanner = new Scanner(); + foreach (RuleLevels::getRulesForLevel($level) as $rule) { + $scanner->addRule($rule); + } + + $analyser = new Analyser($config, $scanner, new BaselineManager()); + $result = $analyser->analyse($paths); + $violations = $result['violations']; + + $product = is_string($input->getOption('product')) ? $input->getOption('product') : 'Web Application'; + $productVersion = is_string($input->getOption('product-version')) ? $input->getOption('product-version') : '1.0.0'; + $evaluator = is_string($input->getOption('evaluator')) ? $input->getOption('evaluator') : 'YakNet Accessibility Console'; + $format = strtolower(is_string($input->getOption('format')) ? $input->getOption('format') : 'markdown'); + + $generator = new VpatReportGenerator(); + $rendered = match ($format) { + 'html' => $generator->renderHtml($violations, $product, $productVersion, $evaluator), + 'json' => $generator->renderJson($violations, $product, $productVersion, $evaluator), + default => $generator->renderMarkdown($violations, $product, $productVersion, $evaluator), + }; + + $outputFile = $input->getOption('output'); + if (is_string($outputFile) && $outputFile !== '') { + $dir = dirname($outputFile); + if (!is_dir($dir) && $dir !== '.') { + @mkdir($dir, 0775, true); + } + file_put_contents($outputFile, $rendered); + $io->success(sprintf('VPAT 2.5 report (%s) saved to: %s', strtoupper($format), $outputFile)); + return Command::SUCCESS; + } + + $output->write($rendered); + return Command::SUCCESS; + } +} diff --git a/src/Core/Analyser.php b/src/Core/Analyser.php index 6b98689..7c66b11 100644 --- a/src/Core/Analyser.php +++ b/src/Core/Analyser.php @@ -5,7 +5,9 @@ namespace YakNet\AccessibilityConsole\Core; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use SplFileInfo; +use YakNet\AccessibilityConsole\Cache\ScanCache; use YakNet\AccessibilityConsole\Core\Locator\PreciseElementLocator; +use YakNet\AccessibilityConsole\Core\Suppression\InlineSuppressionParser; use YakNet\AccessibilityConsole\Parser\TemplatePreprocessor; use YakNet\AccessibilityConsole\Rules\RuleLevels; @@ -16,20 +18,29 @@ class Analyser private BaselineManager $baselineManager; private TemplatePreprocessor $templatePreprocessor; private PreciseElementLocator $elementLocator; + private InlineSuppressionParser $suppressionParser; + private ?ScanCache $cache; private string $projectRoot; + /** @var array */ + private array $suppressedAuditLog = []; + public function __construct( ?Config $config = null, ?Scanner $scanner = null, ?BaselineManager $baselineManager = null, ?TemplatePreprocessor $templatePreprocessor = null, - ?PreciseElementLocator $elementLocator = null + ?PreciseElementLocator $elementLocator = null, + ?InlineSuppressionParser $suppressionParser = null, + ?ScanCache $cache = null ) { $this->config = $config ?? new Config(); $this->scanner = $scanner ?? $this->setupScanner(); $this->baselineManager = $baselineManager ?? new BaselineManager(); $this->templatePreprocessor = $templatePreprocessor ?? new TemplatePreprocessor(); $this->elementLocator = $elementLocator ?? new PreciseElementLocator(); + $this->suppressionParser = $suppressionParser ?? new InlineSuppressionParser(); + $this->cache = $cache; $cwd = getcwd(); $this->projectRoot = $cwd ? str_replace('\\', '/', realpath($cwd) ?: $cwd) : '.'; @@ -50,9 +61,7 @@ class Analyser $activeRules = []; foreach ($rules as $rule) { - $ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface) - ? $rule->getId() - : (new \ReflectionClass($rule))->getShortName(); + $ruleId = $rule->getId(); if (in_array($ruleId, $rulesConfig['exclude'], true)) { continue; @@ -67,8 +76,8 @@ class Analyser $reflection = new \ReflectionClass($customRuleClass); if ($reflection->isInstantiable()) { $rule = $reflection->newInstance(); - $ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface) - ? $rule->getId() + $ruleId = method_exists($rule, 'getId') + ? $rule->getId() : $reflection->getShortName(); $activeRules[$ruleId] = $rule; } @@ -113,6 +122,7 @@ class Analyser $violations = []; $baselinedCount = 0; + $this->suppressedAuditLog = []; foreach ($filesToScan as $index => $file) { if ($onProgress) { @@ -124,30 +134,57 @@ class Analyser continue; } - // Preprocess templates (Blade, Twig, PHP) into scan-ready HTML preserving line numbers - $scanContent = $this->templatePreprocessor->preprocess($rawContent, $file); - - // Scan file content - try { - $fileViolations = $this->scanner->scan($scanContent); - } catch (\Throwable $e) { - // Skip if parsing failed dramatically - continue; + $relativeFile = $this->makePathRelative($file); + + // Parse inline suppression directives () + $suppressions = $this->suppressionParser->parse($rawContent); + + // Try incremental cache hit first + $cachedViolations = $this->cache?->get($relativeFile, $rawContent); + if ($cachedViolations !== null) { + $fileViolations = $cachedViolations; + } else { + // Preprocess templates (Blade, Twig, Vue, JSX, PHP) into scan-ready HTML preserving line numbers + $scanContent = $this->templatePreprocessor->preprocess($rawContent, $file); + + // Scan file content + try { + $fileViolations = $this->scanner->scan($scanContent); + } catch (\Throwable $e) { + // Skip if parsing failed dramatically + continue; + } + + // Enrich line/column locations before caching + foreach ($fileViolations as $violation) { + if (!isset($violation->location['line']) || $violation->location['line'] <= 1) { + $location = $this->elementLocator->locate($rawContent, $violation->htmlSnippet); + $violation->location = [ + 'file' => $relativeFile, + 'line' => $location['line'], + 'column' => $location['column'], + ]; + } else { + $violation->location['file'] = $relativeFile; + } + } + + $this->cache?->put($relativeFile, $rawContent, $fileViolations); } - $relativeFile = $this->makePathRelative($file); - foreach ($fileViolations as $violation) { - // Find line and column number using high-precision locator - if (!isset($violation->location['line']) || $violation->location['line'] <= 1) { - $location = $this->elementLocator->locate($rawContent, $violation->htmlSnippet); - $violation->location = [ + $lineNum = $violation->location['line'] ?? 1; + + // Check inline suppression directives + $suppressionReason = $this->suppressionParser->getSuppressionReason($suppressions, $violation->ruleId, $lineNum); + if ($suppressionReason !== null) { + $this->suppressedAuditLog[] = [ 'file' => $relativeFile, - 'line' => $location['line'], - 'column' => $location['column'], + 'line' => $lineNum, + 'ruleId' => $violation->ruleId, + 'reason' => $suppressionReason, ]; - } else { - $violation->location['file'] = $relativeFile; + continue; } // Check if ignored in baseline @@ -158,6 +195,8 @@ class Analyser } } } + + $this->cache?->save(); return [ 'violations' => $violations, @@ -165,6 +204,16 @@ class Analyser ]; } + /** + * Audit trail of violations suppressed via inline comments during the latest analysis run. + * + * @return array + */ + public function getSuppressedAuditLog(): array + { + return $this->suppressedAuditLog; + } + public function getBaselineManager(): BaselineManager { return $this->baselineManager; @@ -211,7 +260,7 @@ class Analyser $iterator = new RecursiveIteratorIterator($filter, RecursiveIteratorIterator::SELF_FIRST); - $extensions = ['php', 'html', 'twig', 'blade.php']; + $extensions = $this->config->getExtensions(); foreach ($iterator as $file) { /** @var SplFileInfo $file */ diff --git a/src/Core/Config.php b/src/Core/Config.php index ffa6236..34d2bae 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -127,4 +127,54 @@ class Config $key = $this->get('gemini_api_key') ?? $_ENV['GEMINI_API_KEY'] ?? getenv('GEMINI_API_KEY') ?: null; return is_string($key) ? $key : null; } + + public function getPreset(): ?string + { + $preset = $this->get('preset'); + return is_string($preset) && $preset !== '' ? $preset : null; + } + + /** + * Governance policy configuration block from a11y.yaml. + * + * @return array + */ + public function getPolicyConfig(): array + { + $policy = $this->get('policy', []); + if (!is_array($policy)) { + return []; + } + /** @var array $policy */ + return $policy; + } + + /** + * Notification webhook configuration block from a11y.yaml. + * + * @return array + */ + public function getNotificationsConfig(): array + { + $notifications = $this->get('notifications', []); + if (!is_array($notifications)) { + return []; + } + /** @var array $notifications */ + return $notifications; + } + + /** + * File extensions to include during directory scans. + * + * @return array + */ + public function getExtensions(): array + { + $extensions = $this->get('extensions'); + if (is_array($extensions)) { + return array_values(array_filter($extensions, 'is_string')); + } + return ['php', 'html', 'htm', 'xhtml', 'twig', 'blade.php', 'vue', 'jsx', 'tsx', 'latte']; + } } diff --git a/src/Core/Container/ContainerFactory.php b/src/Core/Container/ContainerFactory.php index ee60537..582ed6a 100644 --- a/src/Core/Container/ContainerFactory.php +++ b/src/Core/Container/ContainerFactory.php @@ -7,10 +7,15 @@ use Psr\Container\ContainerInterface; use YakNet\AccessibilityConsole\Core\Config; use YakNet\AccessibilityConsole\Core\Analyser; use YakNet\AccessibilityConsole\Core\Scanner; -use YakNet\AccessibilityConsole\Console\Command\ScanCommand; +use YakNet\AccessibilityConsole\Console\Command\CompareCommand; +use YakNet\AccessibilityConsole\Console\Command\DoctorCommand; +use YakNet\AccessibilityConsole\Console\Command\ExplainCommand; use YakNet\AccessibilityConsole\Console\Command\FixCommand; use YakNet\AccessibilityConsole\Console\Command\InitCommand; +use YakNet\AccessibilityConsole\Console\Command\PresetsCommand; use YakNet\AccessibilityConsole\Console\Command\RulesCommand; +use YakNet\AccessibilityConsole\Console\Command\ScanCommand; +use YakNet\AccessibilityConsole\Console\Command\VpatCommand; use YakNet\AccessibilityConsole\Console\Command\WatchCommand; class ContainerFactory @@ -55,6 +60,21 @@ class ContainerFactory WatchCommand::class => function () { return new WatchCommand(); }, + VpatCommand::class => function () { + return new VpatCommand(); + }, + CompareCommand::class => function () { + return new CompareCommand(); + }, + DoctorCommand::class => function () { + return new DoctorCommand(); + }, + ExplainCommand::class => function () { + return new ExplainCommand(); + }, + PresetsCommand::class => function () { + return new PresetsCommand(); + }, ]); return $builder->build(); diff --git a/src/Core/RuleEngine.php b/src/Core/RuleEngine.php index 407c4ca..d44f3ef 100644 --- a/src/Core/RuleEngine.php +++ b/src/Core/RuleEngine.php @@ -5,6 +5,7 @@ namespace YakNet\AccessibilityConsole\Core; use DOMDocument; use DOMElement; use DOMXPath; +use YakNet\AccessibilityConsole\Rules\RuleExecutionStats; use YakNet\AccessibilityConsole\Rules\RuleInterface; class RuleEngine @@ -12,6 +13,18 @@ class RuleEngine /** @var array */ private array $rules = []; + private ?RuleExecutionStats $stats = null; + + public function setStats(?RuleExecutionStats $stats): void + { + $this->stats = $stats; + } + + public function getStats(): ?RuleExecutionStats + { + return $this->stats; + } + public function addRule(mixed $rule): void { $this->rules[] = $rule; @@ -47,7 +60,12 @@ class RuleEngine // 1. Run Document-level rules foreach ($docRules as $rule) { + $start = $this->stats !== null ? hrtime(true) : 0; $violations = $rule->check($doc); + if ($this->stats !== null) { + $elapsedMs = (hrtime(true) - $start) / 1_000_000; + $this->stats->record($rule->getId(), $elapsedMs, !empty($violations)); + } $allViolations = array_merge($allViolations, $violations); } @@ -63,7 +81,12 @@ class RuleEngine } foreach ($elementRules as $rule) { + $start = $this->stats !== null ? hrtime(true) : 0; $violation = $rule->check($element); + if ($this->stats !== null) { + $elapsedMs = (hrtime(true) - $start) / 1_000_000; + $this->stats->record($rule->getId(), $elapsedMs, $violation !== null); + } if ($violation !== null) { $allViolations[] = $violation; } diff --git a/src/Core/SelfHealing/LocalHealer.php b/src/Core/SelfHealing/LocalHealer.php index fe19347..b893435 100644 --- a/src/Core/SelfHealing/LocalHealer.php +++ b/src/Core/SelfHealing/LocalHealer.php @@ -136,8 +136,182 @@ class LocalHealer return "EXPLANATION: Injected default lang=\"tr\" to HTML element.\nFIX: " . $fixed; } break; + + case 'WCAG_3_2_2_BUTTON_TYPE': + case 'ButtonTypeExplicit': + if (preg_match('/]*\btype=)/i', $snippet)) { + $fixed = preg_replace('/]*\bfocusable=)/i', $snippet)) { + $fixed = preg_replace('/]*\btabindex=["\']-\d+["\']/i', $snippet)) { + $fixed = preg_replace('/\s+tabindex=["\']-\d+["\']/i', '', $snippet) ?: $snippet; + return "EXPLANATION: Removed negative tabindex from visible ', + '', + ], + 'DocumentHasH1' => [ + DocumentHasH1::class, + '

Subtitle only

', + '

Main Title

Subtitle

', + ], + 'InputTypeValidation' => [ + InputTypeValidation::class, + '', + '', + ], + 'FormErrorSummary' => [ + FormErrorSummary::class, + '', + 'Invalid email', + ], + 'CheckboxGroupFieldset' => [ + CheckboxGroupFieldset::class, + '
', + '
Topics
', + ], + 'SelectOptionNotEmpty' => [ + SelectOptionNotEmpty::class, + '', + '', + ], + 'TextareaAccessibleName' => [ + TextareaAccessibleName::class, + '', + '', + ], + 'OutputForValid' => [ + OutputForValid::class, + '0', + '0', + ], + 'ButtonTypeExplicit' => [ + ButtonTypeExplicit::class, + '
', + '
', + ], + 'LinkDownloadContext' => [ + LinkDownloadContext::class, + '
Annual Report', + 'Annual Report (PDF)', + ], + 'ColorContrastAAA' => [ + ColorContrastAAA::class, + '

Medium contrast text

', + '

High contrast text

', + ], + 'FontSizeMinimum' => [ + FontSizeMinimum::class, + '

Tiny legal text

', + '

Readable text

', + ], + 'AllCapsLongText' => [ + AllCapsLongText::class, + '

' . str_repeat('This is a long uppercase paragraph. ', 5) . '

', + '

SHORT BADGE

', + ], + 'JustifiedTextBanned' => [ + JustifiedTextBanned::class, + '

Justified text block

', + '

Aligned text block

', + ], + 'SvgFocusableIeEdge' => [ + SvgFocusableIeEdge::class, + '', + '', + ], + ]; + } + + /** + * @param class-string $ruleClass + */ + #[DataProvider('newRulesProvider')] + public function testRuleDetectsViolationAndPassesCompliantMarkup(string $ruleClass, string $badHtml, string $goodHtml): void + { + $scanner = new Scanner(); + $scanner->addRule(new $ruleClass()); + + $badViolations = $scanner->scan($badHtml); + $this->assertNotEmpty($badViolations, "Expected {$ruleClass} to report violation for bad HTML."); + + $goodViolations = $scanner->scan($goodHtml); + $this->assertEmpty($goodViolations, "Expected {$ruleClass} to report 0 violations for compliant HTML."); + } +} diff --git a/tests/V4SymmetryModulesTest.php b/tests/V4SymmetryModulesTest.php new file mode 100644 index 0000000..6c5639b --- /dev/null +++ b/tests/V4SymmetryModulesTest.php @@ -0,0 +1,74 @@ +'); + + try { + $scanner = new Scanner(); + $scanner->addRule(new ImgAltText()); + + // First run: cache miss & populate + $cache1 = new ScanCache($cacheFile, 'sig-v1'); + $analyser1 = new Analyser(new Config(), $scanner, new BaselineManager(), null, null, null, $cache1); + $res1 = $analyser1->analyse([$htmlFile]); + $this->assertCount(1, $res1['violations']); + $this->assertSame(0, $cache1->getStats()['hits']); + $this->assertSame(1, $cache1->getStats()['misses']); + + // Second run: cache hit! + $cache2 = new ScanCache($cacheFile, 'sig-v1'); + $cache2->load(); + $analyser2 = new Analyser(new Config(), $scanner, new BaselineManager(), null, null, null, $cache2); + $res2 = $analyser2->analyse([$htmlFile]); + $this->assertCount(1, $res2['violations']); + $this->assertSame(1, $cache2->getStats()['hits']); + $this->assertSame(100.0, $cache2->getStats()['hit_rate']); + } finally { + @unlink($cacheFile); + @unlink($htmlFile); + } + } + + public function testCiWorkflowGeneratorSupportsAllFourPlatforms(): void + { + $generator = new CiWorkflowGenerator(); + + foreach (CiWorkflowGenerator::getSupportedPlatforms() as $platform) { + $yaml = $generator->generate($platform, 'wcag22-aa', 95, 'templates'); + $this->assertStringContainsString('vendor/bin/a11y', $yaml); + $this->assertStringContainsString('--preset=wcag22-aa', $yaml); + $this->assertNotEmpty(CiWorkflowGenerator::getDefaultPath($platform)); + } + } + + public function testAccessibilityAssertionsTraitValidatesCleanHtml(): void + { + $cleanHtml = 'YakNet

Welcome

Accessible page.

'; + + $this->assertHtmlAccessible($cleanHtml, level: 4); + $this->assertAccessibilityScoreAtLeast($cleanHtml, minScore: 95, level: 4); + $this->assertMeetsAccessibilityPreset($cleanHtml, 'wcag22-aa'); + $this->assertNoAccessibilityRuleViolation($cleanHtml, 'WCAG_1_1_1_ALT'); + } +}