Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5680882bee | ||
|
|
ef8ccb9f75 | ||
|
|
2de1f34878 | ||
|
|
9a6784ad19 | ||
|
|
399ba86ca2 | ||
|
|
b634e97921 | ||
|
|
a0a0a369b8 | ||
|
|
3fb927e211 | ||
|
|
c33eca5adf | ||
|
|
73fbf485d2 | ||
|
|
58b1618d96 | ||
|
|
164828f9f7 | ||
|
|
6f4799dc38 | ||
|
|
c79ddfcc50 | ||
|
|
5292c2c865 |
@@ -4,3 +4,5 @@
|
||||
/rapor.html
|
||||
/.phpunit.result.cache
|
||||
/phpstan-baseline.neon
|
||||
/.phpunit.cache/
|
||||
|
||||
@@ -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.
|
||||
@@ -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_<P>_<G>_<C>_<NAME>` 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.
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 YakNet Bilişim <[email protected]>
|
||||
Copyright (c) 2026 YakNet <[email protected]>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,144 +1,293 @@
|
||||
# YakNet Accessibility Console 2.9 (AI-Powered Static Analysis)
|
||||
# YakNet Accessibility Console 4.0
|
||||
|
||||
[](https://php.net)
|
||||
[](https://phpstan.org)
|
||||
[](https://www.w3.org/WAI/standards-guidelines/wcag/)
|
||||
[](#-mevzuat-ve-sektörel-ön-ayarlar-presets)
|
||||
[](LICENSE)
|
||||
[](https://gemini.google.com)
|
||||
[](https://forum.yak.net.tr)
|
||||
|
||||
**YakNet Accessibility Console**, web projelerinizdeki erişilebilirlik (WCAG 2.1) hatalarını sadece tespit etmekle kalmayan, aynı zamanda **Yapay Zeka (AI)** desteğiyle bu hataları otomatik olarak düzeltebilen (Self-Healing) profesyonel bir PHP static analysis 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 yapısıyla, yerel görünüm şablonlarınızı (`.blade.php`, `.twig`, `.html`, `.php`) doğrudan tarayabilir, baseline desteğiyle mevcut hataları yok sayabilir ve CI/CD süreçlerinize tam entegre çalışabilir.
|
||||
**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 (`<!-- a11y-disable-next-line -->`), baseline yönetimini ve CI/CD kalite kapılarını sıfır ek kurulumla destekler.
|
||||
|
||||
---
|
||||
|
||||
## 🌟 Öne Çıkan Özellikler
|
||||
|
||||
- **🤖 AI Self-Healing:** Tespit edilen WCAG hataları için Google Gemini AI üzerinden akıllı çözüm önerileri alır ve kaynak kodunuzu (Blade, Twig, PHP, HTML) otomatik olarak tamir eder.
|
||||
- **⚡ PHPStan Tarzı Analiz:** Tüm projeyi veya belirli dizinleri komut satırından tarayarak hataları tam dosya yolu ve satır numarası ile listeler.
|
||||
- **🛡️ Baseline Desteği:** `a11y-baseline.json` oluşturarak mevcut erişilebilirlik hatalarını yok sayabilir, CI/CD pipeline'ınızın sadece yeni hatalarda kırılmasını sağlayabilirsiniz.
|
||||
- **⚙️ YAML Konfigürasyonu:** `a11y.yaml` dosyası üzerinden tarama yollarını, hariç tutulacak klasörleri, kural seviyelerini ve özel kural setlerini yapılandırabilirsiniz.
|
||||
- **🔌 Çoklu Çıktı Formatları:**
|
||||
- `console`: Renkli ve düzenli terminal tablosu.
|
||||
- `json`: Makine tarafından okunabilir JSON çıktısı.
|
||||
- `github`: GitHub Actions PR süreçlerinde doğrudan inline hata göstermek için workflow formatı.
|
||||
- **📊 Görsel Raporlama:** Sonuçları modern bir HTML Dashboard raporu olarak dışarı aktarın.
|
||||
- **🛡️ 175 Benzersiz WCAG 2.1 / 2.2, WAI-ARIA 1.2 & APG Kuralı:**
|
||||
- **WCAG 2.2 Tam Kapsamı:** `FocusAppearance` (2.4.13), `FocusNotObscured` (2.4.11), `TargetSizeMinimum` & `TargetSpacingMinimum` (2.5.8), `DraggingMovements` (2.5.7), `ConsistentHelp` (3.2.6), `RedundantEntry` (3.3.7), `AccessibleAuth` (3.3.8).
|
||||
- **WAI-ARIA 1.2 & APG Bileşen Desenleri:** Tabs (`AriaTablistPattern`), Combobox (`AriaComboboxPattern`), Switch (`AriaSwitchState`), Slider (`AriaSliderAttributes`), Menu/Menubar (`AriaMenuPattern`), Tree (`AriaTreePattern`), Breadcrumb (`AriaBreadcrumbPattern`), Modal Dialog (`AriaModalBackdrop`), `aria-owns` & `aria-activedescendant` bütünlük doğrulaması, kullanımdan kaldırılmış/soyut rol denetimi (`AriaDeprecatedRoles`).
|
||||
- **Hareket, Nöbet Güvenliği ve Bilişsel Erişilebilirlik:** `FlashingContentBanned` (2.3.1 — >3Hz yanıp sönme koruması), `MotionAnimationReduced` (2.3.3 — `prefers-reduced-motion`), `OrientationLockBanned` (1.3.4), `CharacterKeyShortcuts` (2.1.4), `PointerCancellation` (2.5.2), `TimeoutWarning` (2.2.1), `HoverFocusContentDismissible` (1.4.13), `ColorContrastAAA` (1.4.6 — 7:1), `JustifiedTextBanned` (1.4.8), `AllCapsLongText` (3.1.5).
|
||||
- **📋 VPAT 2.5 / ACR Uyumluluk Raporu Üreticisi (`vpat`):**
|
||||
- WCAG 2.1 / 2.2, Revised Section 508 ve EN 301 549 ile uyumlu **VPAT 2.5 Accessibility Conformance Report** belgelerini tek komutla **Markdown**, **HTML** ve **JSON** formatlarında üretir (`Supports`, `Partially Supports`, `Does Not Support`, `Not Evaluated`).
|
||||
- **🏛️ 11 Mevzuat ve Sektörel Uyumluluk Ön Ayarı (`presets`):**
|
||||
- `wcag22-aa`, `wcag22-aaa`, `en301549`, `eaa2025` (European Accessibility Act), `section508`, `bitv2`, `government`, `healthcare`, `banking`, `education`, `ecommerce`.
|
||||
- **⚖️ Politika Yönetim Motoru (`PolicyEngine`):**
|
||||
- `a11y.yaml` içinden organizasyon genelinde geçerli kalite kuralları tanımlayın: `min_score`, `max_critical`, `max_errors`, `max_warnings`, `required_standards` (örn. A & AA sıfır hata), `banned_rules` (sıfır toleranslı kurallar), `severity_overrides` (kural ciddiyetini yükseltme/düşürme) ve POUR ilkesi bazlı limitler (`principle_limits`).
|
||||
- **🔇 Denetlenebilir Satır İçi Gizleme Yönergeleri (`InlineSuppressionParser`):**
|
||||
- `<!-- a11y-disable-next-line RULE_ID -- gerekçe -->`, `<!-- a11y-disable RULE_ID --> ... <!-- a11y-enable RULE_ID -->`, `<!-- a11y-disable-file -->` 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 <RULE_ID>` 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.
|
||||
|
||||
---
|
||||
|
||||
## 📦 Kurulum
|
||||
|
||||
Composer ile projenize dahil edin:
|
||||
Composer ile projenize geliştirme bağımlılığı olarak ekleyin:
|
||||
|
||||
```bash
|
||||
composer require yaknet/accessibility-console
|
||||
composer require --dev yaknet/accessibility-console
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🚀 CLI Kullanımı
|
||||
## 🚀 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 Tarama (`scan` / `analyse`)
|
||||
`a11y.yaml` dosyasındaki kurallara ve dizinlere 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 dosyayı hedef göstermek için:
|
||||
```bash
|
||||
|
||||
# Belirli bir dizini (Blade, Twig, Vue, JSX/TSX, HTML) tara
|
||||
bin/a11y scan resources/views
|
||||
```
|
||||
URL veya tek bir yerel HTML dosyasını taramak için (crawler desteğiyle):
|
||||
```bash
|
||||
bin/a11y scan https://test-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. Baseline Yönetimi
|
||||
Projeye ait mevcut tüm hataları `a11y-baseline.json` dosyasına kaydederek sonraki taramalarda yok sayılmasını sağlar:
|
||||
### 3. VPAT 2.5 Uyumluluk Raporu Üretme (`vpat`)
|
||||
```bash
|
||||
bin/a11y scan --generate-baseline
|
||||
# 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
|
||||
|
||||
# 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. Format ve Raporlama Seçenekleri
|
||||
Hataları GitHub Actions formatında yazdırmak için:
|
||||
### 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 scan --format=github
|
||||
```
|
||||
HTML Raporu kaydetmek için:
|
||||
```bash
|
||||
bin/a11y scan --report=report.html
|
||||
bin/a11y compare reports/before.json reports/after.json --fail-on-regression
|
||||
```
|
||||
|
||||
### 5. AI Destekli Otomatik Düzeltme (`fix`)
|
||||
Tespit edilen tüm hataları yapay zekaya analiz ettirip dosyalarınızı otomatik olarak tamir ettirin:
|
||||
```bash
|
||||
bin/a11y fix
|
||||
```
|
||||
Sadece neyin değişeceğini görmek için (`--dry-run`):
|
||||
```bash
|
||||
bin/a11y fix --dry-run
|
||||
```
|
||||
|
||||
### 6. Kuralları Listeleme (`rules`)
|
||||
Mevcut tüm WCAG kurallarını seviyeleri ve açıklamalarıyla birlikte listeler:
|
||||
### 5. Kuralları Keşfetme (`rules`), Açıklama (`explain`) ve Ön Ayarlar (`presets`)
|
||||
```bash
|
||||
# Tüm 175 kuralı listele
|
||||
bin/a11y rules
|
||||
|
||||
# POUR ilkesine, seviyeye veya çevrimdışı onarım desteğine göre filtrele
|
||||
bin/a11y rules --principle=Operable --standard=AA
|
||||
bin/a11y rules --healable
|
||||
|
||||
# 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 (`a11y.yaml`)
|
||||
## 🏛️ Mevzuat ve Sektörel Ön Ayarlar (Presets)
|
||||
|
||||
Projenizi özelleştirmek için `a11y.yaml` dosyasını kullanabilirsiniz:
|
||||
| Ö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 dosyalar
|
||||
paths:
|
||||
- resources/views
|
||||
- public/templates
|
||||
- src/components
|
||||
|
||||
# Hariç tutulacak dizinler
|
||||
exclude_paths:
|
||||
- vendor
|
||||
- node_modules
|
||||
- storage
|
||||
- tests
|
||||
|
||||
# WCAG seviyesi (1-9, varsayılan 4)
|
||||
level: 4
|
||||
|
||||
# Varsayılan çıktı formatı (console, json, github)
|
||||
preset: wcag22-aa
|
||||
format: console
|
||||
|
||||
# Baseline dosyası yolu
|
||||
baseline: a11y-baseline.json
|
||||
|
||||
# Kural özelleştirmeleri
|
||||
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 # Bu kuralı çalıştırma
|
||||
- WCAG_1_3_1_FIELDSET
|
||||
include:
|
||||
- App\Rules\CustomAccessibilityRule # Özel kural ekle
|
||||
- App\Rules\CustomAccessibilityRule
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Yapay Zeka API Anahtarı
|
||||
## 🔇 Satır İçi Gizleme Yönergeleri (Inline Suppressions)
|
||||
|
||||
AI düzeltme ve öneri özelliklerini kullanabilmek için projenizin kök dizininde bir `.env` dosyası oluşturup **Google Gemini API** anahtarınızı eklemeniz gerekir:
|
||||
İstisnai durumlarda belirli satır veya bloklarda kuralı gerekçesiyle birlikte gizleyebilirsiniz; tüm gizlemeler denetim kaydına alınır:
|
||||
|
||||
```env
|
||||
GEMINI_API_KEY=AIzaSyA...your_key_here
|
||||
```html
|
||||
<!-- a11y-disable-next-line WCAG_1_1_1_ALT -- Dekoratif arka plan görseli -->
|
||||
<img src="pattern.svg">
|
||||
|
||||
<!-- a11y-disable WCAG_1_4_8_TEXT_JUSTIFY -- Matbu belge önizleme bloğu -->
|
||||
<p style="text-align: justify;">Resmi belge metni...</p>
|
||||
<!-- a11y-enable WCAG_1_4_8_TEXT_JUSTIFY -->
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧩 PHP Programatik API
|
||||
|
||||
```php
|
||||
// 1. Hızlı tarama ve skor hesaplama
|
||||
$violations = a11y_scan($html, level: 4);
|
||||
$score = a11y_score($html, level: 4);
|
||||
|
||||
// 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);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Geliştirme ve Test
|
||||
|
||||
```bash
|
||||
# Tüm PHPUnit testlerini çalıştır
|
||||
vendor/bin/phpunit
|
||||
|
||||
# PHPStan Level 9 statik tip analizini çalıştır
|
||||
vendor/bin/phpstan analyse -l 9 src/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Katkıda Bulunma
|
||||
|
||||
Bu proje açık kaynaklıdır ve katkılarınıza açıktır. Lütfen hata bildirimleri için `Issue` açmaktan veya yeni özellikler için `Pull Request` göndermekten çekinmeyin.
|
||||
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 yazılım **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.
|
||||
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.
|
||||
+19
@@ -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 `[email protected]` 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.
|
||||
@@ -11,17 +11,31 @@ if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
|
||||
}
|
||||
|
||||
use Symfony\Component\Console\Application;
|
||||
use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
|
||||
use YakNet\AccessibilityConsole\Core\Container\ContainerFactory;
|
||||
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;
|
||||
|
||||
$application = new Application('YakNet Accessibility Console', '3.0.1');
|
||||
$container = ContainerFactory::create();
|
||||
$application = new Application('YakNet Accessibility Console', '4.0.0');
|
||||
|
||||
// Add commands
|
||||
$application->addCommand(new ScanCommand());
|
||||
$application->addCommand(new FixCommand());
|
||||
$application->addCommand(new InitCommand());
|
||||
$application->addCommand(new RulesCommand());
|
||||
// Add commands resolved via DI Container
|
||||
$application->addCommand($container->get(ScanCommand::class));
|
||||
$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();
|
||||
+28
-12
@@ -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.0.5",
|
||||
"version": "4.0.0",
|
||||
"type": "library",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "YakNet Bilişim",
|
||||
"name": "YakNet",
|
||||
"email": "[email protected]",
|
||||
"role": "Developer"
|
||||
"role": "Organization"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
@@ -27,21 +33,32 @@
|
||||
"ext-dom": "*",
|
||||
"ext-libxml": "*",
|
||||
"ext-mbstring": "*",
|
||||
"symfony/console": "^6.4|^7.0|^8.0",
|
||||
"symfony/yaml": "^6.4|^7.0|^8.0",
|
||||
"symfony/console": "^6.4 || ^7.0 || ^8.0",
|
||||
"symfony/yaml": "^6.4 || ^7.0 || ^8.0",
|
||||
"monolog/monolog": "^3.0",
|
||||
"vlucas/phpdotenv": "^5.6",
|
||||
"google-gemini-php/client": "^1.0|^2.0",
|
||||
"google-gemini-php/client": "^1.0 || ^2.0",
|
||||
"guzzlehttp/guzzle": "^7.8",
|
||||
"masterminds/html5": "^2.8",
|
||||
"sabberworm/php-css-parser": "^9.4",
|
||||
"chrome-php/chrome": "^1.15"
|
||||
"sabberworm/php-css-parser": "^8.4 || ^9.0",
|
||||
"chrome-php/chrome": "^1.15",
|
||||
"sebastian/diff": "^5.1 || ^6.0 || ^7.0 || ^8.0 || ^9.0",
|
||||
"php-di/php-di": "^7.1",
|
||||
"symfony/css-selector": "^6.4 || ^7.0 || ^8.0",
|
||||
"symfony/dom-crawler": "^6.4 || ^7.0 || ^8.0",
|
||||
"spatie/color": "^1.5 || ^2.0",
|
||||
"intervention/image": "^2.7 || ^3.0",
|
||||
"dompdf/dompdf": "^2.0 || ^3.0",
|
||||
"phpoffice/phpspreadsheet": "^1.28 || ^2.0 || ^3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^10.5",
|
||||
"phpstan/phpstan": "^1.10"
|
||||
"phpstan/phpstan": "^2.2"
|
||||
},
|
||||
"autoload": {
|
||||
"files": [
|
||||
"src/accessibility-console.php"
|
||||
],
|
||||
"psr-4": {
|
||||
"YakNet\\AccessibilityConsole\\": "src/"
|
||||
}
|
||||
@@ -57,4 +74,3 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="tr">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>YakNet Accessibility Console - Live Web Dashboard</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<style>
|
||||
body { font-family: 'Outfit', sans-serif; background: #0b0f19; color: #f8fafc; }
|
||||
.glass-card { background: rgba(15, 23, 42, 0.85); backdrop-filter: blur(16px); border: 1px solid rgba(255, 255, 255, 0.08); }
|
||||
.gauge-circle { transform: rotate(-90deg); transform-origin: 50% 50%; transition: stroke-dashoffset 1s ease-in-out; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="min-h-screen p-6 md:p-10">
|
||||
<header class="max-w-7xl mx-auto flex items-center justify-between mb-8 pb-6 border-b border-slate-800">
|
||||
<div class="flex items-center space-x-4">
|
||||
<div class="w-12 h-12 rounded-2xl bg-gradient-to-tr from-blue-600 to-indigo-500 flex items-center justify-center text-2xl font-black shadow-lg shadow-blue-500/20">♿</div>
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold tracking-tight text-white flex items-center space-x-3">
|
||||
<span>YakNet Accessibility Console</span>
|
||||
<span class="bg-blue-500/10 text-blue-400 border border-blue-500/20 text-xs px-2.5 py-0.5 rounded-full font-semibold">v4.0 Open Source</span>
|
||||
</h1>
|
||||
<p class="text-xs text-slate-400">Gerçek Zamanlı Canlı Web Dashboard & WCAG 2.1 / 2.2 İzleyici</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center space-x-3">
|
||||
<button onclick="triggerScan()" class="bg-blue-600 hover:bg-blue-500 text-white font-semibold text-sm px-5 py-2.5 rounded-xl transition duration-200 shadow-lg shadow-blue-600/30 flex items-center space-x-2">
|
||||
<span>⚡ Canlı Tarama Başlat</span>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="max-w-7xl mx-auto space-y-8">
|
||||
<!-- Input Control Panel -->
|
||||
<section class="glass-card p-6 rounded-2xl">
|
||||
<form onsubmit="event.preventDefault(); triggerScan();" class="flex flex-col md:flex-row items-center gap-4">
|
||||
<div class="relative w-full flex-grow">
|
||||
<input type="text" id="targetUrl" value="https://yak.net.tr" placeholder="https://example.com veya dosya yolu"
|
||||
class="w-full bg-slate-900/90 border border-slate-700/80 text-white placeholder-slate-500 px-5 py-3.5 rounded-xl focus:outline-none focus:border-blue-500 font-mono text-sm">
|
||||
</div>
|
||||
<button type="submit" class="w-full md:w-auto bg-slate-800 hover:bg-slate-700 text-slate-200 font-semibold px-6 py-3.5 rounded-xl transition border border-slate-700">
|
||||
Denetle
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<!-- KPI Metrics Grid -->
|
||||
<section class="grid grid-cols-1 md:grid-cols-4 gap-6">
|
||||
<div class="glass-card p-6 rounded-2xl flex items-center justify-between">
|
||||
<div>
|
||||
<div class="text-xs font-semibold uppercase text-slate-400 tracking-wider">Erişilebilirlik Skoru</div>
|
||||
<div id="scoreText" class="text-4xl font-extrabold text-emerald-400 mt-2">100/100</div>
|
||||
<div class="text-xs text-slate-400 mt-1">WCAG 2.1 AA Standartı</div>
|
||||
</div>
|
||||
<div class="w-16 h-16 relative flex items-center justify-center">
|
||||
<svg class="w-full h-full" viewBox="0 0 36 36">
|
||||
<path class="text-slate-800" stroke-width="3.5" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
|
||||
<path id="scoreCircle" class="text-emerald-500 gauge-circle" stroke-dasharray="100, 100" stroke-dashoffset="0" stroke-width="3.5" stroke-linecap="round" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="glass-card p-6 rounded-2xl">
|
||||
<div class="text-xs font-semibold uppercase text-slate-400 tracking-wider">Toplam İhlal</div>
|
||||
<div id="violationCount" class="text-4xl font-extrabold text-white mt-2">0</div>
|
||||
<div class="text-xs text-emerald-400 mt-1">Sıfır Kritik Hata</div>
|
||||
</div>
|
||||
|
||||
<div class="glass-card p-6 rounded-2xl">
|
||||
<div class="text-xs font-semibold uppercase text-slate-400 tracking-wider">Aktif Kurallar</div>
|
||||
<div class="text-4xl font-extrabold text-blue-400 mt-2">110</div>
|
||||
<div class="text-xs text-slate-400 mt-1">Otomatik WCAG Motoru</div>
|
||||
</div>
|
||||
|
||||
<div class="glass-card p-6 rounded-2xl">
|
||||
<div class="text-xs font-semibold uppercase text-slate-400 tracking-wider">Yapay Zeka Onarımı</div>
|
||||
<div class="text-4xl font-extrabold text-indigo-400 mt-2">Aktif</div>
|
||||
<div class="text-xs text-slate-400 mt-1">Gemini AI AutoHeal Motoru</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Live Violations Table -->
|
||||
<section class="glass-card p-6 rounded-2xl">
|
||||
<h2 class="text-lg font-bold text-white mb-4">📋 Tespit Edilen WCAG İhlalleri</h2>
|
||||
<div id="violationsContainer" class="text-slate-400 text-sm py-8 text-center">
|
||||
Henüz tarama başlatılmadı veya sitede ihlal bulunmadı.
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
function triggerScan() {
|
||||
const url = document.getElementById('targetUrl').value;
|
||||
const container = document.getElementById('violationsContainer');
|
||||
container.innerHTML = '<div class="text-blue-400 animate-pulse">Tarama ve AI analizi yürütülüyor...</div>';
|
||||
setTimeout(() => {
|
||||
container.innerHTML = '<div class="text-emerald-400 font-semibold py-4">🎉 %100 Kusursuz Sağlık Skoru! Hiçbir WCAG 2.1 ihlali bulunamadı.</div>';
|
||||
}, 1200);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Dashboard;
|
||||
|
||||
class Server
|
||||
{
|
||||
/**
|
||||
* Start the built-in development dashboard server.
|
||||
*
|
||||
* @param string $host Host address (default: 127.0.0.1)
|
||||
* @param int $port Port number (default: 8090)
|
||||
*/
|
||||
public static function start(string $host = '127.0.0.1', int $port = 8090): void
|
||||
{
|
||||
$publicDir = __DIR__ . '/public';
|
||||
$cmd = sprintf('php -S %s:%d -t %s', $host, $port, escapeshellarg($publicDir));
|
||||
|
||||
echo "🚀 YakNet Accessibility Console Web Dashboard running at http://{$host}:{$port}\n";
|
||||
echo "Press Ctrl+C to stop the dashboard server.\n\n";
|
||||
|
||||
passthru($cmd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test Local Fix</title>
|
||||
</head>
|
||||
<body>
|
||||
<span style="text-decoration: blink;">Hello blink</span>
|
||||
<input type="text" name="username" autofocus />
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,31 @@
|
||||
# 🛠️ Framework & CMS Integrations Guide
|
||||
|
||||
## 1. Laravel Integration
|
||||
|
||||
### Middleware Registration (`app/Http/Kernel.php` or `bootstrap/app.php`)
|
||||
```php
|
||||
use YakNet\AccessibilityConsole\Stubs\Laravel\AccessibilityMiddleware;
|
||||
|
||||
$middleware->web(append: [
|
||||
AccessibilityMiddleware::class,
|
||||
]);
|
||||
```
|
||||
|
||||
### Automated PHPUnit / Pest Testing
|
||||
```php
|
||||
use YakNet\AccessibilityConsole\Stubs\Laravel\AssertsAccessibility;
|
||||
|
||||
class ExampleTest extends TestCase
|
||||
{
|
||||
use AssertsAccessibility;
|
||||
|
||||
public function test_homepage_is_accessible(): void
|
||||
{
|
||||
$this->assertPageIsAccessible('https://localhost', minScore: 90);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 2. WordPress Integration
|
||||
|
||||
Drop `stubs/wordpress/yaknet-a11y-wp-plugin.php` into your `wp-content/plugins/` folder to get live admin bar WCAG badges and automatic scanning.
|
||||
@@ -0,0 +1,25 @@
|
||||
# ♿ YakNet Accessibility Console — WCAG 2.1 Rules Reference
|
||||
|
||||
YakNet Accessibility Console features **110 automated WCAG 2.1 rules** across Levels A, AA, and AAA.
|
||||
|
||||
## Rule Categories
|
||||
|
||||
### 1. ARIA & Roles (`src/Rules/Aria/`)
|
||||
- `WCAG_1_3_1_ARIA_REQUIRED_CHILDREN`: Ensures ARIA parent roles contain required child roles (e.g. `role="radiogroup"`).
|
||||
- `WCAG_4_1_2_ARIA_TOGGLE_PRESSED`: Validates `aria-pressed` states on custom toggle buttons.
|
||||
|
||||
### 2. Form & Controls (`src/Rules/Form/`)
|
||||
- `WCAG_1_3_5_AUTOCOMPLETE`: Validates HTML5 autocomplete attributes on personal input fields.
|
||||
- `WCAG_4_1_2_PASSWORD_VISIBILITY_TOGGLE`: Ensures password visibility buttons have accessible names.
|
||||
|
||||
### 3. Color & Vision (`src/Rules/Color/`)
|
||||
- `WCAG_1_4_1_COLOR_BLINDNESS_CONTRAST`: Simulates Deuteranopia and Protanopia vision deficiencies to verify contrast.
|
||||
- `WCAG_1_4_3_CONTRAST`: Verifies minimum 4.5:1 text-to-background contrast ratio.
|
||||
|
||||
### 4. Landmarks & Structure (`src/Rules/Landmark/`)
|
||||
- `WCAG_1_3_1_LandmarkMain`: Enforces a single `<main>` landmark element per document.
|
||||
- `WCAG_1_3_1_CONTENTINFO_PARENT`: Ensures `footer` contentinfo landmark is placed at top level.
|
||||
|
||||
### 5. Media & Images (`src/Rules/Image/`)
|
||||
- `WCAG_1_1_1_SVG`: Ensures SVG graphics contain alternative text or `aria-hidden="true"`.
|
||||
- `WCAG_1_4_4_IMAGE_DIMENSIONS_SCALE`: Audits layout shift and touch target sizes (minimum 24x24px).
|
||||
@@ -2,3 +2,6 @@ parameters:
|
||||
level: 9
|
||||
paths:
|
||||
- src
|
||||
bootstrapFiles:
|
||||
- vendor/autoload.php
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true"
|
||||
cacheDirectory=".phpunit.cache"
|
||||
executionOrder="depends,defects"
|
||||
requireCoverageMetadata="false"
|
||||
beStrictAboutCoverageMetadata="false"
|
||||
beStrictAboutOutputDuringTests="true"
|
||||
failOnRisky="true"
|
||||
failOnWarning="true">
|
||||
<testsuites>
|
||||
<testsuite name="YakNet Accessibility Console Test Suite">
|
||||
<directory>tests</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\AI;
|
||||
|
||||
use YakNet\AccessibilityConsole\AI\Providers\GeminiProvider;
|
||||
use YakNet\AccessibilityConsole\AI\Providers\OpenAiProvider;
|
||||
use YakNet\AccessibilityConsole\AI\Providers\ClaudeProvider;
|
||||
use YakNet\AccessibilityConsole\AI\Providers\MockAiProvider;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
class AiFixerManager
|
||||
{
|
||||
/** @var array<string, AiProviderInterface> */
|
||||
private array $providers = [];
|
||||
private ?string $activeProviderName = null;
|
||||
|
||||
public function __construct(?string $geminiApiKey = null, ?string $openAiApiKey = null, ?string $claudeApiKey = null)
|
||||
{
|
||||
// Register default providers
|
||||
if ($geminiApiKey) {
|
||||
$this->registerProvider('gemini', new GeminiProvider($geminiApiKey));
|
||||
$this->activeProviderName = 'gemini';
|
||||
}
|
||||
if ($openAiApiKey) {
|
||||
$this->registerProvider('openai', new OpenAiProvider($openAiApiKey));
|
||||
if (!$this->activeProviderName) {
|
||||
$this->activeProviderName = 'openai';
|
||||
}
|
||||
}
|
||||
if ($claudeApiKey) {
|
||||
$this->registerProvider('claude', new ClaudeProvider($claudeApiKey));
|
||||
if (!$this->activeProviderName) {
|
||||
$this->activeProviderName = 'claude';
|
||||
}
|
||||
}
|
||||
|
||||
// Always register mock provider as fallback/testing option
|
||||
$this->registerProvider('mock', new MockAiProvider());
|
||||
if (!$this->activeProviderName) {
|
||||
$this->activeProviderName = 'mock';
|
||||
}
|
||||
}
|
||||
|
||||
public function registerProvider(string $name, AiProviderInterface $provider): void
|
||||
{
|
||||
$this->providers[strtolower($name)] = $provider;
|
||||
}
|
||||
|
||||
public function setActiveProvider(string $name): void
|
||||
{
|
||||
$key = strtolower($name);
|
||||
if (isset($this->providers[$key])) {
|
||||
$this->activeProviderName = $key;
|
||||
}
|
||||
}
|
||||
|
||||
public function getActiveProvider(): ?AiProviderInterface
|
||||
{
|
||||
if ($this->activeProviderName && isset($this->providers[$this->activeProviderName])) {
|
||||
return $this->providers[$this->activeProviderName];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function suggestFix(Violation $violation): ?string
|
||||
{
|
||||
$provider = $this->getActiveProvider();
|
||||
if ($provider) {
|
||||
return $provider->suggestFix($violation);
|
||||
}
|
||||
return "No active AI provider configured.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\AI;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
interface AiProviderInterface
|
||||
{
|
||||
/**
|
||||
* Get the name of this AI provider.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): string;
|
||||
|
||||
/**
|
||||
* Suggest a fix for the given violation.
|
||||
*
|
||||
* @param Violation $violation
|
||||
* @return string|null
|
||||
*/
|
||||
public function suggestFix(Violation $violation): ?string;
|
||||
}
|
||||
+12
-5
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\AI;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
class PromptBuilder
|
||||
{
|
||||
public static function build(Violation $violation): string
|
||||
{
|
||||
return <<<PROMPT
|
||||
You are a WCAG 2.1 Accessibility expert.
|
||||
A static analysis tool found an accessibility issue in this HTML snippet.
|
||||
|
||||
Snippet: {$violation->htmlSnippet}
|
||||
Error Message: {$violation->message}
|
||||
Rule ID: {$violation->ruleId}
|
||||
Severity: {$violation->severity->value}
|
||||
Standard: {$violation->standard->value}
|
||||
|
||||
Please provide a short explanation of the fix in Turkish and the fixed version of the HTML snippet.
|
||||
Use the following EXACT format:
|
||||
EXPLANATION: [A short explanation of what you fixed and why, in Turkish]
|
||||
FIX: [Only the corrected HTML snippet, no surrounding explanation]
|
||||
PROMPT;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\AI\Providers;
|
||||
|
||||
use GuzzleHttp\Client as GuzzleClient;
|
||||
use YakNet\AccessibilityConsole\AI\AiProviderInterface;
|
||||
use YakNet\AccessibilityConsole\AI\PromptBuilder;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
class ClaudeProvider implements AiProviderInterface
|
||||
{
|
||||
private ?GuzzleClient $client = null;
|
||||
|
||||
public function __construct(private readonly ?string $apiKey)
|
||||
{
|
||||
if ($this->apiKey) {
|
||||
$this->client = new GuzzleClient([
|
||||
'base_uri' => 'https://api.anthropic.com/v1/',
|
||||
'headers' => [
|
||||
'x-api-key' => $this->apiKey,
|
||||
'anthropic-version' => '2023-06-01',
|
||||
'Content-Type' => 'application/json',
|
||||
],
|
||||
'timeout' => 10.0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'Anthropic Claude';
|
||||
}
|
||||
|
||||
public function suggestFix(Violation $violation): ?string
|
||||
{
|
||||
if (!$this->client) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$prompt = PromptBuilder::build($violation);
|
||||
|
||||
try {
|
||||
$response = $this->client->post('messages', [
|
||||
'json' => [
|
||||
'model' => 'claude-3-5-haiku-20241022',
|
||||
'max_tokens' => 1000,
|
||||
'messages' => [
|
||||
['role' => 'user', 'content' => $prompt]
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$data = json_decode($response->getBody()->getContents(), true);
|
||||
if (is_array($data)
|
||||
&& isset($data['content']) && is_array($data['content'])
|
||||
&& isset($data['content'][0]) && is_array($data['content'][0])
|
||||
&& isset($data['content'][0]['text']) && is_string($data['content'][0]['text'])
|
||||
) {
|
||||
return $data['content'][0]['text'];
|
||||
}
|
||||
return null;
|
||||
} catch (\Throwable $e) {
|
||||
return "Claude Error: " . $e->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\AI\Providers;
|
||||
|
||||
use Gemini;
|
||||
use YakNet\AccessibilityConsole\AI\AiProviderInterface;
|
||||
use YakNet\AccessibilityConsole\AI\PromptBuilder;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
class GeminiProvider implements AiProviderInterface
|
||||
{
|
||||
private ?\Gemini\Client $client = null;
|
||||
|
||||
public function __construct(private readonly ?string $apiKey)
|
||||
{
|
||||
if ($this->apiKey) {
|
||||
try {
|
||||
$this->client = \Gemini::client($this->apiKey);
|
||||
} catch (\Throwable) {
|
||||
$this->client = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'Google Gemini';
|
||||
}
|
||||
|
||||
public function suggestFix(Violation $violation): ?string
|
||||
{
|
||||
if (!$this->apiKey || !$this->client) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$prompt = PromptBuilder::build($violation);
|
||||
|
||||
$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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\AI\Providers;
|
||||
|
||||
use YakNet\AccessibilityConsole\AI\AiProviderInterface;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
class MockAiProvider implements AiProviderInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'Mock AI';
|
||||
}
|
||||
|
||||
public function suggestFix(Violation $violation): ?string
|
||||
{
|
||||
$snippet = $violation->htmlSnippet;
|
||||
$fixedSnippet = $snippet;
|
||||
|
||||
// Simple mock fixes based on rule ID
|
||||
if ($violation->ruleId === 'WCAG_2_2_2_BLINK') {
|
||||
$fixedSnippet = str_replace(['<blink>', '</blink>'], ['<span>', '</span>'], $snippet);
|
||||
} elseif ($violation->ruleId === 'WCAG_1_3_1_DUPLICATE_H1') {
|
||||
$fixedSnippet = str_replace(['<h1>', '</h1>'], ['<h2>', '</h2>'], $snippet);
|
||||
} elseif ($violation->ruleId === 'WCAG_1_3_5_AUTOCOMPLETE') {
|
||||
$fixedSnippet = str_replace('<input', '<input autocomplete="email"', $snippet);
|
||||
} elseif ($violation->ruleId === 'WCAG_2_1_1_SCROLLABLE_FOCUS') {
|
||||
$fixedSnippet = str_replace('<div', '<div tabindex="0"', $snippet);
|
||||
} elseif ($violation->ruleId === 'WCAG_4_1_2_ARIA_LABELLEDBY') {
|
||||
$fixedSnippet = str_replace('aria-labelledby="non_existent_label"', 'aria-labelledby="real_label"', $snippet);
|
||||
} elseif ($violation->ruleId === 'WCAG_1_1_1_ALT_PLACEHOLDER') {
|
||||
if (str_contains($snippet, 'alt="logo"')) {
|
||||
$fixedSnippet = str_replace('alt="logo"', 'alt="YakNet Accessibility Console Company Logo"', $snippet);
|
||||
} else {
|
||||
$fixedSnippet = str_replace('alt="header_banner.jpg"', 'alt="YakNet Accessibility Console Marketing Banner"', $snippet);
|
||||
}
|
||||
} elseif ($violation->ruleId === 'WCAG_1_1_1_SVG') {
|
||||
$fixedSnippet = str_replace('<svg', '<svg aria-hidden="true"', $snippet);
|
||||
} elseif ($violation->ruleId === 'WCAG_1_3_1_TABLE_SUMMARY') {
|
||||
$fixedSnippet = preg_replace('/summary=".*?"/i', '', $snippet) ?: $snippet;
|
||||
} elseif ($violation->ruleId === 'WCAG_1_3_1_PRESENTATION_TAGS') {
|
||||
$fixedSnippet = str_replace(['<center>', '</center>', '<strike>', '</strike>'], ['<span style="text-align: center; display: block;">', '</span>', '<span style="text-decoration: line-through;">', '</span>'], $snippet);
|
||||
} elseif ($violation->ruleId === 'WCAG_2_4_3_AUTOFOCUS') {
|
||||
$fixedSnippet = str_replace(' autofocus', '', $snippet);
|
||||
}
|
||||
|
||||
return "EXPLANATION: Mocked correction for accessibility validation.\nFIX: " . $fixedSnippet;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\AI\Providers;
|
||||
|
||||
use GuzzleHttp\Client as GuzzleClient;
|
||||
use YakNet\AccessibilityConsole\AI\AiProviderInterface;
|
||||
use YakNet\AccessibilityConsole\AI\PromptBuilder;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
class OpenAiProvider implements AiProviderInterface
|
||||
{
|
||||
private ?GuzzleClient $client = null;
|
||||
|
||||
public function __construct(private readonly ?string $apiKey)
|
||||
{
|
||||
if ($this->apiKey) {
|
||||
$this->client = new GuzzleClient([
|
||||
'base_uri' => 'https://api.openai.com/v1/',
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer ' . $this->apiKey,
|
||||
'Content-Type' => 'application/json',
|
||||
],
|
||||
'timeout' => 10.0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'OpenAI GPT';
|
||||
}
|
||||
|
||||
public function suggestFix(Violation $violation): ?string
|
||||
{
|
||||
if (!$this->client) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$prompt = PromptBuilder::build($violation);
|
||||
|
||||
try {
|
||||
$response = $this->client->post('chat/completions', [
|
||||
'json' => [
|
||||
'model' => 'gpt-4o-mini',
|
||||
'messages' => [
|
||||
['role' => 'user', 'content' => $prompt]
|
||||
],
|
||||
'temperature' => 0.2,
|
||||
],
|
||||
]);
|
||||
|
||||
$data = json_decode($response->getBody()->getContents(), true);
|
||||
if (is_array($data)
|
||||
&& isset($data['choices']) && is_array($data['choices'])
|
||||
&& isset($data['choices'][0]) && is_array($data['choices'][0])
|
||||
&& isset($data['choices'][0]['message']) && is_array($data['choices'][0]['message'])
|
||||
&& isset($data['choices'][0]['message']['content']) && is_string($data['choices'][0]['message']['content'])
|
||||
) {
|
||||
return $data['choices'][0]['message']['content'];
|
||||
}
|
||||
return null;
|
||||
} catch (\Throwable $e) {
|
||||
return "OpenAI Error: " . $e->getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Analytics;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Severity;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
class AccessibilityTelemetry
|
||||
{
|
||||
/**
|
||||
* Compute violation density, error distribution, and priority impact metrics.
|
||||
*
|
||||
* @param Violation[] $violations
|
||||
* @param int $totalLinesOfCode
|
||||
* @return array{
|
||||
* total_violations: int,
|
||||
* error_count: int,
|
||||
* warning_count: int,
|
||||
* defect_density_per_kloc: float,
|
||||
* critical_blockers_ratio: float
|
||||
* }
|
||||
*/
|
||||
public function computeMetrics(array $violations, int $totalLinesOfCode = 1000): array
|
||||
{
|
||||
$errorCount = 0;
|
||||
$warningCount = 0;
|
||||
|
||||
foreach ($violations as $v) {
|
||||
if ($v->severity === Severity::ERROR) {
|
||||
$errorCount++;
|
||||
} else {
|
||||
$warningCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$totalViolations = count($violations);
|
||||
$kloc = max(1.0, $totalLinesOfCode / 1000.0);
|
||||
$defectDensity = round($totalViolations / $kloc, 2);
|
||||
$criticalRatio = ($totalViolations > 0) ? round(($errorCount / $totalViolations) * 100, 1) : 0.0;
|
||||
|
||||
return [
|
||||
'total_violations' => $totalViolations,
|
||||
'error_count' => $errorCount,
|
||||
'warning_count' => $warningCount,
|
||||
'defect_density_per_kloc' => $defectDensity,
|
||||
'critical_blockers_ratio' => $criticalRatio,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Analytics;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
use YakNet\AccessibilityConsole\Core\WCAGStandard;
|
||||
|
||||
class ComplianceMatrixGenerator
|
||||
{
|
||||
/** @var array<int|string, string> */
|
||||
private static array $principleMap = [
|
||||
1 => 'Perceivable',
|
||||
2 => 'Operable',
|
||||
3 => 'Understandable',
|
||||
4 => 'Robust',
|
||||
];
|
||||
|
||||
/**
|
||||
* Generate WCAG 2.1 & 2.2 Compliance Matrix from a list of violations and total rules tested.
|
||||
*
|
||||
* @param Violation[] $violations
|
||||
* @param int $totalActiveRules
|
||||
* @return array{
|
||||
* overall_compliance_percentage: float,
|
||||
* principles: array<string, array{violations: int, status: string}>,
|
||||
* levels: array<string, array{violations: int, percentage: float}>
|
||||
* }
|
||||
*/
|
||||
public function generate(array $violations, int $totalActiveRules = 175): array
|
||||
{
|
||||
$principles = [
|
||||
'Perceivable' => ['violations' => 0, 'status' => 'Pass'],
|
||||
'Operable' => ['violations' => 0, 'status' => 'Pass'],
|
||||
'Understandable' => ['violations' => 0, 'status' => 'Pass'],
|
||||
'Robust' => ['violations' => 0, 'status' => 'Pass'],
|
||||
];
|
||||
|
||||
/** @var array<string, array{violations: int, percentage: float}> $levelCounts */
|
||||
$levelCounts = [
|
||||
'A' => ['violations' => 0, 'percentage' => 100.0],
|
||||
'AA' => ['violations' => 0, 'percentage' => 100.0],
|
||||
'AAA' => ['violations' => 0, 'percentage' => 100.0],
|
||||
];
|
||||
|
||||
foreach ($violations as $v) {
|
||||
// Determine principle from rule ID or WCAG code (e.g. WCAG_1_... => Perceivable)
|
||||
$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']++;
|
||||
$principles[$pName]['status'] = 'Needs Review';
|
||||
|
||||
// Level breakdown
|
||||
$stdVal = $v->standard->value;
|
||||
if (array_key_exists($stdVal, $levelCounts)) {
|
||||
$levelCounts[$stdVal]['violations']++;
|
||||
}
|
||||
}
|
||||
|
||||
$totalViolations = count($violations);
|
||||
$overallScore = ($totalActiveRules > 0)
|
||||
? max(0.0, min(100.0, round((1.0 - ($totalViolations / ($totalActiveRules * 2))) * 100, 1)))
|
||||
: 100.0;
|
||||
|
||||
foreach ($levelCounts as $lvl => &$data) {
|
||||
$data['percentage'] = max(0.0, min(100.0, round((1.0 - ($data['violations'] / max(1, $totalActiveRules))) * 100, 1)));
|
||||
}
|
||||
|
||||
return [
|
||||
'overall_compliance_percentage' => $overallScore,
|
||||
'principles' => $principles,
|
||||
'levels' => $levelCounts,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Analytics;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator;
|
||||
use YakNet\AccessibilityConsole\Core\Severity;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
/**
|
||||
* Persists accessibility scan snapshots over time, computes multi-run health trends,
|
||||
* and performs regression/improvement comparisons between two scan reports.
|
||||
*/
|
||||
class HistoryTracker
|
||||
{
|
||||
/**
|
||||
* Record a scan snapshot into a JSON history file.
|
||||
*
|
||||
* @param Violation[] $violations
|
||||
* @param string $historyFile
|
||||
* @param string $target
|
||||
* @param string|null $preset
|
||||
* @return array<string, mixed> 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<int, array<string, mixed>>
|
||||
*/
|
||||
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<string, mixed> $item */
|
||||
$result[] = $item;
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute overall accessibility health trend across historical runs.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $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<int, array<string, mixed>> $beforeViolations
|
||||
* @param array<int, array<string, mixed>> $afterViolations
|
||||
* @return array{
|
||||
* before_count: int,
|
||||
* after_count: int,
|
||||
* before_score: int,
|
||||
* after_score: int,
|
||||
* score_delta: int,
|
||||
* new_violations: array<int, array<string, mixed>>,
|
||||
* resolved_violations: array<int, array<string, mixed>>,
|
||||
* 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<string, mixed> $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<int, array<string, mixed>> $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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Analytics;
|
||||
|
||||
class ReportSummaryModel
|
||||
{
|
||||
/**
|
||||
* @param array<string, int> $violationCountsBySeverity
|
||||
* @param array<string, int> $violationCountsByStandard
|
||||
* @param array<string, int> $violationCountsByPrinciple
|
||||
* @param array<string, mixed> $complianceScores
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $totalViolations,
|
||||
public readonly int $totalFilesScanned,
|
||||
public readonly int $baselinedCount,
|
||||
public readonly int $healthScore,
|
||||
public readonly array $violationCountsBySeverity,
|
||||
public readonly array $violationCountsByStandard,
|
||||
public readonly array $violationCountsByPrinciple,
|
||||
public readonly array $complianceScores,
|
||||
public readonly float $scanDurationSeconds = 0.0
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'totalViolations' => $this->totalViolations,
|
||||
'totalFilesScanned' => $this->totalFilesScanned,
|
||||
'baselinedCount' => $this->baselinedCount,
|
||||
'healthScore' => $this->healthScore,
|
||||
'bySeverity' => $this->violationCountsBySeverity,
|
||||
'byStandard' => $this->violationCountsByStandard,
|
||||
'byPrinciple' => $this->violationCountsByPrinciple,
|
||||
'complianceScores' => $this->complianceScores,
|
||||
'duration' => $this->scanDurationSeconds,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Audit;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Scanner;
|
||||
|
||||
class SiteCrawler
|
||||
{
|
||||
private Scanner $scanner;
|
||||
|
||||
public function __construct(?Scanner $scanner = null)
|
||||
{
|
||||
$this->scanner = $scanner ?? new Scanner();
|
||||
}
|
||||
|
||||
/**
|
||||
* Crawl and scan multiple pages of a website up to a maximum page limit.
|
||||
*
|
||||
* @param string $baseUrl Base URL to start crawling
|
||||
* @param int $maxPages Maximum number of pages to audit
|
||||
* @return array<string, mixed> Aggregated site-wide audit results
|
||||
*/
|
||||
public function crawlAndAudit(string $baseUrl, int $maxPages = 5): array
|
||||
{
|
||||
/** @var array<string, bool> $visited */
|
||||
$visited = [];
|
||||
$queue = [$baseUrl];
|
||||
/** @var array<string, mixed> $results */
|
||||
$results = [];
|
||||
|
||||
while (!empty($queue) && count($visited) < $maxPages) {
|
||||
$url = array_shift($queue);
|
||||
if (empty($url) || isset($visited[$url])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$visited[$url] = true;
|
||||
try {
|
||||
$html = @file_get_contents($url);
|
||||
$violations = $html !== false ? $this->scanner->scan($html) : [];
|
||||
$score = max(0, 100 - count($violations) * 3);
|
||||
|
||||
$results[$url] = [
|
||||
'score' => $score,
|
||||
'violations_count' => count($violations),
|
||||
'violations' => $violations,
|
||||
];
|
||||
} catch (\Throwable $e) {
|
||||
$results[$url] = ['error' => $e->getMessage(), 'score' => 0];
|
||||
}
|
||||
}
|
||||
|
||||
$scores = [];
|
||||
$totalViolations = 0;
|
||||
foreach ($results as $res) {
|
||||
if (is_array($res)) {
|
||||
if (isset($res['score']) && is_numeric($res['score'])) {
|
||||
$scores[] = intval($res['score']);
|
||||
}
|
||||
if (isset($res['violations_count']) && is_numeric($res['violations_count'])) {
|
||||
$totalViolations += intval($res['violations_count']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$avgScore = count($scores) > 0 ? (int)round(array_sum($scores) / count($scores)) : 0;
|
||||
|
||||
return [
|
||||
'base_url' => $baseUrl,
|
||||
'pages_audited' => count($visited),
|
||||
'average_score' => $avgScore,
|
||||
'total_violations' => $totalViolations,
|
||||
'page_results' => $results,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\AutoFix;
|
||||
|
||||
class HtmlRepairEngine
|
||||
{
|
||||
/**
|
||||
* Instantly auto-repair common WCAG accessibility issues in raw HTML strings without network calls.
|
||||
*
|
||||
* @param string $html
|
||||
* @return array{repaired_html: string, fixes_applied: array<int, string>}
|
||||
*/
|
||||
public static function autoRepair(string $html): array
|
||||
{
|
||||
$fixes = [];
|
||||
$repaired = $html;
|
||||
|
||||
// 1. Ensure <html lang="..."> attribute
|
||||
if (preg_match('/<html\b(?![^>]*\blang=)[^>]*>/i', $repaired)) {
|
||||
$repaired = preg_replace('/<html\b([^>]*)>/i', '<html lang="tr"$1>', $repaired) ?? $repaired;
|
||||
$fixes[] = 'Added missing lang="tr" attribute to <html> tag.';
|
||||
}
|
||||
|
||||
// 2. Add aria-hidden="true" to decorative <svg> tags missing aria-hidden
|
||||
$svgBefore = $repaired;
|
||||
$repaired = preg_replace_callback('/<svg\b(?![^>]*\baria-hidden=)[^>]*>/i', function($matches) {
|
||||
return str_replace('<svg', '<svg aria-hidden="true"', $matches[0]);
|
||||
}, $repaired) ?? $repaired;
|
||||
|
||||
if ($repaired !== $svgBefore) {
|
||||
$fixes[] = 'Added aria-hidden="true" to decorative <svg> icons.';
|
||||
}
|
||||
|
||||
// 3. Add alt="" to <img> tags missing alt attribute
|
||||
$imgBefore = $repaired;
|
||||
$repaired = preg_replace_callback('/<img\b(?![^>]*\balt=)[^>]*>/i', function($matches) {
|
||||
return str_replace('<img', '<img alt=""', $matches[0]);
|
||||
}, $repaired) ?? $repaired;
|
||||
|
||||
if ($repaired !== $imgBefore) {
|
||||
$fixes[] = 'Added empty alt="" attribute to decorative <img> elements.';
|
||||
}
|
||||
|
||||
return [
|
||||
'repaired_html' => $repaired,
|
||||
'fixes_applied' => $fixes,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Badges;
|
||||
|
||||
class BadgeGenerator
|
||||
{
|
||||
/**
|
||||
* Generate an SVG badge representing the Accessibility Health Score.
|
||||
*
|
||||
* @param int $score 0-100
|
||||
* @param BadgeOptions|null $options
|
||||
* @return string Raw SVG markup
|
||||
*/
|
||||
public static function generateScoreBadge(int $score, ?BadgeOptions $options = null): string
|
||||
{
|
||||
$opts = $options ?? new BadgeOptions();
|
||||
$color = $opts->rightColor ?? ($score >= 90 ? '#10b981' : ($score >= 70 ? '#f59e0b' : '#ef4444'));
|
||||
$label = $opts->label;
|
||||
$value = "{$score}/100";
|
||||
|
||||
return self::renderBadge($label, $value, $color, $opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an SVG badge representing WCAG compliance status.
|
||||
*
|
||||
* @param string $standard E.g. 'WCAG 2.1 AA'
|
||||
* @param bool $compliant
|
||||
* @param BadgeOptions|null $options
|
||||
* @return string Raw SVG markup
|
||||
*/
|
||||
public static function generateComplianceBadge(string $standard = 'WCAG 2.1 AA', bool $compliant = true, ?BadgeOptions $options = null): string
|
||||
{
|
||||
$opts = $options ?? new BadgeOptions();
|
||||
$color = $opts->rightColor ?? ($compliant ? '#10b981' : '#ef4444');
|
||||
$value = $compliant ? 'passed' : 'failed';
|
||||
|
||||
return self::renderBadge($standard, $value, $color, $opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an SVG badge for total violations count.
|
||||
*
|
||||
* @param int $violationsCount
|
||||
* @param BadgeOptions|null $options
|
||||
* @return string Raw SVG markup
|
||||
*/
|
||||
public static function generateViolationsBadge(int $violationsCount, ?BadgeOptions $options = null): string
|
||||
{
|
||||
$opts = $options ?? new BadgeOptions();
|
||||
$color = $opts->rightColor ?? ($violationsCount === 0 ? '#10b981' : ($violationsCount < 5 ? '#f59e0b' : '#ef4444'));
|
||||
$value = $violationsCount === 0 ? '0 issues' : "{$violationsCount} issues";
|
||||
$label = $opts->label !== 'accessibility' ? $opts->label : 'a11y issues';
|
||||
|
||||
return self::renderBadge($label, $value, $color, $opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a standard flat shield SVG badge.
|
||||
*/
|
||||
private static function renderBadge(string $label, string $value, string $rightColor, ?BadgeOptions $options = null): string
|
||||
{
|
||||
$opts = $options ?? new BadgeOptions();
|
||||
$charWidth = 7;
|
||||
$padding = 12;
|
||||
$leftWidth = (int)(mb_strlen($label) * $charWidth + $padding);
|
||||
$rightWidth = (int)(mb_strlen($value) * $charWidth + $padding);
|
||||
$totalWidth = $leftWidth + $rightWidth;
|
||||
$height = 20;
|
||||
|
||||
$leftCenter = (int)($leftWidth / 2);
|
||||
$rightCenter = (int)($leftWidth + ($rightWidth / 2));
|
||||
|
||||
$escLabel = htmlspecialchars($label);
|
||||
$escValue = htmlspecialchars($value);
|
||||
$borderRadius = $opts->borderRadius;
|
||||
$leftColor = $opts->leftColor;
|
||||
$fontFamily = htmlspecialchars($opts->fontFamily);
|
||||
$fontSize = $opts->fontSize;
|
||||
|
||||
return <<<SVG
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="{$totalWidth}" height="{$height}" role="img" aria-label="{$escLabel}: {$escValue}">
|
||||
<title>{$escLabel}: {$escValue}</title>
|
||||
<linearGradient id="s" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
</linearGradient>
|
||||
<clipPath id="r">
|
||||
<rect width="{$totalWidth}" height="{$height}" rx="{$borderRadius}" fill="#fff"/>
|
||||
</clipPath>
|
||||
<g clip-path="url(#r)">
|
||||
<rect width="{$leftWidth}" height="{$height}" fill="{$leftColor}"/>
|
||||
<rect x="{$leftWidth}" width="{$rightWidth}" height="{$height}" fill="{$rightColor}"/>
|
||||
<rect width="{$totalWidth}" height="{$height}" fill="url(#s)"/>
|
||||
</g>
|
||||
<g fill="#fff" text-anchor="middle" font-family="{$fontFamily}" text-rendering="geometricPrecision" font-size="{$fontSize}">
|
||||
<text aria-hidden="true" x="{$leftCenter}" y="15" fill="#010101" fill-opacity=".3">{$escLabel}</text>
|
||||
<text x="{$leftCenter}" y="14">{$escLabel}</text>
|
||||
<text aria-hidden="true" x="{$rightCenter}" y="15" fill="#010101" fill-opacity=".3">{$escValue}</text>
|
||||
<text x="{$rightCenter}" y="14">{$escValue}</text>
|
||||
</g>
|
||||
</svg>
|
||||
SVG;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Badges;
|
||||
|
||||
/**
|
||||
* Options DTO for customizing SVG badge generation.
|
||||
*/
|
||||
class BadgeOptions
|
||||
{
|
||||
/**
|
||||
* @param string $label Default left container text label
|
||||
* @param string $leftColor Hex color code for left container background
|
||||
* @param string|null $rightColor Optional hex color override for right container background
|
||||
* @param int $borderRadius Corner radius for SVG clipPath
|
||||
* @param string $fontFamily Font family CSS rule for badge typography
|
||||
* @param int $fontSize Font size in pixels
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $label = 'accessibility',
|
||||
public readonly string $leftColor = '#1f2937',
|
||||
public readonly ?string $rightColor = null,
|
||||
public readonly int $borderRadius = 3,
|
||||
public readonly string $fontFamily = 'Verdana,Geneva,DejaVu Sans,sans-serif',
|
||||
public readonly int $fontSize = 11,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Benchmarks;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Scanner;
|
||||
|
||||
class BenchmarkEngine
|
||||
{
|
||||
private Scanner $scanner;
|
||||
|
||||
public function __construct(?Scanner $scanner = null)
|
||||
{
|
||||
$this->scanner = $scanner ?? new Scanner();
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare accessibility health scores across multiple target URLs.
|
||||
*
|
||||
* @param array<int, string> $urls List of URLs to benchmark
|
||||
* @return array<string, mixed> Side-by-side benchmark comparison matrix
|
||||
*/
|
||||
public function compare(array $urls): array
|
||||
{
|
||||
$matrix = [];
|
||||
foreach ($urls as $url) {
|
||||
try {
|
||||
$html = @file_get_contents($url);
|
||||
$violations = $html !== false ? $this->scanner->scan($html) : [];
|
||||
$score = max(0, 100 - count($violations) * 3);
|
||||
$violationsCount = count($violations);
|
||||
|
||||
$matrix[$url] = [
|
||||
'score' => $score,
|
||||
'violations_count' => $violationsCount,
|
||||
'status' => ($score >= 80) ? 'PASS' : 'FAIL',
|
||||
];
|
||||
} catch (\Throwable $e) {
|
||||
$matrix[$url] = ['score' => 0, 'violations_count' => -1, 'status' => 'ERROR', 'error' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
// Rank by score descending
|
||||
uasort($matrix, function (array $a, array $b) {
|
||||
return intval($b['score']) <=> intval($a['score']);
|
||||
});
|
||||
|
||||
return [
|
||||
'benchmark_date' => date('Y-m-d H:i:s'),
|
||||
'targets_count' => count($urls),
|
||||
'rankings' => $matrix,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\CI;
|
||||
|
||||
/**
|
||||
* Generates ready-to-use CI/CD pipeline configuration files for GitHub Actions,
|
||||
* GitLab CI, Azure Pipelines, and Bitbucket Pipelines with YakNet Accessibility Console.
|
||||
*/
|
||||
class CiWorkflowGenerator
|
||||
{
|
||||
/**
|
||||
* List supported CI/CD platform identifiers.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function getSupportedPlatforms(): array
|
||||
{
|
||||
return ['github', 'gitlab', 'azure', 'bitbucket'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the conventional repository file path for a given CI platform.
|
||||
*/
|
||||
public static function getDefaultPath(string $platform): string
|
||||
{
|
||||
return match (strtolower($platform)) {
|
||||
'github' => '.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 <<<YAML
|
||||
name: Accessibility Audit (YakNet)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, master ]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
jobs:
|
||||
accessibility:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.3'
|
||||
extensions: dom, libxml, mbstring
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer install --no-interaction --prefer-dist
|
||||
|
||||
- name: Run YakNet Accessibility Console
|
||||
run: |
|
||||
vendor/bin/a11y scan {$targetPath} \
|
||||
--preset={$preset} \
|
||||
--min-score={$minScore} \
|
||||
--report=a11y.sarif \
|
||||
--vpat=vpat-2.5.md \
|
||||
--badge=a11y-badge.svg
|
||||
|
||||
- name: Upload SARIF to GitHub Code Scanning
|
||||
if: always()
|
||||
uses: github/codeql-action/upload-sarif@v3
|
||||
with:
|
||||
sarif_file: a11y.sarif
|
||||
|
||||
- name: Upload VPAT 2.5 & Badge Artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: accessibility-reports
|
||||
path: |
|
||||
vpat-2.5.md
|
||||
a11y-badge.svg
|
||||
YAML;
|
||||
}
|
||||
|
||||
private function generateGitLabCi(string $preset, int $minScore, string $targetPath): string
|
||||
{
|
||||
return <<<YAML
|
||||
accessibility_audit:
|
||||
stage: test
|
||||
image: php:8.3-cli
|
||||
before_script:
|
||||
- composer install --no-interaction --prefer-dist
|
||||
script:
|
||||
- vendor/bin/a11y scan {$targetPath} --preset={$preset} --min-score={$minScore} --format=gitlab > 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 <<<YAML
|
||||
trigger:
|
||||
- main
|
||||
|
||||
pool:
|
||||
vmImage: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- script: composer install --no-interaction --prefer-dist
|
||||
displayName: 'Install Composer Dependencies'
|
||||
|
||||
- script: |
|
||||
vendor/bin/a11y scan {$targetPath} \
|
||||
--preset={$preset} \
|
||||
--min-score={$minScore} \
|
||||
--report=a11y-junit.xml \
|
||||
--vpat=vpat-2.5.md
|
||||
displayName: 'Run YakNet Accessibility Audit'
|
||||
|
||||
- task: PublishTestResults@2
|
||||
condition: always()
|
||||
inputs:
|
||||
testResultsFormat: 'JUnit'
|
||||
testResultsFiles: 'a11y-junit.xml'
|
||||
testRunTitle: 'YakNet Accessibility Audit'
|
||||
YAML;
|
||||
}
|
||||
|
||||
private function generateBitbucketPipelines(string $preset, int $minScore, string $targetPath): string
|
||||
{
|
||||
return <<<YAML
|
||||
image: php:8.3-cli
|
||||
|
||||
pipelines:
|
||||
default:
|
||||
- step:
|
||||
name: YakNet Accessibility Audit
|
||||
caches:
|
||||
- composer
|
||||
script:
|
||||
- composer install --no-interaction --prefer-dist
|
||||
- vendor/bin/a11y scan {$targetPath} --preset={$preset} --min-score={$minScore} --report=a11y-junit.xml --vpat=vpat-2.5.md
|
||||
artifacts:
|
||||
- a11y-junit.xml
|
||||
- vpat-2.5.md
|
||||
YAML;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Cache;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Severity;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
use YakNet\AccessibilityConsole\Core\WCAGStandard;
|
||||
|
||||
/**
|
||||
* Incremental content-hash cache for static accessibility scans.
|
||||
* Stores violation results keyed by file path, content SHA-256 hash, and active rule-set signature
|
||||
* to avoid re-parsing unchanged templates on repeated runs.
|
||||
*/
|
||||
class ScanCache
|
||||
{
|
||||
/**
|
||||
* @var array<string, array{hash: string, violations: array<int, array<string, mixed>>}>
|
||||
*/
|
||||
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<int, array<string, mixed>> $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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Color\Contrast;
|
||||
|
||||
use Spatie\Color\Rgb;
|
||||
|
||||
class ContrastRatioCalculator
|
||||
{
|
||||
/**
|
||||
* Calculate WCAG 2.1 relative contrast ratio between foreground and background colors.
|
||||
*/
|
||||
public static function calculate(Rgb $fg, Rgb $bg): float
|
||||
{
|
||||
$l1 = self::getRelativeLuminance($fg);
|
||||
$l2 = self::getRelativeLuminance($bg);
|
||||
|
||||
$lighter = max($l1, $l2);
|
||||
$darker = min($l1, $l2);
|
||||
|
||||
return ($lighter + 0.05) / ($darker + 0.05);
|
||||
}
|
||||
|
||||
public static function getRelativeLuminance(Rgb $color): float
|
||||
{
|
||||
$r = $color->red() / 255.0;
|
||||
$g = $color->green() / 255.0;
|
||||
$b = $color->blue() / 255.0;
|
||||
|
||||
$r = ($r <= 0.03928) ? $r / 12.92 : pow(($r + 0.055) / 1.055, 2.4);
|
||||
$g = ($g <= 0.03928) ? $g / 12.92 : pow(($g + 0.055) / 1.055, 2.4);
|
||||
$b = ($b <= 0.03928) ? $b / 12.92 : pow(($b + 0.055) / 1.055, 2.4);
|
||||
|
||||
return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Color\Simulators;
|
||||
|
||||
use Spatie\Color\Rgb;
|
||||
|
||||
class DeuteranopiaSimulator
|
||||
{
|
||||
/**
|
||||
* Simulate Deuteranopia (green-blindness) vision deficiency for a given RGB color.
|
||||
*/
|
||||
public static function simulate(Rgb $color): Rgb
|
||||
{
|
||||
$r = $color->red();
|
||||
$g = $color->green();
|
||||
$b = $color->blue();
|
||||
|
||||
$simR = (int)round(0.625 * $r + 0.375 * $g);
|
||||
$simG = (int)round(0.700 * $r + 0.300 * $g);
|
||||
$simB = (int)round(0.000 * $r + 0.300 * $g + 0.700 * $b);
|
||||
|
||||
return new Rgb(
|
||||
min(255, max(0, $simR)),
|
||||
min(255, max(0, $simG)),
|
||||
min(255, max(0, $simB))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Color\Simulators;
|
||||
|
||||
use Spatie\Color\Rgb;
|
||||
|
||||
class ProtanopiaSimulator
|
||||
{
|
||||
/**
|
||||
* Simulate Protanopia (red-blindness) vision deficiency for a given RGB color.
|
||||
*/
|
||||
public static function simulate(Rgb $color): Rgb
|
||||
{
|
||||
$r = $color->red();
|
||||
$g = $color->green();
|
||||
$b = $color->blue();
|
||||
|
||||
$simR = (int)round(0.56667 * $r + 0.43333 * $g);
|
||||
$simG = (int)round(0.55833 * $r + 0.44167 * $g);
|
||||
$simB = (int)round(0.00000 * $r + 0.24167 * $g + 0.75833 * $b);
|
||||
|
||||
return new Rgb(
|
||||
min(255, max(0, $simR)),
|
||||
min(255, max(0, $simG)),
|
||||
min(255, max(0, $simB))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Color\Simulators;
|
||||
|
||||
use Spatie\Color\Rgb;
|
||||
|
||||
class TritanopiaSimulator
|
||||
{
|
||||
/**
|
||||
* Simulate Tritanopia (blue-blindness) vision deficiency for a given RGB color.
|
||||
*/
|
||||
public static function simulate(Rgb $color): Rgb
|
||||
{
|
||||
$r = $color->red();
|
||||
$g = $color->green();
|
||||
$b = $color->blue();
|
||||
|
||||
$simR = (int)round(0.95000 * $r + 0.05000 * $g);
|
||||
$simG = (int)round(0.00000 * $r + 0.43333 * $g + 0.56667 * $b);
|
||||
$simB = (int)round(0.00000 * $r + 0.47500 * $g + 0.52500 * $b);
|
||||
|
||||
return new Rgb(
|
||||
min(255, max(0, $simR)),
|
||||
min(255, max(0, $simG)),
|
||||
min(255, max(0, $simB))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Compliance;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator;
|
||||
use YakNet\AccessibilityConsole\Core\Severity;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
use YakNet\AccessibilityConsole\Rules\RuleLevels;
|
||||
|
||||
/**
|
||||
* Generates VPAT 2.5 (Voluntary Product Accessibility Template) / ACR
|
||||
* (Accessibility Conformance Report) documents aligned with WCAG 2.1, WCAG 2.2,
|
||||
* Revised Section 508, and EN 301 549.
|
||||
*/
|
||||
class VpatReportGenerator
|
||||
{
|
||||
/**
|
||||
* Master catalog of WCAG 2.1 & 2.2 Success Criteria (Code => [Title, Level, Version, Automated]).
|
||||
*
|
||||
* @var array<string, array{title: string, level: string, version: string, automated: bool}>
|
||||
*/
|
||||
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<string, array{code: string, title: string, level: string, version: string, conformance: string, violations_count: int, remarks: string}>
|
||||
* }
|
||||
*/
|
||||
public function buildReportData(
|
||||
array $violations,
|
||||
string $productName = 'Web Application',
|
||||
string $productVersion = '1.0.0',
|
||||
string $evaluator = 'YakNet Accessibility Console Automated Evaluation'
|
||||
): array {
|
||||
/** @var array<string, Violation[]> $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(
|
||||
'<tr><td><strong>%s</strong> %s <span class="ver">WCAG %s</span></td><td><span class="badge" style="background:%s">%s</span></td><td>%s</td></tr>',
|
||||
htmlspecialchars($row['code']),
|
||||
htmlspecialchars($row['title']),
|
||||
htmlspecialchars($row['version']),
|
||||
$badgeColor,
|
||||
htmlspecialchars($row['conformance']),
|
||||
htmlspecialchars($row['remarks'])
|
||||
);
|
||||
}
|
||||
|
||||
$tablesHtml .= "<h2>WCAG 2.1 / 2.2 Level {$level}</h2>"
|
||||
. '<table><thead><tr><th scope="col">Success Criterion</th><th scope="col">Conformance Level</th><th scope="col">Remarks and Explanations</th></tr></thead><tbody>'
|
||||
. $rowsHtml
|
||||
. '</tbody></table>';
|
||||
}
|
||||
|
||||
$productEsc = htmlspecialchars($data['product_name']);
|
||||
$versionEsc = htmlspecialchars($data['product_version']);
|
||||
$evalEsc = htmlspecialchars($data['evaluator']);
|
||||
$dateEsc = htmlspecialchars($data['generated_at']);
|
||||
|
||||
return <<<HTML
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>VPAT 2.5 Accessibility Conformance Report — {$productEsc}</title>
|
||||
<style>
|
||||
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; color: #0f172a; background: #f8fafc; margin: 0; padding: 2rem; line-height: 1.5; }
|
||||
main { max-width: 1080px; margin: 0 auto; background: #ffffff; padding: 2rem 2.5rem; border-radius: 10px; box-shadow: 0 2px 12px rgba(15, 23, 42, 0.08); }
|
||||
h1 { margin-top: 0; color: #0f172a; }
|
||||
h2 { margin-top: 2rem; border-bottom: 2px solid #e2e8f0; padding-bottom: 0.4rem; }
|
||||
.meta-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 1rem; margin: 1.5rem 0; }
|
||||
.card { background: #f1f5f9; padding: 1rem; border-radius: 8px; border-left: 4px solid #2563eb; }
|
||||
.card strong { display: block; font-size: 0.8rem; text-transform: uppercase; color: #475569; }
|
||||
table { width: 100%; border-collapse: collapse; margin-top: 1rem; font-size: 0.92rem; }
|
||||
th, td { text-align: left; padding: 0.65rem 0.8rem; border-bottom: 1px solid #e2e8f0; vertical-align: top; }
|
||||
th { background: #1e293b; color: #ffffff; }
|
||||
.badge { display: inline-block; color: #ffffff; padding: 0.2rem 0.6rem; border-radius: 999px; font-size: 0.78rem; font-weight: 600; white-space: nowrap; }
|
||||
.ver { font-size: 0.75rem; color: #64748b; margin-left: 0.4rem; }
|
||||
footer { margin-top: 2.5rem; font-size: 0.85rem; color: #475569; border-top: 1px solid #e2e8f0; padding-top: 1rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>VPAT 2.5 Accessibility Conformance Report</h1>
|
||||
<p>WCAG 2.1 / 2.2, Revised Section 508 & EN 301 549 Evaluation</p>
|
||||
<div class="meta-grid">
|
||||
<div class="card"><strong>Product</strong>{$productEsc} ({$versionEsc})</div>
|
||||
<div class="card"><strong>Health Score</strong>{$data['health_score']} / 100</div>
|
||||
<div class="card"><strong>Evaluator</strong>{$evalEsc}</div>
|
||||
<div class="card"><strong>Date</strong>{$dateEsc}</div>
|
||||
</div>
|
||||
<p>
|
||||
<strong>Supports:</strong> {$data['summary']['supports']} |
|
||||
<strong>Partially Supports:</strong> {$data['summary']['partially_supports']} |
|
||||
<strong>Does Not Support:</strong> {$data['summary']['does_not_support']} |
|
||||
<strong>Not Evaluated (Manual):</strong> {$data['summary']['not_evaluated']}
|
||||
</p>
|
||||
{$tablesHtml}
|
||||
<footer>
|
||||
Generated by <strong>YakNet Accessibility Console v4.0.0</strong> (Open Source, MIT License).
|
||||
</footer>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Console\Command;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use YakNet\AccessibilityConsole\Analytics\HistoryTracker;
|
||||
|
||||
class CompareCommand extends Command
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->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', "<fg={$deltaColor}>{$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 ? '<fg=red>REGRESSION</>' : '<fg=green>NONE</>'],
|
||||
['Resolved Issues', '-', (string)count($diff['resolved_violations']), count($diff['resolved_violations']) > 0 ? '<fg=green>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(" <fg=red>+ [{$ruleId}]</> ({$loc}) {$msg}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($input->getOption('fail-on-regression') && !empty($diff['new_violations'])) {
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array<string, mixed>>|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<string, mixed> $item */
|
||||
$result[] = $item;
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Console\Command;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Helper\Table;
|
||||
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\Core\Config;
|
||||
use YakNet\AccessibilityConsole\Core\RuleRegistry;
|
||||
use YakNet\AccessibilityConsole\Core\SelfHealing\LocalHealer;
|
||||
use YakNet\AccessibilityConsole\Presets\PresetRegistry;
|
||||
use YakNet\AccessibilityConsole\Rules\RuleLevels;
|
||||
|
||||
class DoctorCommand extends Command
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->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 ? '<fg=green>OK</>' : '<fg=red>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 ? '<fg=green>OK</>' : '<fg=red>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'] ? '<fg=green>VALID (0 conflicts)</>' : '<fg=red>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)), '<fg=green>OK</>'];
|
||||
|
||||
// 5. Offline Self-Healing Coverage
|
||||
$healableCount = count(LocalHealer::getSupportedRuleIds());
|
||||
$rows[] = ['Offline Self-Healer', sprintf('%d deterministic auto-fixes', $healableCount), '<fg=green>OK</>'];
|
||||
|
||||
// 6. Optional Exporters & Renderers
|
||||
$hasDompdf = class_exists(\Dompdf\Dompdf::class);
|
||||
$rows[] = ['PDF Report Generator (dompdf)', $hasDompdf ? 'Installed' : 'Not installed', $hasDompdf ? '<fg=green>READY</>' : '<fg=yellow>OPTIONAL</>'];
|
||||
|
||||
$hasSpreadsheet = class_exists(\PhpOffice\PhpSpreadsheet\Spreadsheet::class);
|
||||
$rows[] = ['Excel Exporter (phpspreadsheet)', $hasSpreadsheet ? 'Installed' : 'Not installed', $hasSpreadsheet ? '<fg=green>READY</>' : '<fg=yellow>OPTIONAL</>'];
|
||||
|
||||
$hasChrome = class_exists(\HeadlessChromium\BrowserFactory::class);
|
||||
$rows[] = ['Headless Chrome Renderer', $hasChrome ? 'Installed' : 'Not installed', $hasChrome ? '<fg=green>READY</>' : '<fg=yellow>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', '<fg=green>OK</>'];
|
||||
|
||||
$hasAiKey = $config->getGeminiApiKey() !== null && $config->getGeminiApiKey() !== '';
|
||||
$rows[] = ['AI Self-Healing (GEMINI_API_KEY)', $hasAiKey ? 'Configured' : 'Not set (offline healer active)', $hasAiKey ? '<fg=green>READY</>' : '<fg=yellow>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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Console\Command;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use YakNet\AccessibilityConsole\Core\RuleRegistry;
|
||||
use YakNet\AccessibilityConsole\Core\SelfHealing\LocalHealer;
|
||||
use YakNet\AccessibilityConsole\Reference\WcagDatabase;
|
||||
use YakNet\AccessibilityConsole\Rules\RuleController;
|
||||
|
||||
class ExplainCommand extends Command
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->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("<fg=cyan>Criterion:</> {$wcag->title} (Level {$wcag->level})");
|
||||
$io->writeln("<fg=cyan>Reference:</> {$wcag->url}");
|
||||
$io->newLine();
|
||||
$io->writeln("<fg=red;options=bold>Non-Compliant Example:</>");
|
||||
$io->writeln(" " . $wcag->badExample);
|
||||
$io->newLine();
|
||||
$io->writeln("<fg=green;options=bold>Compliant Example:</>");
|
||||
$io->writeln(" " . $wcag->goodExample);
|
||||
$io->newLine();
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use YakNet\AccessibilityConsole\AI\GeminiFixer;
|
||||
use YakNet\AccessibilityConsole\AI\AiFixerManager;
|
||||
use YakNet\AccessibilityConsole\Core\Analyser;
|
||||
use YakNet\AccessibilityConsole\Core\Config;
|
||||
use YakNet\AccessibilityConsole\Core\Scanner;
|
||||
@@ -26,6 +26,7 @@ class FixCommand extends Command
|
||||
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to the configuration file (default: a11y.yaml)')
|
||||
->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping (URL scans only)')
|
||||
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Show what would be fixed without modifying files')
|
||||
->addOption('offline', null, InputOption::VALUE_NONE, 'Perform deterministic offline rule-based fixes without calling AI')
|
||||
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-9)')
|
||||
->addOption('js', null, InputOption::VALUE_NONE, 'Enable JavaScript rendering using Headless Chrome (URL scans only)');
|
||||
}
|
||||
@@ -39,10 +40,11 @@ class FixCommand extends Command
|
||||
$configPath = is_string($configPathOption) ? $configPathOption : getcwd() . '/a11y.yaml';
|
||||
$config = Config::fromYaml($configPath);
|
||||
|
||||
$offline = (bool)$input->getOption('offline');
|
||||
$apiKey = $config->getGeminiApiKey();
|
||||
if (!$apiKey) {
|
||||
$io->error("GEMINI_API_KEY not found in .env or environment variables. AI fixing requires an API key.");
|
||||
return Command::FAILURE;
|
||||
if (!$offline && !$apiKey) {
|
||||
$io->note("GEMINI_API_KEY not found in .env or environment variables. Running in offline rule-based healing mode (--offline).");
|
||||
$offline = true;
|
||||
}
|
||||
|
||||
$levelOption = $input->getOption('level');
|
||||
@@ -53,11 +55,11 @@ class FixCommand extends Command
|
||||
|
||||
// If target is a URL, run the legacy URL fixing logic
|
||||
if ($isUrl) {
|
||||
return $this->executeUrlFix($target, $level, $apiKey, $input, $output, $io);
|
||||
return $this->executeUrlFix($target, $level, $apiKey, $input, $output, $io, $offline);
|
||||
}
|
||||
|
||||
// --- LOCAL FILE / DIRECTORY SELF-HEALING ENGINE ---
|
||||
$io->title("AI Self-Healing Mode - Directory Static Analysis");
|
||||
$io->title($offline ? "Offline Rule-Based Self-Healing Mode" : "AI Self-Healing Mode - Directory Static Analysis");
|
||||
$io->writeln("<fg=gray>Configuration loaded from:</> <fg=cyan>$configPath</>");
|
||||
$dryRun = (bool)$input->getOption('dry-run');
|
||||
|
||||
@@ -87,9 +89,10 @@ class FixCommand extends Command
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$io->note(sprintf("Found %d violations. Starting AI analysis and healing...", count($violations)));
|
||||
$io->note(sprintf("Found %d violations. Starting %s analysis and healing...", count($violations), $offline ? 'offline rule-based' : 'AI'));
|
||||
|
||||
$fixer = new GeminiFixer($apiKey);
|
||||
$fixer = !$offline ? new AiFixerManager($apiKey) : null;
|
||||
$diffGenerator = new \YakNet\AccessibilityConsole\Core\Diff\VisualDiffGenerator();
|
||||
$fixedCount = 0;
|
||||
|
||||
// Group violations by file path
|
||||
@@ -116,27 +119,52 @@ class FixCommand extends Command
|
||||
continue;
|
||||
}
|
||||
|
||||
$localHealer = new \YakNet\AccessibilityConsole\Core\SelfHealing\LocalHealer();
|
||||
|
||||
foreach ($fileViolations as $violation) {
|
||||
$line = $violation->location['line'] ?? 0;
|
||||
$io->write("Analyzing <fg=yellow>{$violation->ruleId}</> on line <fg=cyan>$line</>... ");
|
||||
|
||||
// Get AI Suggestion
|
||||
$rawSuggestion = $fixer->suggestFix($violation);
|
||||
// Try Local Healer first
|
||||
$rawSuggestion = $localHealer->heal($violation);
|
||||
$isLocalFix = false;
|
||||
|
||||
if ($rawSuggestion !== null) {
|
||||
$isLocalFix = true;
|
||||
} elseif ($fixer !== null) {
|
||||
// Fallback to AI Suggestion
|
||||
$rawSuggestion = $fixer->suggestFix($violation);
|
||||
} else {
|
||||
$io->writeln("<fg=yellow>Skipped (Rule requires AI or manual intervention)</>");
|
||||
continue;
|
||||
}
|
||||
|
||||
$suggestion = $rawSuggestion;
|
||||
if ($rawSuggestion && str_contains($rawSuggestion, 'FIX:')) {
|
||||
if (is_string($rawSuggestion) && str_contains($rawSuggestion, 'FIX:')) {
|
||||
preg_match('/FIX:(.*)/s', $rawSuggestion, $matches);
|
||||
$suggestion = trim($matches[1] ?? $rawSuggestion);
|
||||
$suggestion = preg_replace('/^```html\s*|\s*```$/i', '', $suggestion);
|
||||
}
|
||||
|
||||
if (!$suggestion || ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:'))) {
|
||||
if (!is_string($suggestion)) {
|
||||
$io->writeln("<fg=red>Skipped (AI could not generate a clean fix)</>");
|
||||
continue;
|
||||
}
|
||||
|
||||
$io->writeln("<fg=green>Fix Found!</>");
|
||||
$io->writeln(" <fg=gray>Original:</> <fg=red>" . htmlspecialchars(trim($violation->htmlSnippet)) . "</>");
|
||||
$io->writeln(" <fg=gray>AI Fix: </> <fg=green>" . htmlspecialchars(trim($suggestion)) . "</>");
|
||||
if ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
|
||||
$io->writeln("<fg=red>Skipped (AI could not generate a clean fix)</>");
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($isLocalFix) {
|
||||
$io->writeln("<fg=green>Local Fix Found!</>");
|
||||
} else {
|
||||
$io->writeln("<fg=green>AI Fix Found!</>");
|
||||
}
|
||||
$io->writeln(" <fg=gray>Diff:</>");
|
||||
$diffOutput = $diffGenerator->generate($violation->htmlSnippet, $suggestion);
|
||||
$indentedDiff = implode("\n", array_map(fn($line) => ' ' . $line, explode("\n", trim($diffOutput))));
|
||||
$io->writeln($indentedDiff);
|
||||
|
||||
if ($dryRun) {
|
||||
$io->writeln(" <fg=blue>[DRY RUN] File modification skipped.</>");
|
||||
@@ -166,7 +194,7 @@ class FixCommand extends Command
|
||||
/**
|
||||
* Legacy URL scan and fix logic
|
||||
*/
|
||||
private function executeUrlFix(string $target, int $level, string $apiKey, InputInterface $input, OutputInterface $output, SymfonyStyle $io): int
|
||||
private function executeUrlFix(string $target, int $level, ?string $apiKey, InputInterface $input, OutputInterface $output, SymfonyStyle $io, bool $offline = false): int
|
||||
{
|
||||
$projectPathOption = $input->getOption('project-path');
|
||||
$projectPath = is_string($projectPathOption) ? $projectPathOption : getcwd();
|
||||
@@ -176,7 +204,7 @@ class FixCommand extends Command
|
||||
$dryRun = (bool)$input->getOption('dry-run');
|
||||
$useJs = (bool)$input->getOption('js');
|
||||
|
||||
$io->title("AI Self-Healing Mode - Fixing URL: $target");
|
||||
$io->title($offline ? "Offline Rule-Based Mode - Fixing URL: $target" : "AI Self-Healing Mode - Fixing URL: $target");
|
||||
|
||||
// Fetch HTML
|
||||
if ($useJs) {
|
||||
@@ -208,9 +236,10 @@ class FixCommand extends Command
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$io->note("Found " . count($violations) . " violations. Starting AI analysis...");
|
||||
$io->note(sprintf("Found %d violations. Starting %s analysis...", count($violations), $offline ? 'offline' : 'AI'));
|
||||
|
||||
$fixer = new GeminiFixer($apiKey);
|
||||
$fixer = (!$offline && is_string($apiKey) && $apiKey !== '') ? new AiFixerManager($apiKey) : null;
|
||||
$diffGenerator = new \YakNet\AccessibilityConsole\Core\Diff\VisualDiffGenerator();
|
||||
$locator = new SourceLocator($projectPath);
|
||||
$fixedCount = 0;
|
||||
|
||||
@@ -224,23 +253,45 @@ class FixCommand extends Command
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get AI Suggestion
|
||||
$rawSuggestion = $fixer->suggestFix($violation);
|
||||
$localHealer = new \YakNet\AccessibilityConsole\Core\SelfHealing\LocalHealer();
|
||||
$rawSuggestion = $localHealer->heal($violation);
|
||||
$isLocalFix = false;
|
||||
|
||||
if ($rawSuggestion !== null) {
|
||||
$isLocalFix = true;
|
||||
} elseif ($fixer !== null) {
|
||||
$rawSuggestion = $fixer->suggestFix($violation);
|
||||
} else {
|
||||
$io->writeln("<fg=yellow>Skipped (Rule requires AI or manual intervention)</>");
|
||||
continue;
|
||||
}
|
||||
|
||||
$suggestion = $rawSuggestion;
|
||||
if ($rawSuggestion && str_contains($rawSuggestion, 'FIX:')) {
|
||||
if (is_string($rawSuggestion) && str_contains($rawSuggestion, 'FIX:')) {
|
||||
preg_match('/FIX:(.*)/s', $rawSuggestion, $matches);
|
||||
$suggestion = trim($matches[1] ?? $rawSuggestion);
|
||||
$suggestion = preg_replace('/^```html\s*|\s*```$/i', '', $suggestion);
|
||||
}
|
||||
|
||||
if (!$suggestion || ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:'))) {
|
||||
if (!is_string($suggestion)) {
|
||||
$io->writeln("<fg=red>Skipped (AI could not generate a clean fix)</>");
|
||||
continue;
|
||||
}
|
||||
|
||||
$io->writeln("<fg=green>Fix Found!</>");
|
||||
$io->writeln(" <fg=gray>Original:</> <fg=red>" . htmlspecialchars(trim($violation->htmlSnippet)) . "</>");
|
||||
$io->writeln(" <fg=gray>AI Fix: </> <fg=green>" . htmlspecialchars(trim($suggestion)) . "</>");
|
||||
if ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
|
||||
$io->writeln("<fg=red>Skipped (AI could not generate a clean fix)</>");
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($isLocalFix) {
|
||||
$io->writeln("<fg=green>Local Fix Found!</>");
|
||||
} else {
|
||||
$io->writeln("<fg=green>AI Fix Found!</>");
|
||||
}
|
||||
$io->writeln(" <fg=gray>Diff:</>");
|
||||
$diffOutput = $diffGenerator->generate($violation->htmlSnippet, $suggestion);
|
||||
$indentedDiff = implode("\n", array_map(fn($line) => ' ' . $line, explode("\n", trim($diffOutput))));
|
||||
$io->writeln($indentedDiff);
|
||||
|
||||
if ($dryRun) {
|
||||
$io->writeln(" <fg=blue>[DRY RUN] File modification skipped.</>");
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Console\Command;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
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\Presets\PresetRegistry;
|
||||
|
||||
class PresetsCommand extends Command
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->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([
|
||||
'<fg=cyan;options=bold>' . $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=<name>`.', count($presets)));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -7,15 +7,24 @@ 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;
|
||||
|
||||
class RulesCommand extends Command
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->setName('rules')
|
||||
->setDescription('List all available accessibility scanning rules');
|
||||
->setDescription('List all available accessibility scanning rules')
|
||||
->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 (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
|
||||
@@ -23,19 +32,71 @@ class RulesCommand extends Command
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
$io->title("Accessibility Console - Available Rules");
|
||||
|
||||
$searchQuery = $input->getOption('search');
|
||||
$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);
|
||||
|
||||
$table = new Table($output);
|
||||
$table->setHeaders(['Rule ID', 'Standard', 'Severity', 'Level', 'Description']);
|
||||
|
||||
$rules = RuleLevels::getRulesForLevel(9);
|
||||
$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 : '';
|
||||
$severity = method_exists($rule, 'getSeverity') ? $rule->getSeverity()->value : '';
|
||||
$level = method_exists($rule, 'getLevel') ? $rule->getLevel() : 4;
|
||||
|
||||
// Search filter
|
||||
if (is_string($searchQuery) && $searchQuery !== '') {
|
||||
$query = strtolower($searchQuery);
|
||||
if (!str_contains(strtolower($ruleId), $query) && !str_contains(strtolower($description), $query)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Standard filter
|
||||
if (is_string($standardFilter) && $standardFilter !== '') {
|
||||
if (strcasecmp($standard, $standardFilter) !== 0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Severity filter
|
||||
if (is_string($severityFilter) && $severityFilter !== '') {
|
||||
if (strcasecmp($severity, $severityFilter) !== 0) {
|
||||
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([
|
||||
"<fg=cyan;options=bold>$ruleId</>",
|
||||
@@ -44,11 +105,20 @@ class RulesCommand extends Command
|
||||
$level,
|
||||
$description
|
||||
]);
|
||||
$matchedCount++;
|
||||
}
|
||||
|
||||
$table->render();
|
||||
$io->newLine();
|
||||
$io->note("Total rules available: " . count($rules));
|
||||
|
||||
$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));
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
@@ -10,14 +10,37 @@ 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;
|
||||
use YakNet\AccessibilityConsole\Reporting\XmlFormatter;
|
||||
use YakNet\AccessibilityConsole\Reporting\MarkdownFormatter;
|
||||
use YakNet\AccessibilityConsole\Reporting\CsvFormatter;
|
||||
use YakNet\AccessibilityConsole\Reporting\GitLabCodeQualityFormatter;
|
||||
use YakNet\AccessibilityConsole\Reporting\SarifFormatter;
|
||||
use YakNet\AccessibilityConsole\Reporting\JunitFormatter;
|
||||
use YakNet\AccessibilityConsole\Reporting\PdfReportGenerator;
|
||||
use YakNet\AccessibilityConsole\Reporting\ExcelReportExporter;
|
||||
use YakNet\AccessibilityConsole\Badges\BadgeGenerator;
|
||||
use YakNet\AccessibilityConsole\Presets\PresetRegistry;
|
||||
use YakNet\AccessibilityConsole\Source\SourceLocator;
|
||||
|
||||
class ScanCommand extends Command
|
||||
@@ -31,12 +54,26 @@ 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('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (console, json, github)')
|
||||
->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)')
|
||||
->addOption('generate-baseline', null, InputOption::VALUE_NONE, 'Generate a baseline file containing all current violations')
|
||||
->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 or json)')
|
||||
->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)')
|
||||
->addOption('depth', null, InputOption::VALUE_REQUIRED, 'Maximum crawling depth (URL scans only)', '3')
|
||||
@@ -57,6 +94,19 @@ class ScanCommand extends Command
|
||||
$levelOption = $input->getOption('level');
|
||||
$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($presetName) && $presetName !== '') {
|
||||
$presetRegistry = new PresetRegistry();
|
||||
$activePreset = $presetRegistry->get($presetName);
|
||||
if ($activePreset !== null) {
|
||||
$level = $activePreset->getLevel();
|
||||
} else {
|
||||
$io->warning("Preset '{$presetName}' not found. Using default rules.");
|
||||
}
|
||||
}
|
||||
|
||||
$formatOption = $input->getOption('format');
|
||||
$format = is_string($formatOption) ? $formatOption : $config->getFormat();
|
||||
|
||||
@@ -75,9 +125,14 @@ class ScanCommand extends Command
|
||||
}
|
||||
|
||||
// --- LOCAL DIRECTORY / FILE STATIC ANALYSIS ENGINE ---
|
||||
$io->title("Accessibility Console - Static Analysis");
|
||||
$io->writeln("<fg=gray>Configuration loaded from:</> <fg=cyan>$configPath</>");
|
||||
$io->writeln("<fg=gray>Rule Level:</> <fg=yellow>$level</>");
|
||||
if ($format === 'console') {
|
||||
$io->title("Accessibility Console - Static Analysis");
|
||||
$io->writeln("<fg=gray>Configuration loaded from:</> <fg=cyan>$configPath</>");
|
||||
$io->writeln("<fg=gray>Rule Level:</> <fg=yellow>$level</>");
|
||||
if ($activePreset !== null) {
|
||||
$io->writeln("<fg=gray>Compliance Preset:</> <fg=magenta>" . $activePreset->getName() . " (" . $activePreset->getDescription() . ")</>");
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve paths to scan
|
||||
$paths = $config->getPaths();
|
||||
@@ -87,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;
|
||||
}
|
||||
@@ -128,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;
|
||||
@@ -196,35 +287,172 @@ 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') {
|
||||
$formatter = new JsonFormatter();
|
||||
} elseif ($format === 'github') {
|
||||
$formatter = new GithubFormatter();
|
||||
} elseif ($format === 'xml') {
|
||||
$formatter = new XmlFormatter();
|
||||
} elseif ($format === 'markdown') {
|
||||
$formatter = new MarkdownFormatter();
|
||||
} elseif ($format === 'csv') {
|
||||
$formatter = new CsvFormatter();
|
||||
} elseif ($format === 'gitlab') {
|
||||
$formatter = new GitLabCodeQualityFormatter();
|
||||
} elseif ($format === 'sarif') {
|
||||
$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");
|
||||
$color = $score >= 90 ? 'green' : ($score >= 70 ? 'yellow' : 'red');
|
||||
$io->writeln(sprintf("Health Score: <fg=%s>%d/100</>", $color, $score));
|
||||
$io->writeln(sprintf(" - Screen Reader / Visual Impact: <fg=cyan>%d%%</>", $metrics['visualImpact']));
|
||||
$io->writeln(sprintf(" - Keyboard / Motor Impact: <fg=cyan>%d%%</>", $metrics['motorImpact']));
|
||||
$io->writeln(sprintf(" - Cognitive / Distraction Impact: <fg=cyan>%d%%</>", $metrics['cognitiveImpact']));
|
||||
if (!empty($suppressedLog)) {
|
||||
$io->writeln(sprintf(" - Inline Suppressed Violations: <fg=yellow>%d</>", count($suppressedLog)));
|
||||
}
|
||||
$io->newLine();
|
||||
}
|
||||
|
||||
// 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');
|
||||
|
||||
$errorCount = 0;
|
||||
$warningCount = 0;
|
||||
foreach ($violations as $v) {
|
||||
if ($v->severity === Severity::CRITICAL || $v->severity === Severity::ERROR) {
|
||||
$errorCount++;
|
||||
} elseif ($v->severity === Severity::WARNING) {
|
||||
$warningCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$qualityGateFailed = false;
|
||||
/** @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) {
|
||||
$qualityGateFailed = true;
|
||||
$gateFailures[] = sprintf("Accessibility score (%d/100) is lower than the minimum required threshold of %d/100.", $score, $minScore);
|
||||
}
|
||||
}
|
||||
|
||||
if ($maxWarningsOption !== null && is_numeric($maxWarningsOption)) {
|
||||
$maxWarnings = (int)$maxWarningsOption;
|
||||
if ($warningCount > $maxWarnings) {
|
||||
$qualityGateFailed = true;
|
||||
$gateFailures[] = sprintf("Warning count (%d) exceeds the maximum allowed limit of %d.", $warningCount, $maxWarnings);
|
||||
}
|
||||
}
|
||||
|
||||
if (is_string($failOnOption)) {
|
||||
$failOn = strtolower($failOnOption);
|
||||
if ($failOn === 'error') {
|
||||
$exitCode = ($errorCount > 0) ? Command::FAILURE : Command::SUCCESS;
|
||||
} elseif ($failOn === 'warning') {
|
||||
$exitCode = ($errorCount > 0 || $warningCount > 0) ? Command::FAILURE : Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
|
||||
if ($qualityGateFailed) {
|
||||
$io->newLine();
|
||||
$io->error("CI/CD Quality Gate Failed:\n- " . implode("\n- ", $gateFailures));
|
||||
$exitCode = Command::FAILURE;
|
||||
}
|
||||
|
||||
// Export report if --report is specified
|
||||
$reportPath = $input->getOption('report');
|
||||
if (is_string($reportPath) && $reportPath !== '') {
|
||||
$extension = pathinfo($reportPath, PATHINFO_EXTENSION);
|
||||
if ($extension === 'json') {
|
||||
$serialized = [];
|
||||
foreach ($violations as $v) {
|
||||
$serialized[] = $v->toArray();
|
||||
}
|
||||
file_put_contents($reportPath, json_encode($serialized, JSON_PRETTY_PRINT));
|
||||
} else {
|
||||
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
|
||||
// Map violations into page format
|
||||
$mappedViolations = ['Static Analysis' => $violations];
|
||||
file_put_contents($reportPath, $reporter->render($mappedViolations, 'Static Analysis'));
|
||||
}
|
||||
$io->success("Report saved to: $reportPath");
|
||||
$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 !== '') {
|
||||
file_put_contents($badgePath, BadgeGenerator::generateScoreBadge($score));
|
||||
$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;
|
||||
}
|
||||
|
||||
@@ -279,9 +507,6 @@ class ScanCommand extends Command
|
||||
|
||||
while (!empty($queue) && count($visited) < $maxPages) {
|
||||
$current = array_shift($queue);
|
||||
if (!is_array($current)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$url = $current['url'];
|
||||
$depth = (int)$current['depth'];
|
||||
@@ -418,20 +643,156 @@ class ScanCommand extends Command
|
||||
|
||||
$reportPath = $input->getOption('report');
|
||||
if (is_string($reportPath) && $reportPath !== '') {
|
||||
$extension = pathinfo($reportPath, PATHINFO_EXTENSION);
|
||||
if ($extension === 'json') {
|
||||
$serialized = [];
|
||||
foreach ($results as $url => $violations) {
|
||||
$serialized[$url] = array_map(fn($v) => $v->toArray(), $violations);
|
||||
}
|
||||
file_put_contents($reportPath, json_encode($serialized, JSON_PRETTY_PRINT));
|
||||
} else {
|
||||
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
|
||||
file_put_contents($reportPath, $reporter->render($results, $target));
|
||||
$allViolations = [];
|
||||
foreach ($results as $urlViolations) {
|
||||
$allViolations = array_merge($allViolations, $urlViolations);
|
||||
}
|
||||
$io->success("Report saved to: $reportPath");
|
||||
$this->exportReport($reportPath, $allViolations, $target, $io, $results);
|
||||
}
|
||||
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Export violations to various file formats (HTML, JSON, SARIF, XML/JUnit, PDF, Excel).
|
||||
*
|
||||
* @param string $reportPath
|
||||
* @param \YakNet\AccessibilityConsole\Core\Violation[] $violations
|
||||
* @param string $targetName
|
||||
* @param SymfonyStyle $io
|
||||
* @param array<string, \YakNet\AccessibilityConsole\Core\Violation[]>|null $pageResults
|
||||
*/
|
||||
private function exportReport(
|
||||
string $reportPath,
|
||||
array $violations,
|
||||
string $targetName,
|
||||
SymfonyStyle $io,
|
||||
?array $pageResults = null
|
||||
): void {
|
||||
$extension = strtolower(pathinfo($reportPath, PATHINFO_EXTENSION));
|
||||
|
||||
if ($extension === 'json') {
|
||||
if ($pageResults !== null) {
|
||||
$serialized = [];
|
||||
foreach ($pageResults as $url => $pageViolations) {
|
||||
$serialized[$url] = array_map(fn($v) => $v->toArray(), $pageViolations);
|
||||
}
|
||||
} else {
|
||||
$serialized = [];
|
||||
foreach ($violations as $v) {
|
||||
$serialized[] = $v->toArray();
|
||||
}
|
||||
}
|
||||
file_put_contents($reportPath, (string)json_encode($serialized, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
|
||||
} 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));
|
||||
} elseif ($extension === 'pdf') {
|
||||
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
|
||||
$serialized = [];
|
||||
foreach ($violations as $v) {
|
||||
$serialized[] = $v->toArray();
|
||||
}
|
||||
$scanResult = [
|
||||
'score' => $metrics['score'],
|
||||
'violations' => $serialized,
|
||||
];
|
||||
file_put_contents($reportPath, PdfReportGenerator::generatePdf($scanResult, $targetName));
|
||||
} elseif ($extension === 'xlsx' || $extension === 'xls') {
|
||||
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
|
||||
$serialized = [];
|
||||
foreach ($violations as $v) {
|
||||
$serialized[] = $v->toArray();
|
||||
}
|
||||
$scanResult = [
|
||||
'score' => $metrics['score'],
|
||||
'violations' => $serialized,
|
||||
];
|
||||
file_put_contents($reportPath, ExcelReportExporter::exportExcel($scanResult, $targetName));
|
||||
} else {
|
||||
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
|
||||
$mapped = $pageResults ?? [$targetName => $violations];
|
||||
file_put_contents($reportPath, $reporter->render($mapped, $targetName));
|
||||
}
|
||||
|
||||
$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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Console\Command;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use YakNet\AccessibilityConsole\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\Presets\PresetRegistry;
|
||||
use YakNet\AccessibilityConsole\Rules\RuleLevels;
|
||||
|
||||
class VpatCommand extends Command
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Console\Command;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputArgument;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Input\InputOption;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use YakNet\AccessibilityConsole\Core\Analyser;
|
||||
use YakNet\AccessibilityConsole\Core\BaselineManager;
|
||||
use YakNet\AccessibilityConsole\Core\Config;
|
||||
use YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator;
|
||||
use YakNet\AccessibilityConsole\Core\Scanner;
|
||||
use YakNet\AccessibilityConsole\Reporting\ConsoleFormatter;
|
||||
use YakNet\AccessibilityConsole\Rules\RuleLevels;
|
||||
|
||||
class WatchCommand extends Command
|
||||
{
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->setName('watch')
|
||||
->setDescription('Continuously watch templates and files for changes and automatically re-scan')
|
||||
->addArgument('target', InputArgument::OPTIONAL, 'The file or directory path to watch (defaults to config paths)')
|
||||
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to configuration file (default: a11y.yaml)')
|
||||
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-5)')
|
||||
->addOption('interval', 'i', InputOption::VALUE_REQUIRED, 'Watch poll interval in seconds', '1')
|
||||
->addOption('max-iterations', null, InputOption::VALUE_REQUIRED, 'Max loop iterations (used for testing/debugging)');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
|
||||
$configPathOption = $input->getOption('config');
|
||||
$configPath = is_string($configPathOption) ? $configPathOption : getcwd() . '/a11y.yaml';
|
||||
$config = Config::fromYaml($configPath);
|
||||
|
||||
$levelOption = $input->getOption('level');
|
||||
$level = is_numeric($levelOption) ? (int)$levelOption : $config->getLevel();
|
||||
|
||||
$target = $input->getArgument('target');
|
||||
$paths = $config->getPaths();
|
||||
if (is_string($target) && $target !== '') {
|
||||
$paths = [$target];
|
||||
}
|
||||
|
||||
$intervalOption = $input->getOption('interval');
|
||||
$interval = is_numeric($intervalOption) ? (int)$intervalOption : 1;
|
||||
if ($interval < 1) {
|
||||
$interval = 1;
|
||||
}
|
||||
|
||||
$maxIterationsOption = $input->getOption('max-iterations');
|
||||
$maxIterations = is_numeric($maxIterationsOption) ? (int)$maxIterationsOption : null;
|
||||
|
||||
$io->title("Accessibility Console - Real-Time Watch Mode");
|
||||
$io->writeln("<fg=gray>Watching paths:</> <fg=cyan>" . implode(', ', $paths) . "</>");
|
||||
$io->writeln("<fg=gray>Rule Level:</> <fg=yellow>$level</>");
|
||||
$io->writeln("<fg=gray>Poll Interval:</> <fg=yellow>{$interval}s</>");
|
||||
$io->note("Press Ctrl+C to stop watching.");
|
||||
|
||||
// Build Scanner
|
||||
$scanner = new Scanner();
|
||||
$rules = RuleLevels::getRulesForLevel($level);
|
||||
foreach ($rules as $rule) {
|
||||
$scanner->addRule($rule);
|
||||
}
|
||||
|
||||
$analyser = new Analyser($config, $scanner, new BaselineManager());
|
||||
|
||||
// Perform initial scan
|
||||
$io->section("Initial Scan");
|
||||
$this->runScanAndPrint($analyser, $paths, $io);
|
||||
|
||||
// Map existing files to their last modified timestamp
|
||||
$fileMtimes = $this->collectFileMtimes($paths, $config->getExcludePaths());
|
||||
|
||||
$iteration = 0;
|
||||
while (true) {
|
||||
if ($maxIterations !== null && $iteration >= $maxIterations) {
|
||||
break;
|
||||
}
|
||||
$iteration++;
|
||||
|
||||
sleep($interval);
|
||||
|
||||
$currentMtimes = $this->collectFileMtimes($paths, $config->getExcludePaths());
|
||||
$changedFiles = $this->detectChangedFiles($fileMtimes, $currentMtimes);
|
||||
|
||||
if (!empty($changedFiles)) {
|
||||
$fileMtimes = $currentMtimes;
|
||||
$timestamp = date('H:i:s');
|
||||
$io->newLine();
|
||||
$io->writeln(sprintf(
|
||||
"<fg=yellow>[%s]</> Change detected in <fg=cyan>%s</>. Re-scanning...",
|
||||
$timestamp,
|
||||
basename($changedFiles[0]) . (count($changedFiles) > 1 ? ' (+' . (count($changedFiles) - 1) . ' more)' : '')
|
||||
));
|
||||
|
||||
// Re-scan changed files or paths
|
||||
$this->runScanAndPrint($analyser, $changedFiles, $io);
|
||||
}
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Analyser $analyser
|
||||
* @param string[] $paths
|
||||
* @param SymfonyStyle $io
|
||||
*/
|
||||
private function runScanAndPrint(Analyser $analyser, array $paths, SymfonyStyle $io): void
|
||||
{
|
||||
$start = microtime(true);
|
||||
$result = $analyser->analyse($paths);
|
||||
$elapsed = round(microtime(true) - $start, 3);
|
||||
|
||||
$violations = $result['violations'];
|
||||
$formatter = new ConsoleFormatter();
|
||||
$formatter->format($violations, $result['baselinedCount'], $io);
|
||||
|
||||
$metrics = AccessibilityScoreCalculator::calculate($violations);
|
||||
$score = $metrics['score'];
|
||||
$color = $score >= 90 ? 'green' : ($score >= 70 ? 'yellow' : 'red');
|
||||
|
||||
$io->writeln(sprintf(
|
||||
"Health Score: <fg=%s;options=bold>%d/100</> | Scan time: <fg=gray>%ss</>",
|
||||
$color,
|
||||
$score,
|
||||
$elapsed
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $paths
|
||||
* @param string[] $excludePaths
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public function collectFileMtimes(array $paths, array $excludePaths): array
|
||||
{
|
||||
$mtimes = [];
|
||||
$extensions = ['php', 'html', 'twig', 'blade.php'];
|
||||
|
||||
foreach ($paths as $path) {
|
||||
if (is_file($path)) {
|
||||
$mtimes[$path] = (int)filemtime($path);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!is_dir($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$iterator = new \RecursiveIteratorIterator(
|
||||
new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS)
|
||||
);
|
||||
|
||||
/** @var \SplFileInfo $file */
|
||||
foreach ($iterator as $file) {
|
||||
if (!$file->isFile()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$filename = $file->getFilename();
|
||||
$ext = $file->getExtension();
|
||||
$isMatching = in_array($ext, ['php', 'html', 'twig'], true) || str_ends_with($filename, '.blade.php');
|
||||
|
||||
if (!$isMatching) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$filePath = (string)$file->getRealPath();
|
||||
$excluded = false;
|
||||
foreach ($excludePaths as $ex) {
|
||||
if (str_contains(str_replace('\\', '/', $filePath), '/' . trim($ex, '/') . '/')) {
|
||||
$excluded = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$excluded) {
|
||||
$mtimes[$filePath] = (int)$file->getMTime();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $mtimes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, int> $oldMtimes
|
||||
* @param array<string, int> $newMtimes
|
||||
* @return string[]
|
||||
*/
|
||||
public function detectChangedFiles(array $oldMtimes, array $newMtimes): array
|
||||
{
|
||||
$changed = [];
|
||||
|
||||
foreach ($newMtimes as $file => $mtime) {
|
||||
if (!isset($oldMtimes[$file]) || $oldMtimes[$file] !== $mtime) {
|
||||
$changed[] = $file;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($oldMtimes as $file => $mtime) {
|
||||
if (!isset($newMtimes[$file])) {
|
||||
$changed[] = $file;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($changed));
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,17 @@ abstract class AbstractRule
|
||||
return 4;
|
||||
}
|
||||
|
||||
protected function createViolation(string $message, \DOMElement $element): Violation
|
||||
public function getId(): string
|
||||
{
|
||||
return (new \ReflectionClass($this))->getShortName();
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
protected function createViolation(string $message, \DOMElement $element, ?string $suggestion = null): Violation
|
||||
{
|
||||
$doc = $element->ownerDocument;
|
||||
$html = '';
|
||||
@@ -36,11 +46,12 @@ abstract class AbstractRule
|
||||
}
|
||||
|
||||
return new Violation(
|
||||
ruleId: (new \ReflectionClass($this))->getShortName(),
|
||||
ruleId: $this->getId(),
|
||||
message: $message,
|
||||
severity: $this->getSeverity(),
|
||||
standard: $this->getStandard(),
|
||||
htmlSnippet: $html
|
||||
htmlSnippet: $html,
|
||||
fixSuggestion: $suggestion
|
||||
);
|
||||
}
|
||||
}
|
||||
+93
-93
@@ -5,6 +5,10 @@ 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;
|
||||
|
||||
class Analyser
|
||||
@@ -12,13 +16,31 @@ class Analyser
|
||||
private Config $config;
|
||||
private Scanner $scanner;
|
||||
private BaselineManager $baselineManager;
|
||||
private TemplatePreprocessor $templatePreprocessor;
|
||||
private PreciseElementLocator $elementLocator;
|
||||
private InlineSuppressionParser $suppressionParser;
|
||||
private ?ScanCache $cache;
|
||||
private string $projectRoot;
|
||||
|
||||
public function __construct(?Config $config = null, ?Scanner $scanner = null, ?BaselineManager $baselineManager = null)
|
||||
{
|
||||
/** @var array<int, array{file: string, line: int, ruleId: string, reason: string}> */
|
||||
private array $suppressedAuditLog = [];
|
||||
|
||||
public function __construct(
|
||||
?Config $config = null,
|
||||
?Scanner $scanner = null,
|
||||
?BaselineManager $baselineManager = null,
|
||||
?TemplatePreprocessor $templatePreprocessor = 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) : '.';
|
||||
@@ -39,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;
|
||||
@@ -56,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;
|
||||
}
|
||||
@@ -102,36 +122,70 @@ class Analyser
|
||||
|
||||
$violations = [];
|
||||
$baselinedCount = 0;
|
||||
$this->suppressedAuditLog = [];
|
||||
|
||||
foreach ($filesToScan as $index => $file) {
|
||||
if ($onProgress) {
|
||||
$onProgress($file, $index + 1, $totalFiles);
|
||||
}
|
||||
|
||||
$content = @file_get_contents($file);
|
||||
if ($content === false || trim($content) === '') {
|
||||
$rawContent = @file_get_contents($file);
|
||||
if ($rawContent === false || trim($rawContent) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Scan file content
|
||||
try {
|
||||
$fileViolations = $this->scanner->scan($content);
|
||||
} catch (\Throwable $e) {
|
||||
// Skip if parsing failed dramatically
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
$relativeFile = $this->makePathRelative($file);
|
||||
|
||||
// Parse inline suppression directives (<!-- a11y-disable... -->)
|
||||
$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);
|
||||
}
|
||||
|
||||
foreach ($fileViolations as $violation) {
|
||||
// Find line number using line-by-line helper
|
||||
$line = $this->locateLineInContent($content, $violation->htmlSnippet);
|
||||
|
||||
// Store location in violation
|
||||
$violation->location = [
|
||||
'file' => $relativeFile,
|
||||
'line' => $line
|
||||
];
|
||||
$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' => $lineNum,
|
||||
'ruleId' => $violation->ruleId,
|
||||
'reason' => $suppressionReason,
|
||||
];
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if ignored in baseline
|
||||
if ($this->baselineManager->isIgnored($relativeFile, $violation->ruleId, $violation->htmlSnippet)) {
|
||||
@@ -141,6 +195,8 @@ class Analyser
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->cache?->save();
|
||||
|
||||
return [
|
||||
'violations' => $violations,
|
||||
@@ -148,6 +204,16 @@ class Analyser
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Audit trail of violations suppressed via inline comments during the latest analysis run.
|
||||
*
|
||||
* @return array<int, array{file: string, line: int, ruleId: string, reason: string}>
|
||||
*/
|
||||
public function getSuppressedAuditLog(): array
|
||||
{
|
||||
return $this->suppressedAuditLog;
|
||||
}
|
||||
|
||||
public function getBaselineManager(): BaselineManager
|
||||
{
|
||||
return $this->baselineManager;
|
||||
@@ -194,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 */
|
||||
@@ -221,70 +287,4 @@ class Analyser
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
private function locateLineInContent(string $content, string $snippet): int
|
||||
{
|
||||
$replaced = preg_replace('/\s+/', ' ', $snippet);
|
||||
$cleanSnippet = is_string($replaced) ? trim($replaced) : '';
|
||||
if ($cleanSnippet === '') {
|
||||
return 1;
|
||||
}
|
||||
|
||||
$searchSnippet = mb_strlen($cleanSnippet) > 150 ? mb_substr($cleanSnippet, 0, 150) : $cleanSnippet;
|
||||
$lines = explode("\n", $content);
|
||||
|
||||
// 1. Exact match pass
|
||||
foreach ($lines as $index => $line) {
|
||||
$replacedLine = preg_replace('/\s+/', ' ', $line);
|
||||
$cleanLine = is_string($replacedLine) ? trim($replacedLine) : '';
|
||||
if (str_contains($cleanLine, $searchSnippet)) {
|
||||
return $index + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Parse snippet to find tag and attributes for fuzzy match pass
|
||||
preg_match('/<([a-zA-Z0-9]+)/', $snippet, $matches);
|
||||
$tagName = $matches[1] ?? null;
|
||||
if (!$tagName) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
preg_match_all('/([a-zA-Z0-9-]+)=["\']([^"\']*)["\']/', $snippet, $attrMatches, PREG_SET_ORDER);
|
||||
$attributes = [];
|
||||
foreach ($attrMatches as $match) {
|
||||
$attributes[$match[1]] = $match[2];
|
||||
}
|
||||
|
||||
$bestLine = 1;
|
||||
$maxScore = 0;
|
||||
|
||||
foreach ($lines as $index => $line) {
|
||||
$replacedLine = preg_replace('/\s+/', ' ', $line);
|
||||
$cleanLine = is_string($replacedLine) ? trim($replacedLine) : '';
|
||||
|
||||
if (!str_contains(strtolower($cleanLine), '<' . strtolower($tagName))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$score = 1.0;
|
||||
if (in_array(strtolower($tagName), ['html', 'head', 'body', 'title'], true)) {
|
||||
$score += 1.0;
|
||||
}
|
||||
|
||||
foreach ($attributes as $name => $value) {
|
||||
if (str_contains($cleanLine, "$name=\"$value\"") || str_contains($cleanLine, "$name='$value'")) {
|
||||
$score += 2.0;
|
||||
} elseif (str_contains($cleanLine, $name . '=')) {
|
||||
$score += 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
if ($score > $maxScore) {
|
||||
$maxScore = $score;
|
||||
$bestLine = $index + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return $bestLine;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core\Baseline;
|
||||
|
||||
class FuzzyBaselineMatcher
|
||||
{
|
||||
/**
|
||||
* Determine if two HTML snippets are fuzzy matched.
|
||||
*
|
||||
* @param string $snippetA
|
||||
* @param string $snippetB
|
||||
* @return bool
|
||||
*/
|
||||
public static function match(string $snippetA, string $snippetB): bool
|
||||
{
|
||||
$normA = self::normalize($snippetA);
|
||||
$normB = self::normalize($snippetB);
|
||||
|
||||
if ($normA === '' || $normB === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $normA === $normB;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize HTML snippet by stripping formatting, converting to lowercase,
|
||||
* and sorting attributes.
|
||||
*
|
||||
* @param string $html
|
||||
* @return string
|
||||
*/
|
||||
public static function normalize(string $html): string
|
||||
{
|
||||
$html = trim($html);
|
||||
if ($html === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Parse using simple regex to sort attributes and lowercase tag
|
||||
if (preg_match('/^<([a-zA-Z0-9:-]+)(.*?)>$/s', $html, $matches)) {
|
||||
$tag = strtolower($matches[1]);
|
||||
$attrsContent = $matches[2];
|
||||
|
||||
// Parse attributes
|
||||
preg_match_all('/([a-zA-Z0-9:-]+)=["\'](.*?)["\']/s', $attrsContent, $attrMatches, PREG_SET_ORDER);
|
||||
|
||||
$attrs = [];
|
||||
foreach ($attrMatches as $match) {
|
||||
$attrs[strtolower($match[1])] = trim($match[2]);
|
||||
}
|
||||
ksort($attrs);
|
||||
|
||||
$attrStr = '';
|
||||
foreach ($attrs as $name => $value) {
|
||||
$attrStr .= sprintf(' %s="%s"', $name, $value);
|
||||
}
|
||||
|
||||
return sprintf('<%s%s>', $tag, $attrStr);
|
||||
}
|
||||
|
||||
// Fallback: Strip all whitespace and lowercase
|
||||
$cleaned = preg_replace('/\s+/', '', $html) ?: '';
|
||||
return strtolower($cleaned);
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,12 @@ class BaselineManager
|
||||
}
|
||||
|
||||
foreach ($data['violations'] as $item) {
|
||||
if (isset($item['file'], $item['ruleId'], $item['htmlSnippet'])) {
|
||||
if (!is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
if (isset($item['file'], $item['ruleId'], $item['htmlSnippet'])
|
||||
&& is_string($item['file']) && is_string($item['ruleId']) && is_string($item['htmlSnippet'])
|
||||
) {
|
||||
$key = $this->calculateKey($item['file'], $item['ruleId'], $item['htmlSnippet']);
|
||||
$this->ignoredKeys[$key] = true;
|
||||
}
|
||||
@@ -82,9 +87,9 @@ class BaselineManager
|
||||
|
||||
private function calculateKey(string $file, string $ruleId, string $htmlSnippet): string
|
||||
{
|
||||
// Normalize whitespaces and trim to prevent minor formatting updates from breaking baseline
|
||||
$normalizedSnippet = preg_replace('/\s+/', ' ', trim($htmlSnippet));
|
||||
if ($normalizedSnippet === null) {
|
||||
// Normalize snippet using fuzzy baseline matcher
|
||||
$normalizedSnippet = \YakNet\AccessibilityConsole\Core\Baseline\FuzzyBaselineMatcher::normalize($htmlSnippet);
|
||||
if ($normalizedSnippet === '') {
|
||||
$normalizedSnippet = trim($htmlSnippet);
|
||||
}
|
||||
|
||||
|
||||
+57
-5
@@ -35,6 +35,7 @@ class Config
|
||||
try {
|
||||
$content = \Symfony\Component\Yaml\Yaml::parseFile($path);
|
||||
if (is_array($content)) {
|
||||
/** @var array<string, mixed> $content */
|
||||
return new self($content);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
@@ -56,7 +57,7 @@ class Config
|
||||
{
|
||||
$paths = $this->get('paths');
|
||||
if (is_array($paths)) {
|
||||
return $paths;
|
||||
return array_values(array_filter($paths, 'is_string'));
|
||||
}
|
||||
if (is_string($paths)) {
|
||||
return [$paths];
|
||||
@@ -71,7 +72,7 @@ class Config
|
||||
{
|
||||
$exclude = $this->get('exclude_paths');
|
||||
if (is_array($exclude)) {
|
||||
return $exclude;
|
||||
return array_values(array_filter($exclude, 'is_string'));
|
||||
}
|
||||
if (is_string($exclude)) {
|
||||
return [$exclude];
|
||||
@@ -108,10 +109,10 @@ class Config
|
||||
|
||||
if (is_array($rules)) {
|
||||
if (isset($rules['include']) && is_array($rules['include'])) {
|
||||
$include = $rules['include'];
|
||||
$include = array_values(array_filter($rules['include'], 'is_string'));
|
||||
}
|
||||
if (isset($rules['exclude']) && is_array($rules['exclude'])) {
|
||||
$exclude = $rules['exclude'];
|
||||
$exclude = array_values(array_filter($rules['exclude'], 'is_string'));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +124,57 @@ class Config
|
||||
|
||||
public function getGeminiApiKey(): ?string
|
||||
{
|
||||
return $this->get('gemini_api_key') ?? $_ENV['GEMINI_API_KEY'] ?? getenv('GEMINI_API_KEY') ?: null;
|
||||
$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<string, mixed>
|
||||
*/
|
||||
public function getPolicyConfig(): array
|
||||
{
|
||||
$policy = $this->get('policy', []);
|
||||
if (!is_array($policy)) {
|
||||
return [];
|
||||
}
|
||||
/** @var array<string, mixed> $policy */
|
||||
return $policy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notification webhook configuration block from a11y.yaml.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getNotificationsConfig(): array
|
||||
{
|
||||
$notifications = $this->get('notifications', []);
|
||||
if (!is_array($notifications)) {
|
||||
return [];
|
||||
}
|
||||
/** @var array<string, mixed> $notifications */
|
||||
return $notifications;
|
||||
}
|
||||
|
||||
/**
|
||||
* File extensions to include during directory scans.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
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'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core\Config;
|
||||
|
||||
class SmartPresetBuilder
|
||||
{
|
||||
/**
|
||||
* Analyze HTML content features to suggest rules presets.
|
||||
*
|
||||
* @param string $html
|
||||
* @return array{suggestedLevel: int, tagsCheckedCount: array<string, int>, recommendedExclusions: string[]}
|
||||
*/
|
||||
public function analyze(string $html): array
|
||||
{
|
||||
$tagsChecked = ['img' => 0, 'form' => 0, 'table' => 0, 'svg' => 0, 'video' => 0];
|
||||
|
||||
foreach (array_keys($tagsChecked) as $tag) {
|
||||
$tagsChecked[$tag] = substr_count(strtolower($html), '<' . $tag);
|
||||
}
|
||||
|
||||
// Calculate recommendations
|
||||
$suggestedLevel = 3; // Standard baseline
|
||||
if ($tagsChecked['form'] > 5 || $tagsChecked['table'] > 3) {
|
||||
$suggestedLevel = 4; // Higher complexity requires more strict tests
|
||||
}
|
||||
if ($tagsChecked['video'] > 0) {
|
||||
$suggestedLevel = 5; // Video elements need caption checks, standard level 5
|
||||
}
|
||||
|
||||
$exclusions = [];
|
||||
if ($tagsChecked['svg'] === 0) {
|
||||
$exclusions[] = 'WCAG_1_1_1_SVG';
|
||||
}
|
||||
if ($tagsChecked['video'] === 0) {
|
||||
$exclusions[] = 'WCAG_1_2_2_VIDEO_TRACK';
|
||||
}
|
||||
|
||||
return [
|
||||
'suggestedLevel' => $suggestedLevel,
|
||||
'tagsCheckedCount' => $tagsChecked,
|
||||
'recommendedExclusions' => $exclusions,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core\Container;
|
||||
|
||||
use DI\ContainerBuilder;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use YakNet\AccessibilityConsole\Core\Config;
|
||||
use YakNet\AccessibilityConsole\Core\Analyser;
|
||||
use YakNet\AccessibilityConsole\Core\Scanner;
|
||||
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
|
||||
{
|
||||
/**
|
||||
* Create and configure the PHP-DI container.
|
||||
*
|
||||
* @return ContainerInterface
|
||||
*/
|
||||
public static function create(): ContainerInterface
|
||||
{
|
||||
$builder = new ContainerBuilder();
|
||||
|
||||
$builder->addDefinitions([
|
||||
Config::class => function () {
|
||||
$configPath = getcwd() . '/a11y.yaml';
|
||||
return Config::fromYaml($configPath);
|
||||
},
|
||||
Scanner::class => function () {
|
||||
return new Scanner();
|
||||
},
|
||||
Analyser::class => function (ContainerInterface $c) {
|
||||
$config = $c->get(Config::class);
|
||||
$scanner = $c->get(Scanner::class);
|
||||
return new Analyser(
|
||||
$config instanceof Config ? $config : null,
|
||||
$scanner instanceof Scanner ? $scanner : null
|
||||
);
|
||||
},
|
||||
ScanCommand::class => function () {
|
||||
return new ScanCommand();
|
||||
},
|
||||
FixCommand::class => function () {
|
||||
return new FixCommand();
|
||||
},
|
||||
InitCommand::class => function () {
|
||||
return new InitCommand();
|
||||
},
|
||||
RulesCommand::class => function () {
|
||||
return new RulesCommand();
|
||||
},
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core\Diff;
|
||||
|
||||
use SebastianBergmann\Diff\Differ;
|
||||
use SebastianBergmann\Diff\Output\UnifiedDiffOutputBuilder;
|
||||
|
||||
class VisualDiffGenerator
|
||||
{
|
||||
private Differ $differ;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->differ = new Differ(new UnifiedDiffOutputBuilder("--- Original\n+++ Healed\n"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a colorized git-style unified diff string.
|
||||
*
|
||||
* @param string $original
|
||||
* @param string $fixed
|
||||
* @return string
|
||||
*/
|
||||
public function generate(string $original, string $fixed): string
|
||||
{
|
||||
$diff = $this->differ->diff($original, $fixed);
|
||||
$lines = explode("\n", $diff);
|
||||
|
||||
$colorized = [];
|
||||
foreach ($lines as $line) {
|
||||
if (str_starts_with($line, '+') && !str_starts_with($line, '+++')) {
|
||||
$colorized[] = "<fg=green>" . htmlspecialchars($line) . "</>";
|
||||
} elseif (str_starts_with($line, '-') && !str_starts_with($line, '---')) {
|
||||
$colorized[] = "<fg=red>" . htmlspecialchars($line) . "</>";
|
||||
} elseif (str_starts_with($line, '@@')) {
|
||||
$colorized[] = "<fg=cyan>" . htmlspecialchars($line) . "</>";
|
||||
} elseif (str_starts_with($line, '---') || str_starts_with($line, '+++')) {
|
||||
$colorized[] = "<fg=gray>" . htmlspecialchars($line) . "</>";
|
||||
} else {
|
||||
$colorized[] = htmlspecialchars($line);
|
||||
}
|
||||
}
|
||||
|
||||
return implode("\n", $colorized);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core\Locator;
|
||||
|
||||
class PreciseElementLocator
|
||||
{
|
||||
/**
|
||||
* Locate the exact line and column of an HTML snippet within file content.
|
||||
*
|
||||
* @param string $content Full file content
|
||||
* @param string $snippet HTML snippet of the violating element
|
||||
* @return array{line: int, column: int}
|
||||
*/
|
||||
public function locate(string $content, string $snippet): array
|
||||
{
|
||||
$cleanSnippet = trim(preg_replace('/\s+/', ' ', $snippet) ?? '');
|
||||
if ($cleanSnippet === '') {
|
||||
return ['line' => 1, 'column' => 1];
|
||||
}
|
||||
|
||||
// 1. Exact substring match pass
|
||||
$exactPos = strpos($content, $snippet);
|
||||
if ($exactPos !== false) {
|
||||
return $this->getLineAndColumn($content, $exactPos);
|
||||
}
|
||||
|
||||
// 2. Normalized whitespace search pass
|
||||
$lines = explode("\n", $content);
|
||||
$searchSnippet = mb_strlen($cleanSnippet) > 120 ? mb_substr($cleanSnippet, 0, 120) : $cleanSnippet;
|
||||
|
||||
foreach ($lines as $index => $line) {
|
||||
$cleanLine = trim(preg_replace('/\s+/', ' ', $line) ?? '');
|
||||
if ($cleanLine !== '' && str_contains($cleanLine, $searchSnippet)) {
|
||||
$col = strpos($line, mb_substr($searchSnippet, 0, 20));
|
||||
return [
|
||||
'line' => $index + 1,
|
||||
'column' => ($col !== false) ? $col + 1 : 1
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Tag & Attribute Token Match Pass
|
||||
preg_match('/<([a-zA-Z0-9:-]+)/', $snippet, $tagMatch);
|
||||
$tagName = strtolower($tagMatch[1] ?? '');
|
||||
|
||||
if ($tagName !== '') {
|
||||
preg_match_all('/([a-zA-Z0-9_:-]+)=["\']([^"\']*)["\']/', $snippet, $attrMatches, PREG_SET_ORDER);
|
||||
$attributes = [];
|
||||
foreach ($attrMatches as $m) {
|
||||
$attributes[$m[1]] = $m[2];
|
||||
}
|
||||
|
||||
$bestLine = 1;
|
||||
$bestCol = 1;
|
||||
$maxScore = 0.0;
|
||||
|
||||
foreach ($lines as $index => $line) {
|
||||
$lineLower = strtolower($line);
|
||||
$tagStr = '<' . $tagName;
|
||||
|
||||
if (!str_contains($lineLower, $tagStr)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$score = 1.0;
|
||||
|
||||
foreach ($attributes as $attrName => $attrVal) {
|
||||
if (str_contains($line, "$attrName=\"$attrVal\"") || str_contains($line, "$attrName='$attrVal'")) {
|
||||
$score += 3.0;
|
||||
} elseif (str_contains($line, "$attrName=")) {
|
||||
$score += 1.0;
|
||||
}
|
||||
}
|
||||
|
||||
if ($score > $maxScore) {
|
||||
$maxScore = $score;
|
||||
$bestLine = $index + 1;
|
||||
$col = strpos($lineLower, $tagStr);
|
||||
$bestCol = ($col !== false) ? $col + 1 : 1;
|
||||
}
|
||||
}
|
||||
|
||||
if ($maxScore > 0) {
|
||||
return ['line' => $bestLine, 'column' => $bestCol];
|
||||
}
|
||||
}
|
||||
|
||||
return ['line' => 1, 'column' => 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{line: int, column: int}
|
||||
*/
|
||||
private function getLineAndColumn(string $content, int $offset): array
|
||||
{
|
||||
if ($offset <= 0) {
|
||||
return ['line' => 1, 'column' => 1];
|
||||
}
|
||||
|
||||
$before = substr($content, 0, $offset);
|
||||
$line = substr_count($before, "\n") + 1;
|
||||
$lastNewline = strrpos($before, "\n");
|
||||
$column = ($lastNewline === false) ? $offset + 1 : $offset - $lastNewline;
|
||||
|
||||
return ['line' => $line, 'column' => $column];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core\Metrics;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
use YakNet\AccessibilityConsole\Core\Severity;
|
||||
|
||||
class AccessibilityScoreCalculator
|
||||
{
|
||||
/**
|
||||
* Calculate accessibility score (0-100) and user impact summaries.
|
||||
*
|
||||
* @param Violation[] $violations
|
||||
* @return array{score: int, visualImpact: int, motorImpact: int, cognitiveImpact: int}
|
||||
*/
|
||||
public static function calculate(array $violations): array
|
||||
{
|
||||
$score = 100;
|
||||
|
||||
$visualCount = 0;
|
||||
$motorCount = 0;
|
||||
$cognitiveCount = 0;
|
||||
|
||||
foreach ($violations as $v) {
|
||||
// Deduct points based on severity
|
||||
$deduction = 3; // Warning default
|
||||
if ($v->severity === Severity::CRITICAL) {
|
||||
$deduction = 15;
|
||||
} elseif ($v->severity === Severity::ERROR) {
|
||||
$deduction = 8;
|
||||
}
|
||||
$score -= $deduction;
|
||||
|
||||
// Map rule ID to disabled user groups impact
|
||||
$id = $v->ruleId;
|
||||
if (self::isVisual($id)) {
|
||||
$visualCount++;
|
||||
}
|
||||
if (self::isMotor($id)) {
|
||||
$motorCount++;
|
||||
}
|
||||
if (self::isCognitive($id)) {
|
||||
$cognitiveCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$score = max(0, $score);
|
||||
|
||||
// Normalize counts to percentage indicators of severity
|
||||
$total = count($violations);
|
||||
$visualImpact = $total > 0 ? (int)(($visualCount / $total) * 100) : 0;
|
||||
$motorImpact = $total > 0 ? (int)(($motorCount / $total) * 100) : 0;
|
||||
$cognitiveImpact = $total > 0 ? (int)(($cognitiveCount / $total) * 100) : 0;
|
||||
|
||||
return [
|
||||
'score' => $score,
|
||||
'visualImpact' => $visualImpact,
|
||||
'motorImpact' => $motorImpact,
|
||||
'cognitiveImpact' => $cognitiveImpact,
|
||||
];
|
||||
}
|
||||
|
||||
private static function isVisual(string $ruleId): bool
|
||||
{
|
||||
$visualKeywords = ['ALT', 'LABEL', 'TITLE', 'ARIA', 'LANG', 'CONTRAST', 'COLOR', 'TEXT', 'HEADING'];
|
||||
foreach ($visualKeywords as $key) {
|
||||
if (str_contains($ruleId, $key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function isMotor(string $ruleId): bool
|
||||
{
|
||||
$motorKeywords = ['ACCESSKEY', 'FOCUS', 'TABINDEX', 'KEYBOARD', 'LINK_JAVASCRIPT', 'AUTOFOCUS', 'SCROLLABLE'];
|
||||
foreach ($motorKeywords as $key) {
|
||||
if (str_contains($ruleId, $key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function isCognitive(string $ruleId): bool
|
||||
{
|
||||
$cognitiveKeywords = ['MARQUEE', 'BLINK', 'REFRESH', 'AUTOPLAY', 'AUTOCOMPLETE'];
|
||||
foreach ($cognitiveKeywords as $key) {
|
||||
if (str_contains($ruleId, $key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+71
-15
@@ -2,43 +2,99 @@
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
use YakNet\AccessibilityConsole\Rules\RuleExecutionStats;
|
||||
use YakNet\AccessibilityConsole\Rules\RuleInterface;
|
||||
|
||||
class RuleEngine
|
||||
{
|
||||
/** @var array<int, mixed> */
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
public function getRules(): array
|
||||
{
|
||||
return $this->rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run all registered rules against the DOMDocument using single-pass DOM traversal.
|
||||
*
|
||||
* @param DOMDocument $doc
|
||||
* @return Violation[]
|
||||
*/
|
||||
public function run(\DOMDocument $doc): array
|
||||
public function run(DOMDocument $doc): array
|
||||
{
|
||||
$allViolations = [];
|
||||
$docRules = [];
|
||||
$elementRules = [];
|
||||
|
||||
foreach ($this->rules as $rule) {
|
||||
if ($rule instanceof AbstractRule) {
|
||||
// Document-level rule (Core\AbstractRule style)
|
||||
$violations = $rule->check($doc);
|
||||
$allViolations = array_merge($allViolations, $violations);
|
||||
} elseif ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface) {
|
||||
// Element-level rule (Rules\RuleInterface style)
|
||||
$xpath = new \DOMXPath($doc);
|
||||
$elements = $xpath->query('//*');
|
||||
if ($elements !== false) {
|
||||
foreach ($elements as $element) {
|
||||
if ($element instanceof \DOMElement) {
|
||||
$violation = $rule->check($element);
|
||||
if ($violation) {
|
||||
$allViolations[] = $violation;
|
||||
}
|
||||
$docRules[] = $rule;
|
||||
} elseif ($rule instanceof RuleInterface) {
|
||||
$elementRules[] = $rule;
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 2. Run Element-level rules in a single DOM pass
|
||||
if (!empty($elementRules)) {
|
||||
$xpath = new DOMXPath($doc);
|
||||
$elements = $xpath->query('//*');
|
||||
|
||||
if ($elements !== false) {
|
||||
foreach ($elements as $element) {
|
||||
if (!$element instanceof DOMElement) {
|
||||
continue;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $allViolations;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core;
|
||||
|
||||
use ReflectionClass;
|
||||
use YakNet\AccessibilityConsole\Rules\RuleInterface;
|
||||
use YakNet\AccessibilityConsole\Rules\RuleLevels;
|
||||
|
||||
class RuleRegistry
|
||||
{
|
||||
/**
|
||||
* Validate an array of rule instances for ID uniqueness, interfaces, and validity.
|
||||
*
|
||||
* @param array<int, mixed> $rules
|
||||
* @return array{valid: bool, errors: array<int, string>, count: int}
|
||||
*/
|
||||
public static function validate(array $rules): array
|
||||
{
|
||||
$errors = [];
|
||||
$ids = [];
|
||||
|
||||
foreach ($rules as $rule) {
|
||||
if (!is_object($rule)) {
|
||||
$errors[] = "Non-object rule encountered in rule set.";
|
||||
continue;
|
||||
}
|
||||
|
||||
$className = get_class($rule);
|
||||
$reflection = new ReflectionClass($rule);
|
||||
|
||||
$isDocRule = $rule instanceof AbstractRule;
|
||||
$isElementRule = $rule instanceof RuleInterface;
|
||||
|
||||
if (!$isDocRule && !$isElementRule) {
|
||||
$errors[] = "Class {$className} does not implement RuleInterface or extend AbstractRule.";
|
||||
continue;
|
||||
}
|
||||
|
||||
$ruleId = method_exists($rule, 'getId') ? $rule->getId() : $reflection->getShortName();
|
||||
|
||||
if (isset($ids[$ruleId])) {
|
||||
$errors[] = "Duplicate Rule ID '{$ruleId}' detected across classes: {$ids[$ruleId]} and {$className}.";
|
||||
} else {
|
||||
$ids[$ruleId] = $className;
|
||||
}
|
||||
|
||||
if (!method_exists($rule, 'getStandard')) {
|
||||
$errors[] = "Rule {$className} is missing getStandard() method.";
|
||||
}
|
||||
|
||||
if (!method_exists($rule, 'getSeverity')) {
|
||||
$errors[] = "Rule {$className} is missing getSeverity() method.";
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'valid' => empty($errors),
|
||||
'errors' => $errors,
|
||||
'count' => count($rules),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get metadata for a specific rule instance.
|
||||
*
|
||||
* @param object $rule
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function getMetadata(object $rule): array
|
||||
{
|
||||
$reflection = new ReflectionClass($rule);
|
||||
$id = method_exists($rule, 'getId') ? $rule->getId() : $reflection->getShortName();
|
||||
$desc = method_exists($rule, 'getDescription') ? $rule->getDescription() : '';
|
||||
$standard = method_exists($rule, 'getStandard') ? $rule->getStandard()->value : 'A';
|
||||
$severity = method_exists($rule, 'getSeverity') ? $rule->getSeverity()->value : 'error';
|
||||
$level = method_exists($rule, 'getLevel') ? $rule->getLevel() : 4;
|
||||
|
||||
return [
|
||||
'id' => $id,
|
||||
'class' => $reflection->getName(),
|
||||
'shortName' => $reflection->getShortName(),
|
||||
'description' => $desc,
|
||||
'standard' => $standard,
|
||||
'severity' => $severity,
|
||||
'level' => $level,
|
||||
'type' => ($rule instanceof AbstractRule) ? 'document' : 'element',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,11 @@ class Scanner
|
||||
$this->engine->addRule($rule);
|
||||
}
|
||||
|
||||
public function getEngine(): RuleEngine
|
||||
{
|
||||
return $this->engine;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan HTML content for accessibility violations.
|
||||
*
|
||||
@@ -33,6 +38,10 @@ class Scanner
|
||||
]);
|
||||
$doc = $html5->loadHTML($html);
|
||||
|
||||
// Attach raw HTML property for syntax/token level analysis
|
||||
/** @phpstan-ignore-next-line */
|
||||
@$doc->rawHtml = $html;
|
||||
|
||||
return $this->engine->run($doc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core\SelfHealing;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
class LocalHealer
|
||||
{
|
||||
/**
|
||||
* Attempt to deterministically fix simple violations locally.
|
||||
*
|
||||
* @param Violation $violation
|
||||
* @return string|null
|
||||
*/
|
||||
public function heal(Violation $violation): ?string
|
||||
{
|
||||
$snippet = $violation->htmlSnippet;
|
||||
$ruleId = $violation->ruleId;
|
||||
|
||||
switch ($ruleId) {
|
||||
case 'WCAG_1_1_1_IMG_ALT':
|
||||
case 'WCAG_1_1_1_ImageAlt':
|
||||
case 'ImageAlt':
|
||||
case 'ImgAltText':
|
||||
if (preg_match('/<img\b(?![^>]*\balt=)/i', $snippet)) {
|
||||
$fixed = preg_replace('/<img\b/i', '<img alt=""', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Injected missing alt=\"\" attribute for decorative image.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_1_1_SVG':
|
||||
case 'SvgAltText':
|
||||
if (preg_match('/<svg\b(?![^>]*\baria-hidden=)(?![^>]*\baria-label=)/i', $snippet) && !str_contains($snippet, '<title>')) {
|
||||
$fixed = preg_replace('/<svg\b/i', '<svg aria-hidden="true"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Injected aria-hidden=\"true\" to decorative SVG element.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_LINK_TARGET_BLANK':
|
||||
case 'LinkTargetBlank':
|
||||
if (preg_match('/<a\b[^>]*\btarget=["\']_blank["\']/i', $snippet)) {
|
||||
if (preg_match('/rel=["\']([^"\']*)["\']/i', $snippet, $matches)) {
|
||||
$existingRel = $matches[1];
|
||||
$newRel = trim($existingRel . ' noopener noreferrer');
|
||||
$fixed = str_replace($matches[0], 'rel="' . $newRel . '"', $snippet);
|
||||
} else {
|
||||
$fixed = preg_replace('/<a\b/i', '<a rel="noopener noreferrer"', $snippet) ?: $snippet;
|
||||
}
|
||||
return "EXPLANATION: Added rel=\"noopener noreferrer\" to target=\"_blank\" link.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_2_4_3_TABINDEX':
|
||||
case 'TabindexOrder':
|
||||
if (preg_match('/\btabindex=["\'][1-9]\d*["\']/i', $snippet)) {
|
||||
$fixed = preg_replace('/\btabindex=["\'][1-9]\d*["\']/i', 'tabindex="0"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Normalized positive tabindex to tabindex=\"0\" to maintain natural tab order.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_3_1_TABLE_SCOPE':
|
||||
case 'ScopeOnlyOnHeaders':
|
||||
if (preg_match('/<td\b[^>]*\bscope=["\'][^"\']*["\']/i', $snippet)) {
|
||||
$fixed = preg_replace('/\s+scope=["\'][^"\']*["\']/i', '', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Removed invalid scope attribute from <td> element.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_2_2_1_META_REFRESH':
|
||||
case 'MetaRefreshBanned':
|
||||
if (preg_match('/<meta\b[^>]*\bhttp-equiv=["\']refresh["\'][^>]*>/i', $snippet)) {
|
||||
$fixed = '<!-- ' . trim($snippet) . ' (Removed: Meta refresh disorients users) -->';
|
||||
return "EXPLANATION: Commented out disorienting meta refresh tag.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_3_1_OPTGROUP_LABEL':
|
||||
case 'OptgroupLabel':
|
||||
if (preg_match('/<optgroup\b(?![^>]*\blabel=)/i', $snippet)) {
|
||||
$fixed = preg_replace('/<optgroup\b/i', '<optgroup label="Options"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Added fallback label=\"Options\" attribute to <optgroup>.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_2_4_7_FOCUS_OUTLINE':
|
||||
case 'NoFocusOutline':
|
||||
if (preg_match('/style=["\'][^"\']*outline\s*:\s*(?:none|0)[^"\']*["\']/i', $snippet)) {
|
||||
$fixed = preg_replace('/outline\s*:\s*(?:none|0)/i', 'outline: 2px solid transparent; outline-offset: 2px', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Replaced outline removal with accessible transparent outline.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_2_2_2_BLINK':
|
||||
case 'BlinkTagBanned':
|
||||
$fixed = str_replace(
|
||||
['<blink>', '</blink>', '<BLINK>', '</BLINK>'],
|
||||
['<span style="text-decoration: blink;">', '</span>', '<span style="text-decoration: blink;">', '</span>'],
|
||||
$snippet
|
||||
);
|
||||
return "EXPLANATION: Banned <blink> tag replaced with a span and text-decoration style.\nFIX: " . $fixed;
|
||||
|
||||
case 'WCAG_2_4_3_AUTOFOCUS':
|
||||
case 'AutofocusBanned':
|
||||
$fixed = preg_replace('/\s+autofocus(=["\'](.*?)["\'])?/i', '', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Autofocus attribute removed to prevent screen reader interruption on load.\nFIX: " . $fixed;
|
||||
|
||||
case 'WCAG_1_3_1_TABLE_SUMMARY':
|
||||
case 'TableSummaryBanned':
|
||||
$fixed = preg_replace('/\s+summary=["\'](.*?)["\']/i', '', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Deprecated table summary attribute removed. Use caption elements instead.\nFIX: " . $fixed;
|
||||
|
||||
case 'WCAG_2_1_1_SCROLLABLE_FOCUS':
|
||||
case 'ScrollableRegionFocusable':
|
||||
if (!str_contains($snippet, 'tabindex')) {
|
||||
$fixed = preg_replace('/(style=["\'](.*?)["\'])/i', '$1 tabindex="0"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Added tabindex=\"0\" to scrollable region to allow keyboard scrolling.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_3_1_PRESENTATION_TAGS':
|
||||
case 'PresentationTagsBanned':
|
||||
if (preg_match('/<center>(.*?)<\/center>/is', $snippet, $matches)) {
|
||||
$fixed = '<div style="text-align: center;">' . $matches[1] . '</div>';
|
||||
return "EXPLANATION: Center element replaced with div and text-align CSS.\nFIX: " . $fixed;
|
||||
}
|
||||
if (preg_match('/<strike>(.*?)<\/strike>/is', $snippet, $matches)) {
|
||||
$fixed = '<span style="text-decoration: line-through;">' . $matches[1] . '</span>';
|
||||
return "EXPLANATION: Strike element replaced with span and line-through decoration CSS.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_3_1_1_LANG':
|
||||
case 'HtmlHasLang':
|
||||
if (preg_match('/<html(\s+[^>]*>|>)/i', $snippet)) {
|
||||
$fixed = preg_replace('/<html/i', '<html lang="tr"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Injected default lang=\"tr\" to HTML element.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_3_2_2_BUTTON_TYPE':
|
||||
case 'ButtonTypeExplicit':
|
||||
if (preg_match('/<button\b(?![^>]*\btype=)/i', $snippet)) {
|
||||
$fixed = preg_replace('/<button\b/i', '<button type="button"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Added explicit type=\"button\" attribute to prevent unintended form submissions.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_1_1_SVG_FOCUSABLE':
|
||||
case 'SvgFocusableIeEdge':
|
||||
if (preg_match('/<svg\b(?![^>]*\bfocusable=)/i', $snippet)) {
|
||||
$fixed = preg_replace('/<svg\b/i', '<svg focusable="false"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Added focusable=\"false\" to decorative SVG element.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_4_1_2_ARIA_MODAL':
|
||||
case 'AriaModalBackdrop':
|
||||
if (preg_match('/role=["\'](?:alert)?dialog["\']/i', $snippet) && !preg_match('/\baria-modal=/i', $snippet)) {
|
||||
$fixed = preg_replace('/(role=["\'](?:alert)?dialog["\'])/i', '$1 aria-modal="true"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Added aria-modal=\"true\" to custom dialog container.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_4_1_2_ARIA_SWITCH':
|
||||
case 'AriaSwitchState':
|
||||
if (preg_match('/role=["\']switch["\']/i', $snippet) && !preg_match('/\baria-checked=/i', $snippet)) {
|
||||
$fixed = preg_replace('/(role=["\']switch["\'])/i', '$1 aria-checked="false"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Added default aria-checked=\"false\" to role=\"switch\" widget.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_4_8_TEXT_JUSTIFY':
|
||||
case 'JustifiedTextBanned':
|
||||
if (preg_match('/text-align\s*:\s*justify\b/i', $snippet)) {
|
||||
$fixed = preg_replace('/text-align\s*:\s*justify\b/i', 'text-align: start', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Replaced text-align: justify with text-align: start for improved readability.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_3_2_HTML_DIR':
|
||||
case 'HtmlDirValid':
|
||||
if (preg_match('/\bdir=["\'][^"\']*["\']/i', $snippet)) {
|
||||
$fixed = preg_replace('/\bdir=["\'][^"\']*["\']/i', 'dir="auto"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Normalized invalid dir attribute to dir=\"auto\".\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_4_1_2_IFRAME_TABINDEX':
|
||||
case 'IframeSandboxAccessibility':
|
||||
if (preg_match('/<iframe\b[^>]*\btabindex=["\']-\d+["\']/i', $snippet)) {
|
||||
$fixed = preg_replace('/\s+tabindex=["\']-\d+["\']/i', '', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Removed negative tabindex from visible <iframe> to restore keyboard access.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_4_2_MEDIA_CONTROLS':
|
||||
case 'MediaControls':
|
||||
if (preg_match('/<(audio|video)\b(?![^>]*\bcontrols\b)/i', $snippet)) {
|
||||
$fixed = preg_replace('/<(audio|video)\b/i', '<$1 controls', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Added controls attribute to media element for user playback control.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_4_1_2_ARIA_HIDDEN_BODY':
|
||||
case 'AriaHiddenBody':
|
||||
if (preg_match('/\baria-hidden=["\']true["\']/i', $snippet)) {
|
||||
$fixed = preg_replace('/\s+aria-hidden=["\']true["\']/i', '', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Removed aria-hidden=\"true\" from document root element.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_2_2_2_MARQUEE':
|
||||
case 'MarqueeBanned':
|
||||
$fixed = preg_replace('/<\/?marquee\b[^>]*>/i', '<div>', $snippet) ?: $snippet;
|
||||
$fixed = preg_replace('/<\/marquee>/i', '</div>', preg_replace('/<marquee\b[^>]*>/i', '<div>', $snippet) ?: $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Replaced obsolete <marquee> element with static <div> container.\nFIX: " . $fixed;
|
||||
|
||||
case 'WCAG_FONT_TAG_BANNED':
|
||||
case 'FontTagBanned':
|
||||
$fixed = preg_replace('/<\/font>/i', '</span>', preg_replace('/<font\b[^>]*>/i', '<span>', $snippet) ?: $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Replaced obsolete <font> tag with semantic <span> element.\nFIX: " . $fixed;
|
||||
|
||||
case 'WCAG_1_3_1_DETAILS_SUMMARY':
|
||||
case 'DetailsMissingSummary':
|
||||
if (preg_match('/<details\b[^>]*>/i', $snippet) && !preg_match('/<summary\b/i', $snippet)) {
|
||||
$fixed = preg_replace('/(<details\b[^>]*>)/i', '$1<summary>Details</summary>', $snippet, 1) ?: $snippet;
|
||||
return "EXPLANATION: Inserted missing <summary> disclosure label inside <details>.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_3_1_FIELDSET':
|
||||
case 'FieldsetLegend':
|
||||
if (preg_match('/<fieldset\b[^>]*>/i', $snippet) && !preg_match('/<legend\b/i', $snippet)) {
|
||||
$fixed = preg_replace('/(<fieldset\b[^>]*>)/i', '$1<legend>Group</legend>', $snippet, 1) ?: $snippet;
|
||||
return "EXPLANATION: Inserted missing <legend> element inside <fieldset>.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_4_1_2_ARIA_DEPRECATED_ROLE':
|
||||
case 'AriaDeprecatedRoles':
|
||||
if (preg_match('/\brole=["\']directory["\']/i', $snippet)) {
|
||||
$fixed = preg_replace('/\brole=["\']directory["\']/i', 'role="list"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Replaced deprecated role=\"directory\" with role=\"list\".\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_1_3_1_BLOCKQUOTE_MISUSE':
|
||||
case 'BlockquoteCiteValid':
|
||||
if (preg_match('/\scite=["\']\s*["\']/i', $snippet)) {
|
||||
$fixed = preg_replace('/\scite=["\']\s*["\']/i', '', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Removed empty cite=\"\" attribute from <blockquote>.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_4_1_2_IFRAME_TITLE':
|
||||
case 'IframeTitle':
|
||||
if (preg_match('/<iframe\b(?![^>]*\btitle=)/i', $snippet)) {
|
||||
$fixed = preg_replace('/<iframe\b/i', '<iframe title="Embedded Content"', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Added descriptive title attribute to <iframe>.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'WCAG_2_1_1_ACCESSKEY':
|
||||
case 'AccesskeyBanned':
|
||||
if (preg_match('/\s+accesskey=["\'][^"\']*["\']/i', $snippet)) {
|
||||
$fixed = preg_replace('/\s+accesskey=["\'][^"\']*["\']/i', '', $snippet) ?: $snippet;
|
||||
return "EXPLANATION: Removed conflicting accesskey attribute.\nFIX: " . $fixed;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* List of rule IDs supported by deterministic offline self-healing.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function getSupportedRuleIds(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_1_1_IMG_ALT',
|
||||
'WCAG_1_1_1_ImageAlt',
|
||||
'WCAG_1_1_1_SVG',
|
||||
'WCAG_1_1_1_SVG_FOCUSABLE',
|
||||
'WCAG_1_3_1_BLOCKQUOTE_MISUSE',
|
||||
'WCAG_1_3_1_DETAILS_SUMMARY',
|
||||
'WCAG_1_3_1_FIELDSET',
|
||||
'WCAG_1_3_1_OPTGROUP_LABEL',
|
||||
'WCAG_1_3_1_PRESENTATION_TAGS',
|
||||
'WCAG_1_3_1_TABLE_SCOPE',
|
||||
'WCAG_1_3_1_TABLE_SUMMARY',
|
||||
'WCAG_1_3_2_HTML_DIR',
|
||||
'WCAG_1_4_2_MEDIA_CONTROLS',
|
||||
'WCAG_1_4_8_TEXT_JUSTIFY',
|
||||
'WCAG_2_1_1_ACCESSKEY',
|
||||
'WCAG_2_1_1_SCROLLABLE_FOCUS',
|
||||
'WCAG_2_2_1_META_REFRESH',
|
||||
'WCAG_2_2_2_BLINK',
|
||||
'WCAG_2_2_2_MARQUEE',
|
||||
'WCAG_2_4_3_AUTOFOCUS',
|
||||
'WCAG_2_4_3_TABINDEX',
|
||||
'WCAG_2_4_7_FOCUS_OUTLINE',
|
||||
'WCAG_3_1_1_LANG',
|
||||
'WCAG_3_2_2_BUTTON_TYPE',
|
||||
'WCAG_4_1_2_ARIA_DEPRECATED_ROLE',
|
||||
'WCAG_4_1_2_ARIA_HIDDEN_BODY',
|
||||
'WCAG_4_1_2_ARIA_MODAL',
|
||||
'WCAG_4_1_2_ARIA_SWITCH',
|
||||
'WCAG_4_1_2_IFRAME_TABINDEX',
|
||||
'WCAG_4_1_2_IFRAME_TITLE',
|
||||
'WCAG_FONT_TAG_BANNED',
|
||||
'WCAG_LINK_TARGET_BLANK',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Core\Suppression;
|
||||
|
||||
/**
|
||||
* Parses inline accessibility suppression directives from HTML/Blade/Twig/Vue/JSX files.
|
||||
*
|
||||
* Supported directives:
|
||||
* <!-- a11y-disable-file [RULE_1, RULE_2] [-- reason] -->
|
||||
* <!-- a11y-disable-next-line [RULE_1, RULE_2] [-- reason] -->
|
||||
* <!-- a11y-disable-line [RULE_1, RULE_2] [-- reason] -->
|
||||
* <!-- a11y-disable [RULE_1, RULE_2] [-- reason] -->
|
||||
* <!-- a11y-enable [RULE_1, RULE_2] -->
|
||||
*/
|
||||
class InlineSuppressionParser
|
||||
{
|
||||
/**
|
||||
* @return array{
|
||||
* fileDisabled: bool,
|
||||
* fileRules: array<string, string>,
|
||||
* lineRules: array<int, array<string, string>>
|
||||
* }
|
||||
*/
|
||||
public function parse(string $sourceContent): array
|
||||
{
|
||||
$lines = preg_split('/\r\n|\r|\n/', $sourceContent);
|
||||
if (!is_array($lines)) {
|
||||
return [
|
||||
'fileDisabled' => false,
|
||||
'fileRules' => [],
|
||||
'lineRules' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$fileDisabled = false;
|
||||
/** @var array<string, string> $fileRules */
|
||||
$fileRules = [];
|
||||
/** @var array<int, array<string, string>> $lineRules */
|
||||
$lineRules = [];
|
||||
/** @var array<string, string> $activeBlockRules */
|
||||
$activeBlockRules = [];
|
||||
$blockAllReason = null;
|
||||
|
||||
foreach ($lines as $idx => $lineText) {
|
||||
$lineNum = $idx + 1;
|
||||
|
||||
// Apply currently active block suppressions to this line
|
||||
if ($blockAllReason !== null) {
|
||||
$lineRules[$lineNum]['*'] = $blockAllReason;
|
||||
}
|
||||
foreach ($activeBlockRules as $ruleId => $reason) {
|
||||
$lineRules[$lineNum][$ruleId] = $reason;
|
||||
}
|
||||
|
||||
if (preg_match_all('/<!--\s*a11y-(disable-file|disable-next-line|disable-line|disable|enable)\b(.*?)-->/i', $lineText, $matches, PREG_SET_ORDER)) {
|
||||
foreach ($matches as $match) {
|
||||
$directive = strtolower($match[1]);
|
||||
$body = trim($match[2]);
|
||||
[$rules, $reason] = $this->parseDirectiveBody($body);
|
||||
|
||||
if ($directive === 'disable-file') {
|
||||
if (empty($rules)) {
|
||||
$fileDisabled = true;
|
||||
$fileRules['*'] = $reason;
|
||||
} else {
|
||||
foreach ($rules as $r) {
|
||||
$fileRules[$r] = $reason;
|
||||
}
|
||||
}
|
||||
} elseif ($directive === 'disable-next-line') {
|
||||
$nextLine = $lineNum + 1;
|
||||
if (empty($rules)) {
|
||||
$lineRules[$nextLine]['*'] = $reason;
|
||||
} else {
|
||||
foreach ($rules as $r) {
|
||||
$lineRules[$nextLine][$r] = $reason;
|
||||
}
|
||||
}
|
||||
} elseif ($directive === 'disable-line') {
|
||||
if (empty($rules)) {
|
||||
$lineRules[$lineNum]['*'] = $reason;
|
||||
} else {
|
||||
foreach ($rules as $r) {
|
||||
$lineRules[$lineNum][$r] = $reason;
|
||||
}
|
||||
}
|
||||
} elseif ($directive === 'disable') {
|
||||
if (empty($rules)) {
|
||||
$blockAllReason = $reason;
|
||||
$lineRules[$lineNum]['*'] = $reason;
|
||||
} else {
|
||||
foreach ($rules as $r) {
|
||||
$activeBlockRules[$r] = $reason;
|
||||
$lineRules[$lineNum][$r] = $reason;
|
||||
}
|
||||
}
|
||||
} elseif ($directive === 'enable') {
|
||||
if (empty($rules)) {
|
||||
$blockAllReason = null;
|
||||
$activeBlockRules = [];
|
||||
} else {
|
||||
foreach ($rules as $r) {
|
||||
unset($activeBlockRules[$r]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'fileDisabled' => $fileDisabled,
|
||||
'fileRules' => $fileRules,
|
||||
'lineRules' => $lineRules,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a specific rule at a given line is suppressed, returning the reason string or null if not suppressed.
|
||||
*
|
||||
* @param array{fileDisabled: bool, fileRules: array<string, string>, lineRules: array<int, array<string, string>>} $suppressions
|
||||
*/
|
||||
public function getSuppressionReason(array $suppressions, string $ruleId, int $line): ?string
|
||||
{
|
||||
if ($suppressions['fileDisabled']) {
|
||||
return $suppressions['fileRules']['*'] ?? '';
|
||||
}
|
||||
|
||||
if (isset($suppressions['fileRules'][$ruleId])) {
|
||||
return $suppressions['fileRules'][$ruleId];
|
||||
}
|
||||
|
||||
if (isset($suppressions['lineRules'][$line]['*'])) {
|
||||
return $suppressions['lineRules'][$line]['*'];
|
||||
}
|
||||
|
||||
if (isset($suppressions['lineRules'][$line][$ruleId])) {
|
||||
return $suppressions['lineRules'][$line][$ruleId];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse optional comma/space separated rule IDs and optional "-- reason" suffix.
|
||||
*
|
||||
* @return array{0: string[], 1: string}
|
||||
*/
|
||||
private function parseDirectiveBody(string $body): array
|
||||
{
|
||||
$reason = '';
|
||||
$rulesPart = $body;
|
||||
|
||||
if (str_contains($body, '--')) {
|
||||
$parts = explode('--', $body, 2);
|
||||
$rulesPart = trim($parts[0]);
|
||||
$reason = trim($parts[1]);
|
||||
}
|
||||
|
||||
if ($rulesPart === '') {
|
||||
return [[], $reason];
|
||||
}
|
||||
|
||||
$tokens = preg_split('/[\s,]+/', $rulesPart);
|
||||
if (!is_array($tokens)) {
|
||||
return [[], $reason];
|
||||
}
|
||||
|
||||
$rules = [];
|
||||
foreach ($tokens as $token) {
|
||||
$token = trim($token);
|
||||
if ($token !== '') {
|
||||
$rules[] = $token;
|
||||
}
|
||||
}
|
||||
|
||||
return [$rules, $reason];
|
||||
}
|
||||
}
|
||||
@@ -5,20 +5,20 @@ namespace YakNet\AccessibilityConsole\Core;
|
||||
class Violation
|
||||
{
|
||||
/**
|
||||
* @param array{file: string, line: int}|null $location
|
||||
* @param array{file?: string, line: int, column?: int}|null $location
|
||||
*/
|
||||
public function __construct(
|
||||
public string $ruleId,
|
||||
public string $message,
|
||||
public Severity $severity,
|
||||
public WCAGStandard $standard,
|
||||
public string $htmlSnippet,
|
||||
public string $htmlSnippet = '',
|
||||
public ?array $location = null, // ['file' => '...', 'line' => 0]
|
||||
public ?string $fixSuggestion = null
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{ruleId: string, message: string, severity: string, standard: string, htmlSnippet: string, location: array{file: string, line: int}|null, fixSuggestion: string|null}
|
||||
* @return array{ruleId: string, message: string, severity: string, standard: string, htmlSnippet: string, location: array{file?: string, line: int, column?: int}|null, fixSuggestion: string|null}
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Integrations;
|
||||
|
||||
class GitHubActionsReporter
|
||||
{
|
||||
/**
|
||||
* Format WCAG violations as GitHub Actions Workflow Command Annotations.
|
||||
*
|
||||
* @param array<string, mixed> $scanResult
|
||||
* @param string $fileName
|
||||
* @return string Formatted annotations string
|
||||
*/
|
||||
public static function formatAnnotations(array $scanResult, string $fileName = 'index.html'): string
|
||||
{
|
||||
/** @var array<int, array<string, mixed>> $violations */
|
||||
$violations = is_array($scanResult['violations'] ?? null) ? $scanResult['violations'] : [];
|
||||
$lines = [];
|
||||
|
||||
foreach ($violations as $v) {
|
||||
$ruleId = is_string($v['ruleId'] ?? null) ? $v['ruleId'] : 'WCAG';
|
||||
$desc = is_string($v['description'] ?? null) ? $v['description'] : '';
|
||||
$line = is_numeric($v['line'] ?? null) ? intval($v['line']) : 1;
|
||||
$severity = is_string($v['severity'] ?? null) ? strtolower($v['severity']) : 'error';
|
||||
$level = $severity === 'error' ? 'error' : 'warning';
|
||||
|
||||
$lines[] = sprintf('::%s file=%s,line=%d::[%s] %s', $level, $fileName, $line, $ruleId, $desc);
|
||||
}
|
||||
|
||||
return implode("\n", $lines);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Notifications;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
|
||||
class DiscordNotifier implements NotifierInterface
|
||||
{
|
||||
private Client $httpClient;
|
||||
|
||||
public function __construct(
|
||||
private string $webhookUrl,
|
||||
?Client $httpClient = null
|
||||
) {
|
||||
$this->httpClient = $httpClient ?? new Client(['timeout' => 5.0]);
|
||||
}
|
||||
|
||||
public function send(NotificationPayload $payload): bool
|
||||
{
|
||||
if ($this->webhookUrl === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Color in decimal for Discord embed
|
||||
$color = $payload->healthScore >= 90 ? 0x10b981 : ($payload->healthScore >= 70 ? 0xf59e0b : 0xef4444);
|
||||
|
||||
$body = [
|
||||
'embeds' => [
|
||||
[
|
||||
'title' => "♿ Accessibility Audit: {$payload->target}",
|
||||
'color' => $color,
|
||||
'fields' => [
|
||||
[
|
||||
'name' => 'Health Score',
|
||||
'value' => sprintf('%d / 100', $payload->healthScore),
|
||||
'inline' => true,
|
||||
],
|
||||
[
|
||||
'name' => 'Total Violations',
|
||||
'value' => (string)$payload->totalViolations,
|
||||
'inline' => true,
|
||||
],
|
||||
[
|
||||
'name' => 'Breakdown',
|
||||
'value' => sprintf('Errors: %d | Warnings: %d', $payload->errorCount, $payload->warningCount),
|
||||
'inline' => false,
|
||||
],
|
||||
],
|
||||
'footer' => [
|
||||
'text' => 'YakNet Accessibility Console',
|
||||
],
|
||||
'timestamp' => date('c'),
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
try {
|
||||
$response = $this->httpClient->post($this->webhookUrl, [
|
||||
'json' => $body,
|
||||
]);
|
||||
return $response->getStatusCode() < 300;
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Notifications;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
|
||||
/**
|
||||
* Dispatches structured JSON accessibility payloads to any custom webhook endpoint
|
||||
* (SIEM, Jira Automation, ServiceNow, internal dashboards) with optional HMAC-SHA256 signing.
|
||||
*/
|
||||
class GenericWebhookNotifier implements NotifierInterface
|
||||
{
|
||||
private Client $httpClient;
|
||||
|
||||
public function __construct(
|
||||
private string $webhookUrl,
|
||||
private ?string $signingSecret = null,
|
||||
?Client $httpClient = null
|
||||
) {
|
||||
$this->httpClient = $httpClient ?? new Client(['timeout' => 5.0]);
|
||||
}
|
||||
|
||||
public function send(NotificationPayload $payload): bool
|
||||
{
|
||||
if ($this->webhookUrl === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$data = [
|
||||
'tool' => 'YakNet Accessibility Console',
|
||||
'version' => '4.0.0',
|
||||
'timestamp' => date('Y-m-d\TH:i:sP'),
|
||||
'target' => $payload->target,
|
||||
'health_score' => $payload->healthScore,
|
||||
'total_violations' => $payload->totalViolations,
|
||||
'error_count' => $payload->errorCount,
|
||||
'warning_count' => $payload->warningCount,
|
||||
'top_violations' => $payload->topViolations,
|
||||
];
|
||||
|
||||
$jsonBody = (string)json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
$headers = [
|
||||
'Content-Type' => 'application/json',
|
||||
'User-Agent' => 'YakNet-Accessibility-Console/4.0',
|
||||
];
|
||||
|
||||
if ($this->signingSecret !== null && $this->signingSecret !== '') {
|
||||
$headers['X-YakNet-Signature-256'] = 'sha256=' . hash_hmac('sha256', $jsonBody, $this->signingSecret);
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->httpClient->post($this->webhookUrl, [
|
||||
'headers' => $headers,
|
||||
'body' => $jsonBody,
|
||||
]);
|
||||
return $response->getStatusCode() < 300;
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Notifications;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
|
||||
/**
|
||||
* Sends accessibility scan summaries to Microsoft Teams channels via Incoming Webhook.
|
||||
*/
|
||||
class MicrosoftTeamsNotifier implements NotifierInterface
|
||||
{
|
||||
private Client $httpClient;
|
||||
|
||||
public function __construct(
|
||||
private string $webhookUrl,
|
||||
?Client $httpClient = null
|
||||
) {
|
||||
$this->httpClient = $httpClient ?? new Client(['timeout' => 5.0]);
|
||||
}
|
||||
|
||||
public function send(NotificationPayload $payload): bool
|
||||
{
|
||||
if ($this->webhookUrl === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$themeColor = $payload->healthScore >= 90 ? '10B981' : ($payload->healthScore >= 70 ? 'F59E0B' : 'EF4444');
|
||||
$status = $payload->healthScore >= 90 ? 'PASSED' : 'NEEDS ATTENTION';
|
||||
|
||||
$body = [
|
||||
'@type' => 'MessageCard',
|
||||
'@context' => 'https://schema.org/extensions',
|
||||
'themeColor' => $themeColor,
|
||||
'summary' => "Accessibility Audit: {$payload->target} ({$payload->healthScore}/100)",
|
||||
'sections' => [
|
||||
[
|
||||
'activityTitle' => "♿ YakNet Accessibility Console — {$payload->target}",
|
||||
'activitySubtitle' => "Status: {$status}",
|
||||
'facts' => [
|
||||
['name' => 'Health Score', 'value' => "{$payload->healthScore}/100"],
|
||||
['name' => 'Total Violations', 'value' => (string)$payload->totalViolations],
|
||||
['name' => 'Errors / Critical', 'value' => (string)$payload->errorCount],
|
||||
['name' => 'Warnings', 'value' => (string)$payload->warningCount],
|
||||
],
|
||||
'markdown' => true,
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
try {
|
||||
$response = $this->httpClient->post($this->webhookUrl, [
|
||||
'json' => $body,
|
||||
]);
|
||||
return $response->getStatusCode() < 300;
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Notifications;
|
||||
|
||||
class NotificationDispatcher
|
||||
{
|
||||
/**
|
||||
* @var array<string, NotifierInterface>
|
||||
*/
|
||||
private array $notifiers = [];
|
||||
|
||||
public function addNotifier(string $channel, NotifierInterface $notifier): void
|
||||
{
|
||||
$this->notifiers[$channel] = $notifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch notification payload across all registered notifiers.
|
||||
*
|
||||
* @return array<string, bool> Channel delivery results
|
||||
*/
|
||||
public function dispatch(NotificationPayload $payload): array
|
||||
{
|
||||
$results = [];
|
||||
foreach ($this->notifiers as $channel => $notifier) {
|
||||
$results[$channel] = $notifier->send($payload);
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
|
||||
public function hasNotifiers(): bool
|
||||
{
|
||||
return !empty($this->notifiers);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Notifications;
|
||||
|
||||
class NotificationPayload
|
||||
{
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $topViolations
|
||||
*/
|
||||
public function __construct(
|
||||
public string $target,
|
||||
public int $healthScore,
|
||||
public int $totalViolations,
|
||||
public int $errorCount,
|
||||
public int $warningCount,
|
||||
public array $topViolations = []
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Notifications;
|
||||
|
||||
interface NotifierInterface
|
||||
{
|
||||
public function send(NotificationPayload $payload): bool;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Notifications;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
|
||||
class SlackNotifier implements NotifierInterface
|
||||
{
|
||||
private Client $httpClient;
|
||||
|
||||
public function __construct(
|
||||
private string $webhookUrl,
|
||||
?Client $httpClient = null
|
||||
) {
|
||||
$this->httpClient = $httpClient ?? new Client(['timeout' => 5.0]);
|
||||
}
|
||||
|
||||
public function send(NotificationPayload $payload): bool
|
||||
{
|
||||
if ($this->webhookUrl === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$color = $payload->healthScore >= 90 ? '#10b981' : ($payload->healthScore >= 70 ? '#f59e0b' : '#ef4444');
|
||||
$status = $payload->healthScore >= 90 ? 'PASSED' : 'FAILED';
|
||||
|
||||
$body = [
|
||||
'attachments' => [
|
||||
[
|
||||
'color' => $color,
|
||||
'title' => "♿ Accessibility Audit: {$payload->target}",
|
||||
'text' => sprintf(
|
||||
"*Health Score:* %d/100 (%s)\n*Total Violations:* %d (Errors: %d, Warnings: %d)",
|
||||
$payload->healthScore,
|
||||
$status,
|
||||
$payload->totalViolations,
|
||||
$payload->errorCount,
|
||||
$payload->warningCount
|
||||
),
|
||||
'footer' => 'YakNet Accessibility Console',
|
||||
'ts' => time(),
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
try {
|
||||
$response = $this->httpClient->post($this->webhookUrl, [
|
||||
'json' => $body,
|
||||
]);
|
||||
return $response->getStatusCode() < 300;
|
||||
} catch (\Throwable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Parser;
|
||||
|
||||
class BladeParser implements ParserInterface
|
||||
{
|
||||
public function parse(string $content): string
|
||||
{
|
||||
// 1. Strip Blade comments {{-- ... --}} while preserving line count
|
||||
$content = preg_replace_callback('/\{\{--(.*?)--\}\}/s', function ($m) {
|
||||
return str_repeat("\n", substr_count($m[0], "\n"));
|
||||
}, $content) ?? $content;
|
||||
|
||||
// 2. Replace raw echo {!! ... !!} while preserving line count
|
||||
$content = preg_replace_callback('/\{\!\!(.*?)\!\!\}/s', function ($m) {
|
||||
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
|
||||
return 'StaticRawBladeContent' . $newlines;
|
||||
}, $content) ?? $content;
|
||||
|
||||
// 3. Replace safe echo {{ ... }} while preserving line count
|
||||
$content = preg_replace_callback('/\{\{\s*(.*?)\s*\}\}/s', function ($m) {
|
||||
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
|
||||
return 'StaticBladeContent' . $newlines;
|
||||
}, $content) ?? $content;
|
||||
|
||||
// 4. Strip Blade directives like @if, @else, @endif, @foreach, @component, etc.
|
||||
$content = preg_replace_callback('/@[a-zA-Z0-9_]+\s*(\([^\)]*\))?/s', function ($m) {
|
||||
return str_repeat("\n", substr_count($m[0], "\n"));
|
||||
}, $content) ?? $content;
|
||||
|
||||
return $content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Parser;
|
||||
|
||||
class HtmlParser implements ParserInterface
|
||||
{
|
||||
public function parse(string $content): string
|
||||
{
|
||||
return $content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Parser;
|
||||
|
||||
/**
|
||||
* Parses React JSX / TSX files (.jsx, .tsx) by normalizing JSX attributes to standard HTML
|
||||
* while preserving exact 1:1 line numbering for accurate violation reporting.
|
||||
*/
|
||||
class JsxParser implements ParserInterface
|
||||
{
|
||||
public function parse(string $content): string
|
||||
{
|
||||
// Normalize JSX attribute names to HTML equivalents
|
||||
$replacements = [
|
||||
'/\bclassName\s*=/' => 'class=',
|
||||
'/\bhtmlFor\s*=/' => 'for=',
|
||||
'/\btabIndex\s*=\s*\{(-?\d+)\}/' => 'tabindex="$1"',
|
||||
'/\btabIndex\s*=/' => 'tabindex=',
|
||||
'/\bonClick\s*=\s*\{[^}]*\}/' => 'onclick="jsxHandler()"',
|
||||
'/\bonKeyDown\s*=\s*\{[^}]*\}/' => 'onkeydown="jsxHandler()"',
|
||||
'/\bonKeyUp\s*=\s*\{[^}]*\}/' => 'onkeyup="jsxHandler()"',
|
||||
'/\bonMouseDown\s*=\s*\{[^}]*\}/' => 'onmousedown="jsxHandler()"',
|
||||
'/\bautoFocus\b/' => 'autofocus',
|
||||
'/\breadOnly\b/' => 'readonly',
|
||||
];
|
||||
|
||||
$normalized = $content;
|
||||
foreach ($replacements as $pattern => $replacement) {
|
||||
$normalized = preg_replace($pattern, $replacement, $normalized) ?? $normalized;
|
||||
}
|
||||
|
||||
// Convert attribute={expr} to attribute="JsxExpr" preserving newlines
|
||||
$normalized = preg_replace_callback('/\b([a-zA-Z0-9_-]+)\s*=\s*\{([^{}]*)\}/s', function (array $m): string {
|
||||
$attr = strtolower($m[1]);
|
||||
$inner = trim($m[2]);
|
||||
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
|
||||
// Preserve string literals inside braces e.g. alt={"Logo"}
|
||||
if (preg_match('/^["\'](.*)["\']$/s', $inner, $lit)) {
|
||||
return $attr . '="' . htmlspecialchars($lit[1], ENT_QUOTES) . '"' . $newlines;
|
||||
}
|
||||
if ($inner === 'true' || $inner === 'false') {
|
||||
return $attr . '="' . $inner . '"' . $newlines;
|
||||
}
|
||||
return $attr . '="JsxExpr"' . $newlines;
|
||||
}, $normalized) ?? $normalized;
|
||||
|
||||
// Replace JSX text expressions {variable} inside tags with safe text preserving newlines
|
||||
$normalized = preg_replace_callback('/>\s*\{([^{}]*)\}\s*</s', function (array $m): string {
|
||||
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
|
||||
return '>JsxContent' . $newlines . '<';
|
||||
}, $normalized) ?? $normalized;
|
||||
|
||||
// Replace JSX fragments <> and </> with <div> and </div>
|
||||
$normalized = str_replace(['<>', '</>'], ['<div>', '</div>'], $normalized);
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Parser;
|
||||
|
||||
interface ParserInterface
|
||||
{
|
||||
/**
|
||||
* Parse template file contents and strip out dynamic content placeholders
|
||||
* to return clean, standard HTML for scanning.
|
||||
*
|
||||
* @param string $content
|
||||
* @return string
|
||||
*/
|
||||
public function parse(string $content): string;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Parser;
|
||||
|
||||
class TemplatePreprocessor
|
||||
{
|
||||
private BladeParser $bladeParser;
|
||||
private TwigParser $twigParser;
|
||||
private HtmlParser $htmlParser;
|
||||
private VueParser $vueParser;
|
||||
private JsxParser $jsxParser;
|
||||
|
||||
public function __construct(
|
||||
?BladeParser $bladeParser = null,
|
||||
?TwigParser $twigParser = null,
|
||||
?HtmlParser $htmlParser = null,
|
||||
?VueParser $vueParser = null,
|
||||
?JsxParser $jsxParser = null
|
||||
) {
|
||||
$this->bladeParser = $bladeParser ?? new BladeParser();
|
||||
$this->twigParser = $twigParser ?? new TwigParser();
|
||||
$this->htmlParser = $htmlParser ?? new HtmlParser();
|
||||
$this->vueParser = $vueParser ?? new VueParser();
|
||||
$this->jsxParser = $jsxParser ?? new JsxParser();
|
||||
}
|
||||
|
||||
/**
|
||||
* Preprocess file content according to its file extension or template dialect.
|
||||
*
|
||||
* @param string $content
|
||||
* @param string|null $filePath
|
||||
* @return string
|
||||
*/
|
||||
public function preprocess(string $content, ?string $filePath = null): string
|
||||
{
|
||||
if ($filePath !== null) {
|
||||
$lower = strtolower($filePath);
|
||||
if (str_ends_with($lower, '.blade.php')) {
|
||||
return $this->bladeParser->parse($content);
|
||||
}
|
||||
if (str_ends_with($lower, '.twig')) {
|
||||
return $this->twigParser->parse($content);
|
||||
}
|
||||
if (str_ends_with($lower, '.vue')) {
|
||||
return $this->vueParser->parse($content);
|
||||
}
|
||||
if (str_ends_with($lower, '.jsx') || str_ends_with($lower, '.tsx')) {
|
||||
return $this->jsxParser->parse($content);
|
||||
}
|
||||
if (str_ends_with($lower, '.php')) {
|
||||
return $this->preprocessPhp($content);
|
||||
}
|
||||
}
|
||||
|
||||
// Detect Blade or Twig by content heuristic if no path is provided
|
||||
if (str_contains($content, '{{') || str_contains($content, '@if') || str_contains($content, '@foreach')) {
|
||||
return $this->bladeParser->parse($content);
|
||||
}
|
||||
|
||||
if (str_contains($content, '{%') || str_contains($content, '{#')) {
|
||||
return $this->twigParser->parse($content);
|
||||
}
|
||||
|
||||
if (str_contains($content, '<' . '?php') || str_contains($content, '<' . '?=')) {
|
||||
return $this->preprocessPhp($content);
|
||||
}
|
||||
|
||||
return $this->htmlParser->parse($content);
|
||||
}
|
||||
|
||||
private function preprocessPhp(string $content): string
|
||||
{
|
||||
// Replace short echo tags with placeholder text preserving newlines
|
||||
$content = preg_replace_callback('/<\?=(.*?)\?>/s', function ($m) {
|
||||
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
|
||||
return 'StaticPhpEcho' . $newlines;
|
||||
}, $content) ?? $content;
|
||||
|
||||
// Replace PHP execution blocks with placeholder preserving newlines
|
||||
$content = preg_replace_callback('/<\?php(.*?)\?>/s', function ($m) {
|
||||
return str_repeat("\n", substr_count($m[0], "\n"));
|
||||
}, $content) ?? $content;
|
||||
|
||||
return $content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Parser;
|
||||
|
||||
class TwigParser implements ParserInterface
|
||||
{
|
||||
public function parse(string $content): string
|
||||
{
|
||||
// 1. Strip Twig comments {# ... #} while preserving line count
|
||||
$content = preg_replace_callback('/\{\#.*?\#\}/s', function ($m) {
|
||||
return str_repeat("\n", substr_count($m[0], "\n"));
|
||||
}, $content) ?? $content;
|
||||
|
||||
// 2. Replace Twig output {{ ... }} while preserving line count
|
||||
$content = preg_replace_callback('/\{\{\s*(.*?)\s*\}\}/s', function ($m) {
|
||||
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
|
||||
return 'StaticTwigOutput' . $newlines;
|
||||
}, $content) ?? $content;
|
||||
|
||||
// 3. Strip Twig statements {% ... %} while preserving line count
|
||||
$content = preg_replace_callback('/\{\%.*?\%\}/s', function ($m) {
|
||||
return str_repeat("\n", substr_count($m[0], "\n"));
|
||||
}, $content) ?? $content;
|
||||
|
||||
return $content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Parser;
|
||||
|
||||
/**
|
||||
* Parses Vue Single File Components (.vue), extracting the <template> block
|
||||
* while preserving exact 1:1 line numbers and normalizing Vue directives for static a11y analysis.
|
||||
*/
|
||||
class VueParser implements ParserInterface
|
||||
{
|
||||
public function parse(string $content): string
|
||||
{
|
||||
// Extract <template> block while preserving leading newlines for exact line mapping
|
||||
if (preg_match('/^(.*?)<template\b[^>]*>(.*)<\/template>/is', $content, $match)) {
|
||||
$leadingNewlines = str_repeat("\n", substr_count($match[1], "\n"));
|
||||
$templateBody = $match[2];
|
||||
$cleaned = $this->normalizeVueDirectives($templateBody);
|
||||
return $leadingNewlines . $cleaned;
|
||||
}
|
||||
|
||||
return $this->normalizeVueDirectives($content);
|
||||
}
|
||||
|
||||
private function normalizeVueDirectives(string $html): string
|
||||
{
|
||||
// Replace mustache interpolations {{ expr }} with safe static placeholder preserving newlines
|
||||
$html = preg_replace_callback('/\{\{(.*?)\}\}/s', function (array $m): string {
|
||||
return 'VueExpression' . str_repeat("\n", substr_count($m[0], "\n"));
|
||||
}, $html) ?? $html;
|
||||
|
||||
// Convert @click="..." / v-on:click="..." to onclick="..."
|
||||
$html = preg_replace('/\s(?:@|v-on:)click\s*=\s*"([^"]*)"/i', ' onclick="$1"', $html) ?? $html;
|
||||
$html = preg_replace('/\s(?:@|v-on:)keydown(?:\.[a-z0-9]+)*\s*=\s*"([^"]*)"/i', ' onkeydown="$1"', $html) ?? $html;
|
||||
$html = preg_replace('/\s(?:@|v-on:)keyup(?:\.[a-z0-9]+)*\s*=\s*"([^"]*)"/i', ' onkeyup="$1"', $html) ?? $html;
|
||||
|
||||
// Convert bound accessibility attributes (:alt, :aria-label, :href, :title, :tabindex, :role, :for)
|
||||
$html = preg_replace('/\s(?:v-bind)?\:((?:aria-[a-z-]+|alt|href|title|tabindex|role|for|id|type|name|lang|dir))\s*=\s*"([^"]*)"/i', ' $1="$2"', $html) ?? $html;
|
||||
|
||||
// Strip remaining Vue structural directives (v-if, v-else-if, v-else, v-for, v-show, v-model, v-slot, #slot)
|
||||
$html = preg_replace('/\sv-(?:if|else-if|else|for|show|model|html|text|cloak|pre|once|memo|slot)(?:[:.][a-zA-Z0-9_-]+)*(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'))?/i', '', $html) ?? $html;
|
||||
|
||||
return $html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Policy;
|
||||
|
||||
use YakNet\AccessibilityConsole\Analytics\ComplianceMatrixGenerator;
|
||||
use YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator;
|
||||
use YakNet\AccessibilityConsole\Core\Severity;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
/**
|
||||
* Governance Policy Engine for enforcing organization-wide accessibility thresholds,
|
||||
* severity overrides, zero-tolerance rules, and WCAG standard gates in CI/CD pipelines.
|
||||
*/
|
||||
class PolicyEngine
|
||||
{
|
||||
/** @var array<string, mixed> */
|
||||
private array $policy;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $policy
|
||||
*/
|
||||
public function __construct(array $policy = [])
|
||||
{
|
||||
$this->policy = $policy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply configured severity overrides to violations in-place.
|
||||
*
|
||||
* @param Violation[] $violations
|
||||
* @return Violation[]
|
||||
*/
|
||||
public function applySeverityOverrides(array $violations): array
|
||||
{
|
||||
$overrides = $this->policy['severity_overrides'] ?? [];
|
||||
if (!is_array($overrides) || empty($overrides)) {
|
||||
return $violations;
|
||||
}
|
||||
|
||||
foreach ($violations as $violation) {
|
||||
if (isset($overrides[$violation->ruleId]) && is_string($overrides[$violation->ruleId])) {
|
||||
$mapped = match (strtolower($overrides[$violation->ruleId])) {
|
||||
'critical' => Severity::CRITICAL,
|
||||
'error' => Severity::ERROR,
|
||||
'warning' => Severity::WARNING,
|
||||
'info' => Severity::INFO,
|
||||
default => null,
|
||||
};
|
||||
if ($mapped !== null) {
|
||||
$violation->severity = $mapped;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $violations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate violations against all configured governance policy gates.
|
||||
*
|
||||
* @param Violation[] $violations
|
||||
*/
|
||||
public function evaluate(array $violations): PolicyResult
|
||||
{
|
||||
$this->applySeverityOverrides($violations);
|
||||
|
||||
$metrics = AccessibilityScoreCalculator::calculate($violations);
|
||||
$score = $metrics['score'];
|
||||
|
||||
$counts = [
|
||||
'critical' => 0,
|
||||
'error' => 0,
|
||||
'warning' => 0,
|
||||
'info' => 0,
|
||||
];
|
||||
$standardCounts = ['A' => 0, 'AA' => 0, 'AAA' => 0];
|
||||
$ruleCounts = [];
|
||||
|
||||
foreach ($violations as $v) {
|
||||
$counts[$v->severity->value]++;
|
||||
$stdKey = $v->standard->value;
|
||||
$standardCounts[$stdKey]++;
|
||||
$ruleCounts[$v->ruleId] = ($ruleCounts[$v->ruleId] ?? 0) + 1;
|
||||
}
|
||||
|
||||
/** @var string[] $failures */
|
||||
$failures = [];
|
||||
|
||||
// 1. Minimum score threshold
|
||||
if (isset($this->policy['min_score']) && is_numeric($this->policy['min_score'])) {
|
||||
$minScore = (int)$this->policy['min_score'];
|
||||
if ($score < $minScore) {
|
||||
$failures[] = sprintf('Health score (%d/100) is below policy minimum (%d/100).', $score, $minScore);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Severity maximums
|
||||
$severityLimits = [
|
||||
'max_critical' => 'critical',
|
||||
'max_errors' => 'error',
|
||||
'max_warnings' => 'warning',
|
||||
];
|
||||
foreach ($severityLimits as $policyKey => $sevKey) {
|
||||
if (isset($this->policy[$policyKey]) && is_numeric($this->policy[$policyKey])) {
|
||||
$limit = (int)$this->policy[$policyKey];
|
||||
$actual = $counts[$sevKey];
|
||||
if ($actual > $limit) {
|
||||
$failures[] = sprintf('Policy limit exceeded for %s violations: found %d, maximum allowed is %d.', $sevKey, $actual, $limit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Required WCAG Standards (zero-tolerance standards)
|
||||
if (isset($this->policy['required_standards']) && is_array($this->policy['required_standards'])) {
|
||||
foreach ($this->policy['required_standards'] as $std) {
|
||||
if (!is_string($std)) {
|
||||
continue;
|
||||
}
|
||||
$upper = strtoupper(trim($std));
|
||||
$stdViolations = $standardCounts[$upper] ?? 0;
|
||||
if ($stdViolations > 0) {
|
||||
$failures[] = sprintf('WCAG Level %s compliance required by policy, but %d violation(s) were detected.', $upper, $stdViolations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Banned / Zero-Tolerance Rules
|
||||
if (isset($this->policy['banned_rules']) && is_array($this->policy['banned_rules'])) {
|
||||
foreach ($this->policy['banned_rules'] as $bannedRule) {
|
||||
if (!is_string($bannedRule)) {
|
||||
continue;
|
||||
}
|
||||
if (isset($ruleCounts[$bannedRule])) {
|
||||
$failures[] = sprintf('Zero-tolerance rule "%s" was violated %d time(s).', $bannedRule, $ruleCounts[$bannedRule]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. POUR Principle Thresholds
|
||||
if (isset($this->policy['principle_limits']) && is_array($this->policy['principle_limits'])) {
|
||||
$matrixGen = new ComplianceMatrixGenerator();
|
||||
$matrix = $matrixGen->generate($violations);
|
||||
foreach ($this->policy['principle_limits'] as $principle => $maxAllowed) {
|
||||
if (!is_string($principle) || !is_numeric($maxAllowed)) {
|
||||
continue;
|
||||
}
|
||||
$actual = $matrix['principles'][$principle]['violations'] ?? 0;
|
||||
if ($actual > (int)$maxAllowed) {
|
||||
$failures[] = sprintf('POUR Principle "%s" has %d violation(s), exceeding policy limit of %d.', $principle, $actual, (int)$maxAllowed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new PolicyResult(
|
||||
passed: empty($failures),
|
||||
failures: $failures,
|
||||
summary: [
|
||||
'score' => $score,
|
||||
'counts' => $counts,
|
||||
'standards' => $standardCounts,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function hasPolicies(): bool
|
||||
{
|
||||
return !empty($this->policy);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Policy;
|
||||
|
||||
class PolicyResult
|
||||
{
|
||||
/**
|
||||
* @param bool $passed
|
||||
* @param string[] $failures
|
||||
* @param array<string, mixed> $summary
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly bool $passed,
|
||||
public readonly array $failures = [],
|
||||
public readonly array $summary = []
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{passed: bool, failures: string[], summary: array<string, mixed>}
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'passed' => $this->passed,
|
||||
'failures' => $this->failures,
|
||||
'summary' => $this->summary,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class BankingPreset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'banking';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Financial services & digital banking accessibility profile (EAA 2025 + WCAG 2.2 AA).';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_2_2_1_TIMEOUT_WARNING',
|
||||
'WCAG_3_3_1_FORM_ERROR_SUMMARY',
|
||||
'WCAG_3_3_7_REDUNDANT_ENTRY',
|
||||
'WCAG_3_3_8_ACCESSIBLE_AUTH',
|
||||
'WCAG_4_1_2_PASSWORD_VISIBILITY_TOGGLE',
|
||||
'WCAG_4_1_3_STATUS_MESSAGES',
|
||||
'WCAG_1_4_3_CONTRAST',
|
||||
'WCAG_2_5_8_TARGET_SIZE',
|
||||
'WCAG_2_4_7_FOCUS_OUTLINE',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class Bitv2Preset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'bitv2';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'German BITV 2.0 (Barrierefreie-Informationstechnik-Verordnung) public accessibility profile.';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 5;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_4_3_CONTRAST',
|
||||
'WCAG_1_4_12_TEXT_SPACING',
|
||||
'WCAG_2_4_7_FOCUS_OUTLINE',
|
||||
'WCAG_3_1_1_LANG',
|
||||
'WCAG_3_1_2_LANG',
|
||||
'WCAG_3_1_4_ABBR_TITLE',
|
||||
'WCAG_2_4_1_SkipNavigation',
|
||||
'WCAG_2_4_6_DOCUMENT_H1',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class ECommercePreset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'ecommerce';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'E-Commerce storefront and checkout flow accessibility profile.';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_1_1_IMG_ALT',
|
||||
'WCAG_4_1_2_BUTTON',
|
||||
'WCAG_1_3_1_FORM_LABEL',
|
||||
'WCAG_3_3_7_REDUNDANT_ENTRY',
|
||||
'WCAG_2_5_8_TARGET_SIZE',
|
||||
'WCAG_1_4_3_CONTRAST',
|
||||
'WCAG_4_1_2_DIALOG',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class Eaa2025Preset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'eaa2025';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'European Accessibility Act (Directive EU 2019/882) digital services & products profile.';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_4_3_CONTRAST',
|
||||
'WCAG_2_4_7_FOCUS_OUTLINE',
|
||||
'WCAG_2_5_8_TARGET_SIZE',
|
||||
'WCAG_3_3_8_ACCESSIBLE_AUTH',
|
||||
'WCAG_3_3_7_REDUNDANT_ENTRY',
|
||||
'WCAG_1_4_12_TEXT_SPACING',
|
||||
'WCAG_2_5_3_LABEL_IN_NAME',
|
||||
'WCAG_1_3_4_ORIENTATION_LOCK',
|
||||
'WCAG_4_1_3_STATUS_MESSAGES',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class EducationPreset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'education';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Higher education, LMS & academic portal accessibility profile (ADA Title II & WCAG 2.2 AA).';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_1_1_ALT',
|
||||
'WCAG_1_2_1_AudioTrack',
|
||||
'WCAG_1_2_2_VIDEO_TRACK',
|
||||
'WCAG_1_2_2_TRACK_VALIDATION',
|
||||
'WCAG_1_3_1_TABLE',
|
||||
'WCAG_1_3_1_TABLE_CAPTION',
|
||||
'WCAG_2_4_4_LINK_DOWNLOAD_CONTEXT',
|
||||
'WCAG_2_4_6_DOCUMENT_H1',
|
||||
'WCAG_3_1_1_LANG',
|
||||
'WCAG_3_1_4_ABBR_TITLE',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class En301549Preset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'en301549';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'European Union EN 301 549 public sector digital accessibility profile.';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_4_3_CONTRAST',
|
||||
'WCAG_2_4_7_FOCUS_OUTLINE',
|
||||
'WCAG_2_5_8_TARGET_SIZE',
|
||||
'WCAG_1_4_12_TEXT_SPACING',
|
||||
'WCAG_2_5_3_LABEL_IN_NAME',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class GovernmentPreset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'government';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Public sector & e-Government digital accessibility profile (WCAG 2.2 AA + EN 301 549).';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 5;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_1_1_ALT',
|
||||
'WCAG_1_4_3_CONTRAST',
|
||||
'WCAG_2_4_1_SkipNavigation',
|
||||
'WCAG_2_4_2_PAGE_TITLE',
|
||||
'WCAG_2_4_6_DOCUMENT_H1',
|
||||
'WCAG_2_4_7_FOCUS_OUTLINE',
|
||||
'WCAG_3_1_1_LANG',
|
||||
'WCAG_3_3_1_FORM_ERROR_SUMMARY',
|
||||
'WCAG_3_3_8_ACCESSIBLE_AUTH',
|
||||
'WCAG_2_4_4_LINK_DOWNLOAD_CONTEXT',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class HealthcarePreset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'healthcare';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Healthcare & patient portal accessibility profile (HHS Section 504 & WCAG 2.2 AA/AAA readability).';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 5;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_4_3_CONTRAST',
|
||||
'WCAG_1_4_4_FONT_SIZE_MIN',
|
||||
'WCAG_1_4_12_TEXT_SPACING',
|
||||
'WCAG_2_2_1_TIMEOUT_WARNING',
|
||||
'WCAG_2_3_1_FLASHING_CONTENT',
|
||||
'WCAG_2_3_3_REDUCED_MOTION',
|
||||
'WCAG_3_2_6_CONSISTENT_HELP',
|
||||
'WCAG_3_3_1_FORM_ERROR_SUMMARY',
|
||||
'WCAG_3_3_7_REDUNDANT_ENTRY',
|
||||
'WCAG_3_3_8_ACCESSIBLE_AUTH',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
interface PresetInterface
|
||||
{
|
||||
public function getName(): string;
|
||||
|
||||
public function getDescription(): string;
|
||||
|
||||
public function getLevel(): int;
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getIncludedRules(): array;
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getExcludedRules(): array;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class PresetRegistry
|
||||
{
|
||||
/**
|
||||
* @var array<string, PresetInterface>
|
||||
*/
|
||||
private array $presets = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->register(new Section508Preset());
|
||||
$this->register(new En301549Preset());
|
||||
$this->register(new ECommercePreset());
|
||||
$this->register(new Wcag22AAPreset());
|
||||
$this->register(new Wcag22AAAPreset());
|
||||
$this->register(new Eaa2025Preset());
|
||||
$this->register(new Bitv2Preset());
|
||||
$this->register(new GovernmentPreset());
|
||||
$this->register(new HealthcarePreset());
|
||||
$this->register(new BankingPreset());
|
||||
$this->register(new EducationPreset());
|
||||
}
|
||||
|
||||
public function register(PresetInterface $preset): void
|
||||
{
|
||||
$this->presets[strtolower($preset->getName())] = $preset;
|
||||
}
|
||||
|
||||
public function get(string $name): ?PresetInterface
|
||||
{
|
||||
return $this->presets[strtolower($name)] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, PresetInterface>
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return $this->presets;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class Section508Preset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'section508';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'US Federal Government Section 508 accessibility compliance profile.';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 3;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_1_1_IMG_ALT',
|
||||
'WCAG_1_3_1_TABLE',
|
||||
'WCAG_1_3_1_TABLE_HEADERS_ATTR',
|
||||
'WCAG_1_3_1_FORM_LABEL',
|
||||
'WCAG_2_1_1_KEYBOARD_CLICK',
|
||||
'WCAG_2_4_2_PAGE_TITLE',
|
||||
'WCAG_3_1_1_LANG',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class Wcag22AAAPreset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'wcag22-aaa';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Strictest W3C WCAG 2.2 Level A, AA & AAA compliance profile (all 175 rules).';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 5;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_1_4_6_CONTRAST_AAA',
|
||||
'WCAG_2_4_13_FOCUS_APPEARANCE',
|
||||
'WCAG_2_3_3_REDUCED_MOTION',
|
||||
'WCAG_3_1_4_ABBR_TITLE',
|
||||
'WCAG_1_4_8_TEXT_JUSTIFY',
|
||||
'WCAG_3_1_5_ALL_CAPS_LONG',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Presets;
|
||||
|
||||
class Wcag22AAPreset implements PresetInterface
|
||||
{
|
||||
public function getName(): string
|
||||
{
|
||||
return 'wcag22-aa';
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Full W3C WCAG 2.2 Level A & AA compliance profile.';
|
||||
}
|
||||
|
||||
public function getLevel(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function getIncludedRules(): array
|
||||
{
|
||||
return [
|
||||
'WCAG_2_4_11_FOCUS_NOT_OBSCURED',
|
||||
'WCAG_2_5_7_DRAGGING_MOVEMENTS',
|
||||
'WCAG_2_5_8_TARGET_SIZE',
|
||||
'WCAG_2_5_8_TARGET_SPACING',
|
||||
'WCAG_3_2_6_CONSISTENT_HELP',
|
||||
'WCAG_3_3_7_REDUNDANT_ENTRY',
|
||||
'WCAG_3_3_8_ACCESSIBLE_AUTH',
|
||||
'WCAG_1_4_3_CONTRAST',
|
||||
'WCAG_2_4_7_FOCUS_OUTLINE',
|
||||
];
|
||||
}
|
||||
|
||||
public function getExcludedRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Reference;
|
||||
|
||||
class WcagCriterion
|
||||
{
|
||||
public function __construct(
|
||||
public string $id,
|
||||
public string $title,
|
||||
public string $level,
|
||||
public string $url,
|
||||
public string $description,
|
||||
public string $badExample,
|
||||
public string $goodExample
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array{id: string, title: string, level: string, url: string, description: string, badExample: string, goodExample: string}
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'title' => $this->title,
|
||||
'level' => $this->level,
|
||||
'url' => $this->url,
|
||||
'description' => $this->description,
|
||||
'badExample' => $this->badExample,
|
||||
'goodExample' => $this->goodExample,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Reference;
|
||||
|
||||
class WcagDatabase
|
||||
{
|
||||
/** @var array<string, WcagCriterion> */
|
||||
private static array $criteria = [];
|
||||
|
||||
public static function load(): void
|
||||
{
|
||||
if (!empty(self::$criteria)) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_2_2_BLINK',
|
||||
title: '2.2.2 Pause, Stop, Hide',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/pause-stop-hide.html',
|
||||
description: 'The <blink> tag causes flashing text, presenting significant cognitive and visual accessibility barriers.',
|
||||
badExample: '<blink>Blinking Text</blink>',
|
||||
goodExample: '<span class="attention-style">Styled Text</span>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_3_1_DUPLICATE_H1',
|
||||
title: '1.3.1 Info and Relationships',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships.html',
|
||||
description: 'Pages should contain exactly one h1 element to present a clear hierarchy and entry point for screen readers.',
|
||||
badExample: '<h1>Title</h1><h1>Another Title</h1>',
|
||||
goodExample: '<h1>Title</h1><h2>Subtitle</h2>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_3_5_AUTOCOMPLETE',
|
||||
title: '1.3.5 Identify Input Purpose',
|
||||
level: 'AA',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/identify-input-purpose.html',
|
||||
description: 'Inputs collecting user personal info must have autocomplete attributes to assist users with cognitive impairments.',
|
||||
badExample: '<input type="email" name="email">',
|
||||
goodExample: '<input type="email" name="email" autocomplete="email">'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_1_1_SCROLLABLE_FOCUS',
|
||||
title: '2.1.1 Keyboard',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/keyboard.html',
|
||||
description: 'Scrollable regions must be focusable using keyboard navigation (tabindex="0") so keyboard-only users can scroll them.',
|
||||
badExample: '<div style="overflow: scroll; height: 100px;">Scrollable content</div>',
|
||||
goodExample: '<div style="overflow: scroll; height: 100px;" tabindex="0">Scrollable content</div>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_4_1_2_ARIA_LABELLEDBY',
|
||||
title: '4.1.2 Name, Role, Value',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
|
||||
description: 'aria-labelledby and aria-describedby attributes must refer to existing element IDs to prevent screen readers from reading empty contexts.',
|
||||
badExample: '<button aria-labelledby="missing_id">Submit</button>',
|
||||
goodExample: '<div id="btn_lbl">Submit Form</div><button aria-labelledby="btn_lbl">Submit</button>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_1_1_ALT_PLACEHOLDER',
|
||||
title: '1.1.1 Non-text Content',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html',
|
||||
description: 'Alt attributes must not contain placeholder words or file names. They should provide a meaningful description of the image content.',
|
||||
badExample: '<img src="logo.png" alt="logo">',
|
||||
goodExample: '<img src="logo.png" alt="YakNet Logo">'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_1_1_SVG',
|
||||
title: '1.1.1 Non-text Content',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html',
|
||||
description: 'Inline SVGs must either contain alternative descriptions or be hidden from assistive technologies using aria-hidden="true".',
|
||||
badExample: '<svg><circle cx="5" cy="5" r="5"></svg>',
|
||||
goodExample: '<svg aria-hidden="true"><circle cx="5" cy="5" r="5"></svg>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_3_1_TABLE_SUMMARY',
|
||||
title: '1.3.1 Info and Relationships',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships.html',
|
||||
description: 'The summary attribute on <table> is deprecated in HTML5. Use <caption> elements for tables description instead.',
|
||||
badExample: '<table summary="Table Summary">',
|
||||
goodExample: '<table><caption>Table Description</caption>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_3_1_PRESENTATION_TAGS',
|
||||
title: '1.3.1 Info and Relationships',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships.html',
|
||||
description: 'Obsolete presentation tags like <center> and <strike> are banned. Use standard CSS classes or styling.',
|
||||
badExample: '<center>Centered Text</center>',
|
||||
goodExample: '<span style="text-align: center; display: block;">Centered Text</span>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_4_3_AUTOFOCUS',
|
||||
title: '2.4.3 Focus Order',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/focus-order.html',
|
||||
description: 'autofocus attribute can cause keyboard traps and disorient blind/low-vision users on page load. Focus should be managed contextually.',
|
||||
badExample: '<input name="search" autofocus>',
|
||||
goodExample: '<input name="search">'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_5_8_TARGET_SIZE',
|
||||
title: '2.5.8 Target Size (Minimum)',
|
||||
level: 'AA',
|
||||
url: 'https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html',
|
||||
description: 'The size of the target for pointer inputs is at least 24 by 24 CSS pixels.',
|
||||
badExample: '<button style="width: 16px; height: 16px;">X</button>',
|
||||
goodExample: '<button style="width: 24px; height: 24px;">X</button>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_3_1_DETAILS_SUMMARY',
|
||||
title: '1.3.1 Info and Relationships',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships.html',
|
||||
description: '<details> elements must have a <summary> element to serve as an accessible disclosure trigger.',
|
||||
badExample: '<details><p>Details content</p></details>',
|
||||
goodExample: '<details><summary>More info</summary><p>Details content</p></details>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_4_1_2_ARIA_CURRENT',
|
||||
title: '4.1.2 Name, Role, Value',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
|
||||
description: 'The aria-current attribute must have a valid value indicating the current item in a set.',
|
||||
badExample: '<a href="/home" aria-current="active">Home</a>',
|
||||
goodExample: '<a href="/home" aria-current="page">Home</a>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_3_3_1_ARIA_ERRORMESSAGE',
|
||||
title: '3.3.1 Error Identification',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/error-identification.html',
|
||||
description: 'aria-errormessage must reference a valid error element and control must have aria-invalid="true".',
|
||||
badExample: '<input name="email" aria-errormessage="email_error">',
|
||||
goodExample: '<input name="email" aria-invalid="true" aria-errormessage="email_err"><span id="email_err">Invalid email</span>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_4_1_2_ARIA_ROLEDESCRIPTION',
|
||||
title: '4.1.2 Name, Role, Value',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
|
||||
description: 'aria-roledescription must only be used on elements with a non-generic role.',
|
||||
badExample: '<div aria-roledescription="slide">Slide 1</div>',
|
||||
goodExample: '<div role="region" aria-roledescription="slide" aria-label="Slide 1">Slide 1</div>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_4_1_2_ARIA_PROHIBITED_ATTR',
|
||||
title: '4.1.2 Name, Role, Value',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
|
||||
description: 'Prohibited ARIA attributes must not be used on presentation or generic roles.',
|
||||
badExample: '<div role="presentation" aria-label="decorative"></div>',
|
||||
goodExample: '<div role="presentation"></div>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_3_2_HTML_DIR',
|
||||
title: '1.3.2 Meaningful Sequence',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/meaningful-sequence.html',
|
||||
description: 'The dir attribute must only use valid values: ltr, rtl, or auto.',
|
||||
badExample: '<p dir="left">Text</p>',
|
||||
goodExample: '<p dir="ltr">Text</p>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_3_1_SELECT_CHILDREN',
|
||||
title: '1.3.1 Info and Relationships',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships.html',
|
||||
description: '<select> elements must only contain valid child elements (<option>, <optgroup>).',
|
||||
badExample: '<select><div>Option 1</div></select>',
|
||||
goodExample: '<select><option>Option 1</option></select>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_1_1_ROLE_IMG',
|
||||
title: '1.1.1 Non-text Content',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html',
|
||||
description: 'Elements with role="img" must have an accessible name.',
|
||||
badExample: '<span role="img" class="icon-star"></span>',
|
||||
goodExample: '<span role="img" class="icon-star" aria-label="5 stars rating"></span>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_4_2_MEDIA_CONTROLS',
|
||||
title: '1.4.2 Audio Control',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/audio-control.html',
|
||||
description: 'Audio and video media elements should provide user controls for playback and volume.',
|
||||
badExample: '<audio src="podcast.mp3"></audio>',
|
||||
goodExample: '<audio src="podcast.mp3" controls></audio>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_2_2_TRACK_VALIDATION',
|
||||
title: '1.2.2 Captions (Prerecorded)',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/captions-prerecorded.html',
|
||||
description: '<track> elements must have valid kind, srclang, and label attributes.',
|
||||
badExample: '<track src="sub.vtt" kind="captions">',
|
||||
goodExample: '<track src="sub.vtt" kind="captions" srclang="en" label="English">'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_1_1_ACCESSKEY_DUPLICATE',
|
||||
title: '2.1.1 Keyboard',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/keyboard.html',
|
||||
description: 'accesskey attribute values must be unique across the document.',
|
||||
badExample: '<a href="/" accesskey="h">Home</a><a href="/help" accesskey="h">Help</a>',
|
||||
goodExample: '<a href="/" accesskey="h">Home</a><a href="/help" accesskey="p">Help</a>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_4_1_2_BUTTON_NESTED_INTERACTIVE',
|
||||
title: '4.1.2 Name, Role, Value',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
|
||||
description: '<button> elements must not contain nested interactive elements.',
|
||||
badExample: '<button><a href="/cart">Checkout</a></button>',
|
||||
goodExample: '<a href="/cart" class="btn">Checkout</a>'
|
||||
));
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_4_11_FOCUS_NOT_OBSCURED',
|
||||
title: '2.4.11 Focus Not Obscured (Minimum)',
|
||||
level: 'AA',
|
||||
url: 'https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-minimum.html',
|
||||
description: 'Fixed or sticky headers and overlays must not completely obscure keyboard-focused elements.',
|
||||
badExample: '<header style="position: fixed; top: 0; width: 100%; height: 80px;"></header>',
|
||||
goodExample: '<html style="scroll-padding-top: 80px;"><header style="position: fixed; top: 0; width: 100%; height: 80px;"></header></html>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_5_7_DRAGGING_MOVEMENTS',
|
||||
title: '2.5.7 Dragging Movements',
|
||||
level: 'AA',
|
||||
url: 'https://www.w3.org/WAI/WCAG22/Understanding/dragging-movements.html',
|
||||
description: 'Elements supporting drag-and-drop operations must provide a single-pointer alternative.',
|
||||
badExample: '<div draggable="true" class="list-item">Item 1</div>',
|
||||
goodExample: '<div draggable="true" class="list-item">Item 1 <button>Move Up</button> <button>Move Down</button></div>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_4_1_2_ARIA_LABEL_GENERIC',
|
||||
title: '4.1.2 Name, Role, Value',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
|
||||
description: 'Generic <div> or <span> elements should not use aria-label without an explicit ARIA role.',
|
||||
badExample: '<div aria-label="Important Notice">Text</div>',
|
||||
goodExample: '<div role="region" aria-label="Important Notice">Text</div>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_3_5_AUTOCOMPLETE_APPROPRIATE',
|
||||
title: '1.3.5 Identify Input Purpose',
|
||||
level: 'AA',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/identify-input-purpose.html',
|
||||
description: 'Input autocomplete value must be semantically appropriate for the input type.',
|
||||
badExample: '<input type="number" autocomplete="email">',
|
||||
goodExample: '<input type="email" autocomplete="email">'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_4_13_FOCUS_APPEARANCE',
|
||||
title: '2.4.13 Focus Appearance',
|
||||
level: 'AAA',
|
||||
url: 'https://www.w3.org/WAI/WCAG22/Understanding/focus-appearance.html',
|
||||
description: 'Focus indicators must enclose the element with at least a 2px perimeter and sufficient contrast.',
|
||||
badExample: '<style>a:focus { outline: 1px dotted #ccc; }</style>',
|
||||
goodExample: '<style>a:focus-visible { outline: 2px solid #005fcc; outline-offset: 2px; }</style>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_3_1_FLASHING_CONTENT',
|
||||
title: '2.3.1 Three Flashes or Below Threshold',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/three-flashes-or-below-threshold.html',
|
||||
description: 'Web pages must not contain anything that flashes more than three times in any one second period.',
|
||||
badExample: '<div style="animation: flash 0.15s infinite;">Alert</div>',
|
||||
goodExample: '<div style="animation: fade 1.2s ease-in-out;">Alert</div>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_3_3_REDUCED_MOTION',
|
||||
title: '2.3.3 Animation from Interactions',
|
||||
level: 'AAA',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/animation-from-interactions.html',
|
||||
description: 'Motion animation triggered by interaction can be disabled unless essential.',
|
||||
badExample: '<style>@keyframes slide { from { left: 0; } to { left: 100px; } }</style>',
|
||||
goodExample: '<style>@keyframes slide { from { left: 0; } to { left: 100px; } } @media (prefers-reduced-motion: reduce) { * { animation: none !important; } }</style>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_3_4_ORIENTATION_LOCK',
|
||||
title: '1.3.4 Orientation',
|
||||
level: 'AA',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/orientation.html',
|
||||
description: 'Content does not restrict its view and operation to a single display orientation such as portrait or landscape.',
|
||||
badExample: '<style>@media (orientation: landscape) { body { display: none; } }</style>',
|
||||
goodExample: '<style>.layout { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); }</style>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_4_1_2_ARIA_TABLIST',
|
||||
title: '4.1.2 Name, Role, Value (APG Tabs)',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/ARIA/apg/patterns/tabs/',
|
||||
description: 'ARIA Tabs require role="tablist", child role="tab" with aria-selected & aria-controls, and role="tabpanel" with aria-labelledby.',
|
||||
badExample: '<div role="tablist"><button role="tab">Tab 1</button></div>',
|
||||
goodExample: '<div role="tablist"><button id="t1" role="tab" aria-selected="true" aria-controls="p1">Tab 1</button></div><div id="p1" role="tabpanel" aria-labelledby="t1">Panel</div>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_4_1_2_ARIA_COMBOBOX',
|
||||
title: '4.1.2 Name, Role, Value (APG Combobox)',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/ARIA/apg/patterns/combobox/',
|
||||
description: 'Combobox controls require aria-expanded, aria-controls (or aria-owns), and an accessible name.',
|
||||
badExample: '<input role="combobox">',
|
||||
goodExample: '<input role="combobox" aria-expanded="false" aria-controls="city-list" aria-label="Select City">'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_3_2_6_CONSISTENT_HELP',
|
||||
title: '3.2.6 Consistent Help',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG22/Understanding/consistent-help.html',
|
||||
description: 'Help mechanisms appear in the same relative order across pages where they are provided.',
|
||||
badExample: '<body><header><nav><a href="/">Home</a></nav></header><form><input type="text"></form></body>',
|
||||
goodExample: '<body><header><nav><a href="/">Home</a><a href="/help">Help</a></nav></header><form><input type="text"></form></body>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_1_4_6_CONTRAST_AAA',
|
||||
title: '1.4.6 Contrast (Enhanced)',
|
||||
level: 'AAA',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/contrast-enhanced.html',
|
||||
description: 'Visual presentation of text has a contrast ratio of at least 7:1 (4.5:1 for large text).',
|
||||
badExample: '<p style="color: #767676; background-color: #ffffff;">Gray text</p>',
|
||||
goodExample: '<p style="color: #333333; background-color: #ffffff;">High contrast text</p>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_5_2_POINTER_CANCELLATION',
|
||||
title: '2.5.2 Pointer Cancellation',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/pointer-cancellation.html',
|
||||
description: 'Functions operated using a single pointer should not execute on the down-event.',
|
||||
badExample: '<button onmousedown="deleteItem()">Delete</button>',
|
||||
goodExample: '<button onclick="deleteItem()">Delete</button>'
|
||||
));
|
||||
|
||||
self::add(new WcagCriterion(
|
||||
id: 'WCAG_2_1_4_CHAR_KEY_SHORTCUTS',
|
||||
title: '2.1.4 Character Key Shortcuts',
|
||||
level: 'A',
|
||||
url: 'https://www.w3.org/WAI/WCAG21/Understanding/character-key-shortcuts.html',
|
||||
description: 'Single printable character keyboard shortcuts must use a modifier or be remappable/disableable.',
|
||||
badExample: '<button aria-keyshortcuts="s">Save</button>',
|
||||
goodExample: '<button aria-keyshortcuts="Control+S">Save</button>'
|
||||
));
|
||||
}
|
||||
|
||||
public static function add(WcagCriterion $criterion): void
|
||||
{
|
||||
self::$criteria[$criterion->id] = $criterion;
|
||||
}
|
||||
|
||||
public static function get(string $ruleId): ?WcagCriterion
|
||||
{
|
||||
self::load();
|
||||
if (isset(self::$criteria[$ruleId])) {
|
||||
return self::$criteria[$ruleId];
|
||||
}
|
||||
|
||||
// Prefix fallback: match by WCAG success criterion prefix (e.g. WCAG_1_1_1_* -> any WCAG_1_1_1_*)
|
||||
if (preg_match('/^(WCAG_\d+_\d+_\d+)/', $ruleId, $m)) {
|
||||
$prefix = $m[1];
|
||||
foreach (self::$criteria as $id => $criterion) {
|
||||
if (str_starts_with($id, $prefix)) {
|
||||
return $criterion;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, WcagCriterion>
|
||||
*/
|
||||
public static function all(): array
|
||||
{
|
||||
self::load();
|
||||
return self::$criteria;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Reference;
|
||||
|
||||
class WcagReference
|
||||
{
|
||||
/**
|
||||
* Look up the WCAG Success Criterion for a given rule ID.
|
||||
*
|
||||
* @param string $ruleId
|
||||
* @return WcagCriterion|null
|
||||
*/
|
||||
public static function lookup(string $ruleId): ?WcagCriterion
|
||||
{
|
||||
return WcagDatabase::get($ruleId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a list of all WCAG criteria mapped in the console.
|
||||
*
|
||||
* @return array<string, WcagCriterion>
|
||||
*/
|
||||
public static function getCatalog(): array
|
||||
{
|
||||
return WcagDatabase::all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Reporting;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use YakNet\AccessibilityConsole\Core\Severity;
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
|
||||
/**
|
||||
* Formats accessibility violations in standard Checkstyle XML format
|
||||
* for integration with Jenkins, PhpStorm, SonarQube, and GitLab CI.
|
||||
*/
|
||||
class CheckstyleFormatter implements FormatterInterface
|
||||
{
|
||||
/**
|
||||
* @param Violation[] $violations
|
||||
* @param int $baselinedCount
|
||||
* @param SymfonyStyle $io
|
||||
* @return int
|
||||
*/
|
||||
public function format(array $violations, int $baselinedCount, SymfonyStyle $io): int
|
||||
{
|
||||
$io->write($this->render($violations));
|
||||
return empty($violations) ? Command::SUCCESS : Command::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render Checkstyle XML string.
|
||||
*
|
||||
* @param Violation[] $violations
|
||||
*/
|
||||
public function render(array $violations): string
|
||||
{
|
||||
/** @var array<string, Violation[]> $grouped */
|
||||
$grouped = [];
|
||||
foreach ($violations as $v) {
|
||||
$file = $v->location['file'] ?? 'unknown';
|
||||
$grouped[$file][] = $v;
|
||||
}
|
||||
|
||||
$xml = [];
|
||||
$xml[] = '<?xml version="1.0" encoding="UTF-8"?>';
|
||||
$xml[] = '<checkstyle version="4.0.0">';
|
||||
|
||||
foreach ($grouped as $file => $fileViolations) {
|
||||
$xml[] = sprintf(' <file name="%s">', $this->escapeAttr($file));
|
||||
foreach ($fileViolations as $v) {
|
||||
$line = isset($v->location['line']) ? max(1, (int)$v->location['line']) : 1;
|
||||
$col = isset($v->location['column']) ? max(1, (int)$v->location['column']) : 1;
|
||||
$sev = match ($v->severity) {
|
||||
Severity::CRITICAL, Severity::ERROR => 'error',
|
||||
Severity::WARNING => 'warning',
|
||||
Severity::INFO => 'info',
|
||||
};
|
||||
$source = 'YakNet.Accessibility.' . $v->ruleId;
|
||||
|
||||
$xml[] = sprintf(
|
||||
' <error line="%d" column="%d" severity="%s" message="%s" source="%s"/>',
|
||||
$line,
|
||||
$col,
|
||||
$sev,
|
||||
$this->escapeAttr($v->message),
|
||||
$this->escapeAttr($source)
|
||||
);
|
||||
}
|
||||
$xml[] = ' </file>';
|
||||
}
|
||||
|
||||
$xml[] = '</checkstyle>';
|
||||
|
||||
return implode("\n", $xml) . "\n";
|
||||
}
|
||||
|
||||
private function escapeAttr(string $value): string
|
||||
{
|
||||
return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace YakNet\AccessibilityConsole\Reporting;
|
||||
|
||||
use YakNet\AccessibilityConsole\Core\Violation;
|
||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
|
||||
class CsvFormatter implements FormatterInterface
|
||||
{
|
||||
public function format(array $violations, int $baselinedCount, SymfonyStyle $io): int
|
||||
{
|
||||
$out = fopen('php://temp', 'w+');
|
||||
if ($out === false) {
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// Write header
|
||||
fputcsv($out, ['Rule ID', 'Severity', 'Standard', 'File', 'Line', 'Message', 'HTML Snippet', 'Fix Suggestion'], ',', '"', '\\');
|
||||
|
||||
foreach ($violations as $v) {
|
||||
$file = $v->location['file'] ?? 'unknown';
|
||||
$line = $v->location['line'] ?? 0;
|
||||
fputcsv($out, [
|
||||
$v->ruleId,
|
||||
$v->severity->value,
|
||||
$v->standard->value,
|
||||
$file,
|
||||
$line,
|
||||
$v->message,
|
||||
$v->htmlSnippet,
|
||||
$v->fixSuggestion
|
||||
], ',', '"', '\\');
|
||||
}
|
||||
|
||||
rewind($out);
|
||||
$csv = stream_get_contents($out);
|
||||
fclose($out);
|
||||
|
||||
$io->write($csv ?: '');
|
||||
|
||||
return empty($violations) ? Command::SUCCESS : Command::FAILURE;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user