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 | ||
|
|
7f3bf3cb7d | ||
|
|
8e6ea62ba7 | ||
|
|
c138cbca65 | ||
|
|
18aa4641d2 | ||
|
|
c4745d6cb3 | ||
|
|
a2b984df04 | ||
|
|
d5165f0be4 | ||
|
|
84c6521195 | ||
|
|
0134482c54 | ||
|
|
c9ffbdba08 | ||
|
|
2a97138fec | ||
|
|
c42ab714ff | ||
|
|
b805741ef2 | ||
|
|
84f713e434 | ||
|
|
c6df5e2bdc | ||
|
|
75171c6f96 | ||
|
|
1ea2579d20 | ||
|
|
873b4c4233 | ||
|
|
d219272487 | ||
|
|
09f33650ec | ||
|
|
3a19c1c534 |
@@ -4,3 +4,5 @@
|
|||||||
/rapor.html
|
/rapor.html
|
||||||
/.phpunit.result.cache
|
/.phpunit.result.cache
|
||||||
/phpstan-baseline.neon
|
/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
|
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
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
|||||||
@@ -1,96 +1,293 @@
|
|||||||
# YakNet Accessibility Console 2.0 (AI-Powered)
|
# YakNet Accessibility Console 4.0
|
||||||
|
|
||||||
[](https://php.net)
|
[](https://php.net)
|
||||||
|
[](https://phpstan.org)
|
||||||
|
[](https://www.w3.org/WAI/standards-guidelines/wcag/)
|
||||||
|
[](#-mevzuat-ve-sektörel-ön-ayarlar-presets)
|
||||||
[](LICENSE)
|
[](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 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.
|
||||||
|
|
||||||
|
**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
|
## 🌟 Öne Çıkan Özellikler
|
||||||
|
|
||||||
- **🤖 AI Self-Healing:** Tespit edilen WCAG hataları için Google Gemini AI üzerinden akıllı çözüm önerileri alır ve isterseniz kaynak kodunuzu (Blade, Twig, PHP) otomatik olarak tamir eder.
|
- **🛡️ 175 Benzersiz WCAG 2.1 / 2.2, WAI-ARIA 1.2 & APG Kuralı:**
|
||||||
- **⚡ Modern CLI:** Rust/Vite tarzı şık bir komut satırı arayüzü ile saniyeler içinde tarama ve düzeltme yapın.
|
- **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).
|
||||||
- **📊 Görsel Dashboard:** Tarama sonuçlarını modern ve şık bir HTML raporu olarak dışarı aktarın.
|
- **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`).
|
||||||
- **🔍 Akıllı Kaynak Tespiti:** Hataları projenizdeki tam dosya yolu ve satır numarası ile eşleştirir.
|
- **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).
|
||||||
- **🛠️ Geliştirici Dostu:** PSR-4 uyumlu, modern PHP 8.2+ mimarisi ve genişletilebilir kural motoru.
|
- **📋 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
|
## 📦 Kurulum
|
||||||
|
|
||||||
Composer ile projenize hemen dahil edin:
|
Composer ile projenize geliştirme bağımlılığı olarak ekleyin:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
composer require yaknet/accessibility-console
|
composer require --dev yaknet/accessibility-console
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🚀 CLI Kullanımı
|
---
|
||||||
|
|
||||||
Kütüphane, `vendor/bin/a11y` (veya kütüphane dizininde `bin/a11y`) üzerinden kullanılabilir.
|
## 🚀 Komut Satırı (CLI) Kullanımı
|
||||||
|
|
||||||
### 1. Standart Tarama
|
YakNet Accessibility Console **10 komut** sunar: `scan`, `fix`, `vpat`, `compare`, `rules`, `explain`, `presets`, `doctor`, `watch`, `init`.
|
||||||
Bir URL'yi veya yerel bir HTML dosyasını tarayın:
|
|
||||||
|
### 1. Yapılandırma Oluşturma (`init`) ve Sistem Kontrolü (`doctor`)
|
||||||
```bash
|
```bash
|
||||||
bin/a11y scan https://test-siteniz.com
|
# 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. AI Destekli Tarama ve Raporlama
|
### 2. Proje, Şablon veya Canlı URL Tarama (`scan`)
|
||||||
Yapay zeka önerileriyle birlikte tarama yapın ve sonucu HTML olarak kaydedin:
|
|
||||||
```bash
|
```bash
|
||||||
bin/a11y scan https://test-siteniz.com --ai --report=sonuc.html
|
# a11y.yaml yapılandırmasına göre projeyi tara
|
||||||
|
bin/a11y scan
|
||||||
|
|
||||||
|
# Belirli bir dizini (Blade, Twig, Vue, JSX/TSX, HTML) tara
|
||||||
|
bin/a11y scan resources/views
|
||||||
|
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. Otomatik Düzeltme (Self-Healing) - **DEVRİMSEL**
|
### 3. VPAT 2.5 Uyumluluk Raporu Üretme (`vpat`)
|
||||||
Tespit edilen hataları yapay zekaya düzelttirin ve dosyalarınızı güncelleyin:
|
|
||||||
```bash
|
```bash
|
||||||
bin/a11y fix https://test-siteniz.com --project-path=/var/www/projeniz
|
# 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
|
||||||
```
|
```
|
||||||
|
|
||||||
## 💻 Kütüphane Olarak Kullanım
|
### 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 compare reports/before.json reports/after.json --fail-on-regression
|
||||||
|
```
|
||||||
|
|
||||||
Kendi PHP uygulamalarınızın içine entegre edin:
|
### 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
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🏛️ Mevzuat ve Sektörel Ön Ayarlar (Presets)
|
||||||
|
|
||||||
|
| Ö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
|
||||||
|
paths:
|
||||||
|
- resources/views
|
||||||
|
- src/components
|
||||||
|
|
||||||
|
exclude_paths:
|
||||||
|
- vendor
|
||||||
|
- node_modules
|
||||||
|
- storage
|
||||||
|
- tests
|
||||||
|
|
||||||
|
level: 4
|
||||||
|
preset: wcag22-aa
|
||||||
|
format: console
|
||||||
|
baseline: a11y-baseline.json
|
||||||
|
|
||||||
|
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
|
||||||
|
include:
|
||||||
|
- App\Rules\CustomAccessibilityRule
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔇 Satır İçi Gizleme Yönergeleri (Inline Suppressions)
|
||||||
|
|
||||||
|
İstisnai durumlarda belirli satır veya bloklarda kuralı gerekçesiyle birlikte gizleyebilirsiniz; tüm gizlemeler denetim kaydına alınır:
|
||||||
|
|
||||||
|
```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
|
```php
|
||||||
use YakNet\AccessibilityConsole\Core\Scanner;
|
// 1. Hızlı tarama ve skor hesaplama
|
||||||
use YakNet\AccessibilityConsole\Rules\StandardRuleSet;
|
$violations = a11y_scan($html, level: 4);
|
||||||
|
$score = a11y_score($html, level: 4);
|
||||||
|
|
||||||
// 1. Scanner'ı ve Kuralları Hazırla
|
// 2. Mevzuat ön ayarıyla tarama
|
||||||
$scanner = new Scanner();
|
$govViolations = a11y_scan_preset($html, 'government');
|
||||||
foreach (StandardRuleSet::all() as $rule) {
|
|
||||||
$scanner->addRule($rule);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. HTML İçeriğini Tara
|
// 3. VPAT 2.5 raporu ve POUR uyumluluk matrisi üretme
|
||||||
$html = file_get_contents('view.html');
|
$vpatMarkdown = a11y_vpat($html, format: 'markdown', productName: 'YakNet Portal');
|
||||||
$violations = $scanner->scan($html);
|
$matrix = a11y_compliance_matrix($html, level: 5);
|
||||||
|
|
||||||
// 3. Sonuçları İşle
|
// 4. Çevrimdışı deterministik hızlı onarım
|
||||||
foreach ($violations as $v) {
|
$fixedHtml = a11y_quick_fix($html);
|
||||||
echo "Hata: {$v->message} (Kural: {$v->ruleId})\n";
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## ⚙️ Yapılandırma
|
---
|
||||||
|
|
||||||
AI özelliklerini kullanabilmek için projenizin kök dizininde bir `.env` dosyası oluşturun ve **Google Gemini API** anahtarınızı ekleyin:
|
## 🧪 Geliştirme ve Test
|
||||||
|
|
||||||
```env
|
```bash
|
||||||
GEMINI_API_KEY=AIzaSyA...your_key_here
|
# 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/
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🛠️ Mevcut Kurallar (WCAG 2.1)
|
---
|
||||||
|
|
||||||
- **A11Y_VIEWPORT:** Zoom engelleme kontrolü.
|
|
||||||
- **WCAG_1_1_1_ALT:** Görsel alt metin kontrolü.
|
|
||||||
- **WCAG_1_3_1_LABEL:** Form etiketi kontrolü.
|
|
||||||
- **WCAG_1_3_1_FIELDSET:** Fieldset/Legend kontrolü.
|
|
||||||
- **WCAG_1_3_1_HEADING:** Başlık hiyerarşisi kontrolü.
|
|
||||||
- **WCAG_2_4_4_LINK_TEXT:** Boş link kontrolü.
|
|
||||||
- **WCAG_3_1_1_LANG:** HTML dil etiketi kontrolü.
|
|
||||||
- **WCAG_4_1_2_BUTTON:** Boş buton kontrolü.
|
|
||||||
|
|
||||||
## 🤝 Katkıda Bulunma
|
## 🤝 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
|
## 📜 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.
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
{
|
||||||
|
"generator": "YakNet Accessibility Console",
|
||||||
|
"violations": [
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "AriaRole",
|
||||||
|
"htmlSnippet": "<div role=\"cool-widget\" aria-controls=\"non-existent-popup\">WAI-ARIA elements</div>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "AriaRole",
|
||||||
|
"htmlSnippet": "<div role=\"cool-widget\" aria-controls=\"non-existent-popup\">WAI-ARIA elements</div>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "DuplicateId",
|
||||||
|
"htmlSnippet": "<h1 id=\"main-content\">Welcome to a broken page</h1>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "DuplicateId",
|
||||||
|
"htmlSnippet": "<div id=\"main-content\">This is a duplicate main-content ID div!</div>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT",
|
||||||
|
"htmlSnippet": "<img src=\"logo.png\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT_REDUNDANT",
|
||||||
|
"htmlSnippet": "<img src=\"logo2.png\" alt=\"logo of our company\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT_REDUNDANT",
|
||||||
|
"htmlSnippet": "<img src=\"profile.jpg\" alt=\"profile photo of john doe\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_1_2_2_VIDEO_TRACK",
|
||||||
|
"htmlSnippet": "<video src=\"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4\" width=\"320\" height=\"240\" controls=\"\"></video>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_1_3_1_EMPTY_HEADING",
|
||||||
|
"htmlSnippet": "<h2></h2>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_1_3_1_EMPTY_LABEL",
|
||||||
|
"htmlSnippet": "<label for=\"search-input\"></label>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_1_3_1_LABEL",
|
||||||
|
"htmlSnippet": "<input type=\"text\" placeholder=\"Search website...\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_2_1_1_ARIA_FOCUSABLE",
|
||||||
|
"htmlSnippet": "<div role=\"button\">Clickable div button without tabindex</div>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_2_4_2_PAGE_TITLE",
|
||||||
|
"htmlSnippet": "<head>\n <title></title>\n</head>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_2_4_3_TABINDEX",
|
||||||
|
"htmlSnippet": "<a href=\"/keyboard\" tabindex=\"5\">Keyboard test</a>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_2_4_4_LINK_GENERIC",
|
||||||
|
"htmlSnippet": "<a href=\"/read-more\">Click here</a>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_2_4_4_LINK_GENERIC",
|
||||||
|
"htmlSnippet": "<a href=\"/devam-oku\">devamını oku</a>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_2_4_4_LINK_TEXT",
|
||||||
|
"htmlSnippet": "<a href=\"https://google.com\"></a>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_3_1_1_LANG",
|
||||||
|
"htmlSnippet": "<html><head>\n <title></title>\n</head>\n<body>\n <h1 id=\"main-content\">Welcome to a broken page</h1>\n \n <!-- Missing alt attribute -->\n <img src=\"logo.png\">\n \n <!-- Empty link -->\n <a href=\"https://google.com\"></a>\n \n <!-- Empty button -->\n <button type=\"submit\"></button>\n \n <!-- Positive tabindex -->\n <a href=\"/keyboard\" tabindex=\"5\">Keyboard test</a>\n\n <!-- Duplicate ID -->\n <div id=\"main-content\">This is a duplicate main-content ID div!</div>\n\n <!-- Low Contrast -->\n <p style=\"color: #888888; background-color: #999999;\">This text has extremely low contrast ratio!</p>\n\n <!-- Invalid ARIA role and missing controls target -->\n <div role=\"cool-widget\" aria-controls=\"non-existent-popup\">WAI-ARIA elements</div>\n\n <!-- Missing Iframe Title -->\n <iframe src=\"https://www.youtube.com/embed/aqz-KE-bpKQ\" width=\"560\" height=\"315\"></iframe>\n\n <!-- New WCAG Rule Violations for testing -->\n \n <!-- LinkTextGeneric: Generic text without context -->\n <a href=\"/read-more\">Click here</a>\n <a href=\"/devam-oku\">devamını oku</a>\n \n <!-- PlaceholderAsLabel: Input relying only on placeholder -->\n <input type=\"text\" placeholder=\"Search website...\">\n\n <!-- ImageAltRedundant: Redundant words in alt text -->\n <img src=\"logo2.png\" alt=\"logo of our company\">\n <img src=\"profile.jpg\" alt=\"profile photo of john doe\">\n\n <!-- AriaHiddenFocusable: Focusable element hidden with aria-hidden=\"true\" -->\n <div aria-hidden=\"true\">\n <button type=\"button\">Hidden click</button>\n </div>\n <a href=\"#\" aria-hidden=\"true\">Hidden link</a>\n\n <!-- Empty heading violation -->\n <h2></h2>\n\n <!-- Video missing track violation -->\n <video src=\"https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4\" width=\"320\" height=\"240\" controls=\"\"></video>\n\n <!-- Empty label violation -->\n <label for=\"search-input\"></label>\n\n <!-- AriaFocusable violation -->\n <div role=\"button\">Clickable div button without tabindex</div>\n\n <p>This page has multiple accessibility issues.</p>\n</body>\n\n</html>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_3_3_2_PLACEHOLDER_LABEL",
|
||||||
|
"htmlSnippet": "<input type=\"text\" placeholder=\"Search website...\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_4_1_2_BUTTON",
|
||||||
|
"htmlSnippet": "<button type=\"submit\"></button>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/broken.html",
|
||||||
|
"ruleId": "WCAG_4_1_2_IFRAME_TITLE",
|
||||||
|
"htmlSnippet": "<iframe src=\"https://www.youtube.com/embed/aqz-KE-bpKQ\" width=\"560\" height=\"315\"></iframe>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/dynamic_preview.html",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT",
|
||||||
|
"htmlSnippet": "<img src=\"images/gadget.jpg\" width=\"100\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/dynamic_preview.html",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT",
|
||||||
|
"htmlSnippet": "<img src=\"images/widget.png\" width=\"100\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/dynamic_preview.html",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT",
|
||||||
|
"htmlSnippet": "<img src=\"images/thing.jpg\" width=\"100\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/dynamic_preview.html",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT",
|
||||||
|
"htmlSnippet": "<img src=\"https://via.placeholder.com/150\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/dynamic_preview.html",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT",
|
||||||
|
"htmlSnippet": "<img src=\"https://via.placeholder.com/150\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views-fixed/contact.php",
|
||||||
|
"ruleId": "WCAG_3_1_1_LANG",
|
||||||
|
"htmlSnippet": "<html><h2>Contact Us</h2>\n<p>Get in touch with us.</p>\n\n<form action=\"\" method=\"post\">\n <div style=\"margin-bottom: 1rem;\">\n <!-- FIXED: Wrapped in label -->\n <label>\n Name:\n <input type=\"text\" name=\"fullname\" placeholder=\"John Doe\" style=\"padding: 8px; width: 100%;\">\n </label>\n </div>\n\n <div style=\"margin-bottom: 1rem;\">\n <!-- FIXED: Added for/id association -->\n <label for=\"email\">Email Address</label>\n <br>\n <input type=\"email\" id=\"email\" name=\"email\" style=\"padding: 8px; width: 100%;\">\n </div>\n\n <div style=\"margin-bottom: 1rem;\">\n <label for=\"message\">Message</label>\n <br>\n <textarea id=\"message\" name=\"message\" rows=\"5\" style=\"width: 100%;\"></textarea>\n </div>\n\n <!-- FIXED: Added inner text or aria-label -->\n <a href=\"#\" class=\"btn\" aria-label=\"Send via WhatsApp\">\n <i class=\"fa fa-send\"></i> Send\n </a>\n\n <button type=\"submit\" class=\"btn\">Send Message</button>\n</form></html>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views-fixed/home.php",
|
||||||
|
"ruleId": "WCAG_1_3_1_EMPTY_HEADING",
|
||||||
|
"htmlSnippet": "<h3>\n <?php echo $product['name']; >\n </h3>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views-fixed/home.php",
|
||||||
|
"ruleId": "WCAG_3_1_1_LANG",
|
||||||
|
"htmlSnippet": "<html><h2>Latest Products</h2>\n<p>Welcome to our accessible product catalog.</p>\n\n<?php $products = [\n ['id' => 1, 'name' => 'Super Gadget', 'image' => 'gadget.jpg', 'price' => '$99'],\n ['id' => 2, 'name' => 'Mega Widget', 'image' => 'widget.png', 'price' => '$49'],\n ['id' => 3, 'name' => 'Ultra Thing', 'image' => 'thing.jpg', 'price' => '$199'],\n];\n>\n\n<div class=\"products\">\n <?php foreach ($products as $product): >\n <div class=\"card\">\n <!-- FIXED: Added alt attribute describing the product -->\n <img src=\"images/<?php%20echo%20$product['image'];%20?>\" width=\"100\" alt=\"<?php echo htmlspecialchars($product['name']); ?>\">\n <h3>\n <?php echo $product['name']; >\n </h3>\n <p>\n <?php echo $product['price']; >\n </p>\n <button class=\"btn\">Buy Now</button>\n </div>\n <?php endforeach; >\n</div>\n\n<hr>\n\n<h3>Sponsors</h3>\n<div>\n <!-- FIXED: Added empty alt=\"\" for decorative images -->\n <img src=\"https://via.placeholder.com/150\" alt=\"\">\n <img src=\"https://via.placeholder.com/150\" alt=\"\">\n</div></html>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/contact.php",
|
||||||
|
"ruleId": "WCAG_1_3_1_LABEL",
|
||||||
|
"htmlSnippet": "<input type=\"text\" name=\"fullname\" placeholder=\"John Doe\" style=\"padding: 8px; width: 100%;\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/contact.php",
|
||||||
|
"ruleId": "WCAG_1_3_1_LABEL",
|
||||||
|
"htmlSnippet": "<input type=\"email\" name=\"email\" style=\"padding: 8px; width: 100%;\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/contact.php",
|
||||||
|
"ruleId": "WCAG_2_4_4_LINK_TEXT",
|
||||||
|
"htmlSnippet": "<a href=\"#\" class=\"btn\">\n <i class=\"fa fa-send\"></i> <!-- Empty link text error (if we had that rule) -->\n </a>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/contact.php",
|
||||||
|
"ruleId": "WCAG_3_1_1_LANG",
|
||||||
|
"htmlSnippet": "<html><h2>Contact Us</h2>\n<p>Get in touch with us.</p>\n\n<form action=\"\" method=\"post\">\n <div style=\"margin-bottom: 1rem;\">\n <!-- ERROR: No label for input -->\n <div>Name:</div>\n <input type=\"text\" name=\"fullname\" placeholder=\"John Doe\" style=\"padding: 8px; width: 100%;\">\n </div>\n\n <div style=\"margin-bottom: 1rem;\">\n <!-- ERROR: Label exists but not associated with For/ID -->\n <label>Email Address</label>\n <br>\n <input type=\"email\" name=\"email\" style=\"padding: 8px; width: 100%;\">\n </div>\n\n <div style=\"margin-bottom: 1rem;\">\n <label for=\"message\">Message</label>\n <br>\n <textarea id=\"message\" name=\"message\" rows=\"5\" style=\"width: 100%;\"></textarea>\n </div>\n\n <!-- ERROR: Submit button without clear text if it was an input type=image, but button is usually fine. \n Let's add a problematic icon link -->\n <a href=\"#\" class=\"btn\">\n <i class=\"fa fa-send\"></i> <!-- Empty link text error (if we had that rule) -->\n </a>\n\n <button type=\"submit\" class=\"btn\">Send Message</button>\n</form></html>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/contact.php",
|
||||||
|
"ruleId": "WCAG_3_3_2_PLACEHOLDER_LABEL",
|
||||||
|
"htmlSnippet": "<input type=\"text\" name=\"fullname\" placeholder=\"John Doe\" style=\"padding: 8px; width: 100%;\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/home.php",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT",
|
||||||
|
"htmlSnippet": "<img src=\"images/<?php%20echo%20$product['image'];%20?>\" width=\"100\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/home.php",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT",
|
||||||
|
"htmlSnippet": "<img src=\"https://via.placeholder.com/150\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/home.php",
|
||||||
|
"ruleId": "WCAG_1_1_1_ALT",
|
||||||
|
"htmlSnippet": "<img src=\"https://via.placeholder.com/150\">"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/home.php",
|
||||||
|
"ruleId": "WCAG_1_3_1_EMPTY_HEADING",
|
||||||
|
"htmlSnippet": "<h3>\n <?php echo $product['name']; >\n </h3>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/home.php",
|
||||||
|
"ruleId": "WCAG_3_1_1_LANG",
|
||||||
|
"htmlSnippet": "<html><h2>Latest Products</h2>\n<p>Welcome to our dynamic product catalog. (Intentionally filled with errors)</p>\n\n<?php $products = [\n ['id' => 1, 'name' => 'Super Gadget', 'image' => 'gadget.jpg', 'price' => '$99'],\n ['id' => 2, 'name' => 'Mega Widget', 'image' => 'widget.png', 'price' => '$49'],\n ['id' => 3, 'name' => 'Ultra Thing', 'image' => 'thing.jpg', 'price' => '$199'],\n];\n>\n\n<div class=\"products\">\n <?php foreach ($products as $product): >\n <div class=\"card\">\n <!-- ERROR: Dynamic image without alt text -->\n <img src=\"images/<?php%20echo%20$product['image'];%20?>\" width=\"100\">\n <h3>\n <?php echo $product['name']; >\n </h3>\n <p>\n <?php echo $product['price']; >\n </p>\n <button class=\"btn\">Buy Now</button>\n <!-- Error: Button might need specific accessible name if icon-only, but text is okay here. -->\n </div>\n <?php endforeach; >\n</div>\n\n<hr>\n\n<h3>Sponsors</h3>\n<div>\n <!-- ERROR: Decorative image causing noise, missing alt=\"\" -->\n <img src=\"https://via.placeholder.com/150\">\n <img src=\"https://via.placeholder.com/150\">\n</div></html>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/layout.php",
|
||||||
|
"ruleId": "WCAG_2_4_4_LINK_TEXT",
|
||||||
|
"htmlSnippet": "<a href=\"#\" class=\"btn\"></a>"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "demo/views/layout.php",
|
||||||
|
"ruleId": "WCAG_3_1_1_LANG",
|
||||||
|
"htmlSnippet": "<html><!-- Missing lang attribute error --><head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>YakNet Dynamic Demo</title>\n <style>\n body {\n font-family: sans-serif;\n margin: 0;\n padding: 0;\n line-height: 1.6;\n }\n\n header {\n background: #333;\n color: #fff;\n padding: 1rem;\n }\n\n nav a {\n color: #fff;\n margin-right: 1rem;\n text-decoration: none;\n }\n\n .container {\n padding: 2rem;\n max-width: 800px;\n margin: 0 auto;\n }\n\n .card {\n border: 1px solid #ddd;\n padding: 1rem;\n margin-bottom: 1rem;\n border-radius: 4px;\n }\n\n .btn {\n background: #007bff;\n color: white;\n padding: 0.5rem 1rem;\n border: none;\n cursor: pointer;\n }\n </style>\n</head>\n\n<body>\n <header>\n <div class=\"container\" style=\"padding: 0;\">\n <h1>My Dynamic Site</h1>\n <nav>\n <a href=\"?page=home\">Home</a>\n <a href=\"?page=contact\">Contact</a>\n <a href=\"?page=about\">About</a>\n <a href=\"#\" class=\"btn\"></a> <!-- Error: Empty Link -->\n </nav>\n </div>\n </header>\n\n <main class=\"container\">\n <?php include $viewPath; >\n </main>\n\n <footer style=\"text-align: center; padding: 2rem; background: #f4f4f4; margin-top: 2rem;\">\n ©\n <?php echo date('Y'); > YakNet Demo\n </footer>\n</body>\n\n</html>"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# YakNet Accessibility Console Configuration
|
||||||
|
# For detailed configuration, see: https://forum.yak.net.tr
|
||||||
|
|
||||||
|
# Paths to scan (can be directories or specific files)
|
||||||
|
paths:
|
||||||
|
- .
|
||||||
|
|
||||||
|
# Exclude directories or files
|
||||||
|
exclude_paths:
|
||||||
|
- vendor
|
||||||
|
- node_modules
|
||||||
|
- tests
|
||||||
|
- storage
|
||||||
|
- .git
|
||||||
|
|
||||||
|
# Accessibility scanning level (1-9, default 4)
|
||||||
|
level: 4
|
||||||
|
|
||||||
|
# Output format (console, json, html, github)
|
||||||
|
format: console
|
||||||
|
|
||||||
|
# Path to the baseline file for ignoring existing violations
|
||||||
|
baseline: a11y-baseline.json
|
||||||
|
|
||||||
|
# Rule adjustments
|
||||||
|
rules:
|
||||||
|
# Rules to exclude from analysis
|
||||||
|
exclude:
|
||||||
|
# - WCAG_1_3_1_FIELDSET
|
||||||
|
# Additional custom rules to run
|
||||||
|
include:
|
||||||
|
# - App\Rules\MyCustomRule
|
||||||
@@ -1,16 +1,41 @@
|
|||||||
#!/usr/bin/env php
|
#!/usr/bin/env php
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
require __DIR__ . '/../vendor/autoload.php';
|
if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
|
||||||
|
require __DIR__ . '/../vendor/autoload.php';
|
||||||
|
} elseif (file_exists(__DIR__ . '/../../../autoload.php')) {
|
||||||
|
require __DIR__ . '/../../../autoload.php';
|
||||||
|
} else {
|
||||||
|
echo "Autoload file not found.\n";
|
||||||
|
exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
use Symfony\Component\Console\Application;
|
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\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', '2.0.0');
|
$container = ContainerFactory::create();
|
||||||
|
$application = new Application('YakNet Accessibility Console', '4.0.0');
|
||||||
|
|
||||||
// Add commands
|
// Add commands resolved via DI Container
|
||||||
$application->add(new ScanCommand());
|
$application->addCommand($container->get(ScanCommand::class));
|
||||||
$application->add(new FixCommand());
|
$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();
|
$application->run();
|
||||||
+30
-8
@@ -1,24 +1,31 @@
|
|||||||
{
|
{
|
||||||
"name": "yaknet/accessibility-console",
|
"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": [
|
"keywords": [
|
||||||
"accessibility",
|
"accessibility",
|
||||||
"wcag",
|
"wcag",
|
||||||
|
"wcag22",
|
||||||
|
"wai-aria",
|
||||||
|
"vpat",
|
||||||
|
"en301549",
|
||||||
|
"section508",
|
||||||
"a11y",
|
"a11y",
|
||||||
"scanner",
|
"scanner",
|
||||||
|
"linter",
|
||||||
|
"static-analysis",
|
||||||
"ai",
|
"ai",
|
||||||
"gemini",
|
|
||||||
"self-healing",
|
"self-healing",
|
||||||
"yaknet"
|
"yaknet"
|
||||||
],
|
],
|
||||||
"homepage": "https://forum.yak.net.tr",
|
"homepage": "https://forum.yak.net.tr",
|
||||||
|
"version": "4.0.0",
|
||||||
"type": "library",
|
"type": "library",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
"name": "YakNet Bilişim",
|
"name": "YakNet",
|
||||||
"email": "[email protected]",
|
"email": "[email protected]",
|
||||||
"role": "Developer"
|
"role": "Organization"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"require": {
|
"require": {
|
||||||
@@ -26,17 +33,32 @@
|
|||||||
"ext-dom": "*",
|
"ext-dom": "*",
|
||||||
"ext-libxml": "*",
|
"ext-libxml": "*",
|
||||||
"ext-mbstring": "*",
|
"ext-mbstring": "*",
|
||||||
"symfony/console": "^6.4|^7.0",
|
"symfony/console": "^6.4 || ^7.0 || ^8.0",
|
||||||
"symfony/yaml": "^6.4|^7.0",
|
"symfony/yaml": "^6.4 || ^7.0 || ^8.0",
|
||||||
"monolog/monolog": "^3.0",
|
"monolog/monolog": "^3.0",
|
||||||
"vlucas/phpdotenv": "^5.6",
|
"vlucas/phpdotenv": "^5.6",
|
||||||
"google-gemini-php/client": "^1.0"
|
"google-gemini-php/client": "^1.0 || ^2.0",
|
||||||
|
"guzzlehttp/guzzle": "^7.8",
|
||||||
|
"masterminds/html5": "^2.8",
|
||||||
|
"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": {
|
"require-dev": {
|
||||||
"phpunit/phpunit": "^10.5",
|
"phpunit/phpunit": "^10.5",
|
||||||
"phpstan/phpstan": "^1.10"
|
"phpstan/phpstan": "^2.2"
|
||||||
},
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
|
"files": [
|
||||||
|
"src/accessibility-console.php"
|
||||||
|
],
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
"YakNet\\AccessibilityConsole\\": "src/"
|
"YakNet\\AccessibilityConsole\\": "src/"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+111
-10
@@ -1,20 +1,121 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html lang="tr"><!-- FIXED: Added lang attribute (WCAG 3.1.1) -->
|
||||||
<head>
|
<head>
|
||||||
<title>Broken Page</title>
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Erişilebilir Demo Sayfa</title><!-- FIXED: Non-empty page title (WCAG 2.4.2) -->
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
font-family: sans-serif;
|
||||||
|
margin: 0;
|
||||||
|
padding: 2rem;
|
||||||
|
background: #ffffff;
|
||||||
|
color: #1a1a1a; /* FIXED: High contrast text (WCAG 1.4.3) */
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
/* FIXED: Sufficient contrast (WCAG 1.4.3) - was #888 on #999, now dark on white */
|
||||||
|
.low-contrast-example {
|
||||||
|
color: #595959; /* 7:1 contrast on white */
|
||||||
|
background-color: #ffffff;
|
||||||
|
padding: 0.5rem;
|
||||||
|
}
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.25rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
input {
|
||||||
|
padding: 0.4rem;
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
border-radius: 4px;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 300px;
|
||||||
|
}
|
||||||
|
iframe {
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
video {
|
||||||
|
display: block;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
[role="button"] {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h1>Welcome to a broken page</h1>
|
<h1 id="main-content">Erişilebilir Demo Sayfa</h1>
|
||||||
|
<!-- FIXED: Removed duplicate id="main-content" (WCAG 4.1.1) -->
|
||||||
|
|
||||||
<!-- Missing alt attribute -->
|
<!-- FIXED: Added alt attribute (WCAG 1.1.1) -->
|
||||||
<img src="logo.png">
|
<img src="logo.png" alt="YakNet Şirket">
|
||||||
|
|
||||||
<!-- Empty link -->
|
<!-- FIXED: Added descriptive link text (WCAG 2.4.4) -->
|
||||||
<a href="https://google.com"></a>
|
<a href="https://google.com">Google Ana Sayfasına Git</a>
|
||||||
|
|
||||||
<!-- Empty button -->
|
<!-- FIXED: Added discernible button text (WCAG 4.1.2) -->
|
||||||
<button type="submit"></button>
|
<button type="submit">Formu Gönder</button>
|
||||||
|
|
||||||
<p>This page has multiple accessibility issues.</p>
|
<!-- FIXED: Removed positive tabindex (WCAG 2.4.3) — use natural DOM order -->
|
||||||
|
<a href="/keyboard">Klavye Testi</a>
|
||||||
|
|
||||||
|
<!-- FIXED: Removed duplicate id="main-content" — unique wrapper instead -->
|
||||||
|
<div id="duplicate-content-wrapper">Bu bölümün içeriği buradadır.</div>
|
||||||
|
|
||||||
|
<!-- FIXED: High contrast text (WCAG 1.4.3) -->
|
||||||
|
<p class="low-contrast-example">Bu metnin kontrast oranı WCAG AA gereksinimlerini karşılamaktadır.</p>
|
||||||
|
|
||||||
|
<!-- FIXED: Valid WAI-ARIA role (WCAG 4.1.2) and removed reference to non-existent element -->
|
||||||
|
<div role="region" aria-label="WAI-ARIA Örnek Bölüm">WAI-ARIA bölüm örneği</div>
|
||||||
|
|
||||||
|
<!-- FIXED: Added descriptive title to iframe (WCAG 4.1.2) -->
|
||||||
|
<iframe
|
||||||
|
src="https://www.youtube.com/embed/aqz-KE-bpKQ"
|
||||||
|
width="560"
|
||||||
|
height="315"
|
||||||
|
title="YouTube Video: Örnek Video İçeriği"
|
||||||
|
></iframe>
|
||||||
|
|
||||||
|
<!-- FIXED: Descriptive link text instead of generic "click here" / "devamını oku" (WCAG 2.4.4) -->
|
||||||
|
<a href="/read-more">Makaleyi Devamı: WCAG Erişilebilirlik Kılavuzu</a>
|
||||||
|
<a href="/devam-oku">Şiir Serisinin Devamını Oku: "Bahar Rüzgarı"</a>
|
||||||
|
|
||||||
|
<!-- FIXED: Added associated <label> element (WCAG 1.3.1 & 3.3.2) -->
|
||||||
|
<div>
|
||||||
|
<label for="search-input">Web sitesinde ara</label>
|
||||||
|
<input type="text" id="search-input" placeholder="Arama teriminizi girin...">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- FIXED: Removed redundant words "logo" and "photo" from alt texts (WCAG 1.1.1) -->
|
||||||
|
<img src="logo2.png" alt="Şirketimizin simgesi">
|
||||||
|
<img src="profile.jpg" alt="John Doe vesikalık">
|
||||||
|
|
||||||
|
<!-- FIXED: Removed aria-hidden="true" from focusable elements (WCAG 4.1.2) -->
|
||||||
|
<div>
|
||||||
|
<button type="button">Gizli Olmayan Tıklanabilir Düğme</button>
|
||||||
|
</div>
|
||||||
|
<a href="#">Normal Bağlantı</a>
|
||||||
|
|
||||||
|
<!-- FIXED: Added non-empty heading text (WCAG 2.4.6) -->
|
||||||
|
<h2>Alt Bölüm Başlığı</h2>
|
||||||
|
|
||||||
|
<!-- FIXED: Added <track> element for video captions (WCAG 1.2.2) -->
|
||||||
|
<video
|
||||||
|
src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
|
||||||
|
width="320"
|
||||||
|
height="240"
|
||||||
|
controls
|
||||||
|
>
|
||||||
|
<track kind="captions" src="captions.vtt" srclang="tr" label="Türkçe Altyazı" default>
|
||||||
|
</video>
|
||||||
|
|
||||||
|
<!-- FIXED: Added non-empty label text (WCAG 1.3.1) -->
|
||||||
|
<label for="name-input">Ad Soyad</label>
|
||||||
|
<input type="text" id="name-input" name="name">
|
||||||
|
|
||||||
|
<!-- FIXED: Added tabindex="0" to make role="button" keyboard focusable (WCAG 2.1.1) -->
|
||||||
|
<div role="button" tabindex="0">Tıklanabilir Div Düğme (Erişilebilir)</div>
|
||||||
|
|
||||||
|
<p>Bu sayfa WCAG 2.1 erişilebilirlik standartlarına uygun olarak düzenlenmiştir.</p>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+10
-19
@@ -1,19 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
// 1. Setup Autoloading (Mocking Composer)
|
// 1. Setup Autoloading
|
||||||
require_once __DIR__ . '/../src/Scanner.php';
|
require_once __DIR__ . '/../vendor/autoload.php';
|
||||||
require_once __DIR__ . '/../src/Violation.php';
|
|
||||||
require_once __DIR__ . '/../src/SourceLocator.php';
|
|
||||||
require_once __DIR__ . '/../src/Reporter/HtmlReporter.php';
|
|
||||||
require_once __DIR__ . '/../src/Rule/RuleInterface.php';
|
|
||||||
require_once __DIR__ . '/../src/Rules/ImgAltText.php';
|
|
||||||
require_once __DIR__ . '/../src/Rules/FormLabel.php';
|
|
||||||
require_once __DIR__ . '/../src/Rules/HtmlHasLang.php';
|
|
||||||
require_once __DIR__ . '/../src/Rules/EmptyLink.php';
|
|
||||||
|
|
||||||
use YakNet\AccessibilityConsole\Scanner;
|
use YakNet\AccessibilityConsole\Core\Scanner;
|
||||||
use YakNet\AccessibilityConsole\SourceLocator;
|
use YakNet\AccessibilityConsole\Source\SourceLocator;
|
||||||
use YakNet\AccessibilityConsole\Reporter\HtmlReporter;
|
use YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter;
|
||||||
use YakNet\AccessibilityConsole\Rules\ImgAltText;
|
use YakNet\AccessibilityConsole\Rules\ImgAltText;
|
||||||
use YakNet\AccessibilityConsole\Rules\FormLabel;
|
use YakNet\AccessibilityConsole\Rules\FormLabel;
|
||||||
|
|
||||||
@@ -48,19 +40,18 @@ $violations = $scanner->scan($html);
|
|||||||
|
|
||||||
if (!empty($violations)) {
|
if (!empty($violations)) {
|
||||||
// Locate Sources
|
// Locate Sources
|
||||||
// We point it to the 'views' directory so it knows where to look for the error source
|
|
||||||
$locator = new SourceLocator(__DIR__ . '/views');
|
$locator = new SourceLocator(__DIR__ . '/views');
|
||||||
|
|
||||||
foreach ($violations as $violation) {
|
foreach ($violations as $violation) {
|
||||||
$location = $locator->locate($violation->snippet);
|
$location = $locator->locate($violation->htmlSnippet);
|
||||||
if ($location) {
|
if ($location) {
|
||||||
$violation->setSourceLocation($location['file'], $location['line']);
|
$violation->location = $location;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render Report
|
// Render Report (Format as results mapped by page URL)
|
||||||
$reporter = new HtmlReporter();
|
$reporter = new HtmlDashboardReporter();
|
||||||
$reportHtml = $reporter->render($violations);
|
$reportHtml = $reporter->render(['http://localhost:8080/index.php' => $violations], 'demo/index.php');
|
||||||
|
|
||||||
// Inject into body
|
// Inject into body
|
||||||
$html = str_replace('</body>', $reportHtml . '</body>', $html);
|
$html = str_replace('</body>', $reportHtml . '</body>', $html);
|
||||||
|
|||||||
@@ -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,25 @@
|
|||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Test Page</title>
|
||||||
|
<meta http-equiv="refresh" content="30">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<img src="avatar.png" alt="Avatar">
|
||||||
|
<button>Submit</button>
|
||||||
|
<a href="#">Click here for nothing</a>
|
||||||
|
<a href="javascript:void(0)">Do something</a>
|
||||||
|
<label for="nonexistent-id">Broken Label</label>
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<th>Header 1</th>
|
||||||
|
<th>Header 2</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td scope="row">Data 1</td>
|
||||||
|
<td>Data 2</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</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).
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
+26
-16
@@ -11,15 +11,23 @@ class GeminiFixer
|
|||||||
|
|
||||||
public function __construct(private readonly ?string $apiKey)
|
public function __construct(private readonly ?string $apiKey)
|
||||||
{
|
{
|
||||||
if ($this->apiKey && class_exists(Gemini::class)) {
|
if ($this->apiKey) {
|
||||||
$this->client = Gemini::client($this->apiKey);
|
try {
|
||||||
|
$this->client = \Gemini::client($this->apiKey);
|
||||||
|
} catch (\Throwable) {
|
||||||
|
$this->client = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function suggestFix(Violation $violation): ?string
|
public function suggestFix(Violation $violation): ?string
|
||||||
{
|
{
|
||||||
|
if (!$this->apiKey) {
|
||||||
|
return "Hata: GEMINI_API_KEY bulunamadı.";
|
||||||
|
}
|
||||||
|
|
||||||
if (!$this->client) {
|
if (!$this->client) {
|
||||||
return null;
|
return "Hata: Gemini istemcisi başlatılamadı. Kütüphane eksik olabilir.";
|
||||||
}
|
}
|
||||||
|
|
||||||
$prompt = <<<PROMPT
|
$prompt = <<<PROMPT
|
||||||
@@ -30,22 +38,24 @@ Error: {$violation->message}
|
|||||||
Severity: {$violation->severity->value}
|
Severity: {$violation->severity->value}
|
||||||
Standard: {$violation->standard->value}
|
Standard: {$violation->standard->value}
|
||||||
|
|
||||||
Please provide ONLY the fixed version of the HTML snippet.
|
Please provide a short explanation of the fix (in Turkish) and the fixed version of the HTML snippet.
|
||||||
Do not explain, do not add markdown code blocks, just return the corrected HTML.
|
Use the following EXACT format:
|
||||||
If the error is about missing 'alt' text, add a meaningful alt text based on context.
|
EXPLANATION: [A short explanation of what you fixed and why]
|
||||||
If it's about ARIA roles, add the correct ones.
|
FIX: [Only the corrected HTML snippet]
|
||||||
PROMPT;
|
PROMPT;
|
||||||
|
|
||||||
try {
|
$models = ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-1.5-pro', 'gemini-1.5-flash'];
|
||||||
$result = $this->client->generativeModel('gemini-2.5-flash')->generateContent($prompt);
|
$lastError = null;
|
||||||
$suggestion = trim($result->text());
|
|
||||||
|
|
||||||
// Clean up if AI included markdown blocks anyway
|
foreach ($models as $model) {
|
||||||
$suggestion = preg_replace('/^```html\s*|\s*```$/i', '', $suggestion);
|
try {
|
||||||
|
$result = $this->client->generativeModel($model)->generateContent($prompt);
|
||||||
return $suggestion;
|
return trim($result->text());
|
||||||
} catch (\Throwable $e) {
|
} catch (\Throwable $e) {
|
||||||
return "AI Düzeltme Hatası: " . $e->getMessage();
|
$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,10 +8,11 @@ use Symfony\Component\Console\Input\InputInterface;
|
|||||||
use Symfony\Component\Console\Input\InputOption;
|
use Symfony\Component\Console\Input\InputOption;
|
||||||
use Symfony\Component\Console\Output\OutputInterface;
|
use Symfony\Component\Console\Output\OutputInterface;
|
||||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
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\Config;
|
||||||
use YakNet\AccessibilityConsole\Core\Scanner;
|
use YakNet\AccessibilityConsole\Core\Scanner;
|
||||||
use YakNet\AccessibilityConsole\Rules\StandardRuleSet;
|
use YakNet\AccessibilityConsole\Rules\RuleLevels;
|
||||||
use YakNet\AccessibilityConsole\Source\SourceLocator;
|
use YakNet\AccessibilityConsole\Source\SourceLocator;
|
||||||
|
|
||||||
class FixCommand extends Command
|
class FixCommand extends Command
|
||||||
@@ -21,38 +22,211 @@ class FixCommand extends Command
|
|||||||
$this
|
$this
|
||||||
->setName('fix')
|
->setName('fix')
|
||||||
->setDescription('Automatically fix accessibility violations using AI')
|
->setDescription('Automatically fix accessibility violations using AI')
|
||||||
->addArgument('target', InputArgument::REQUIRED, 'The URL or file path to scan')
|
->addArgument('target', InputArgument::OPTIONAL, 'The URL, file, or directory path to scan and fix')
|
||||||
->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping')
|
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to the configuration file (default: a11y.yaml)')
|
||||||
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Show what would be fixed without modifying files');
|
->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)');
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||||
{
|
{
|
||||||
$io = new SymfonyStyle($input, $output);
|
$io = new SymfonyStyle($input, $output);
|
||||||
$target = $input->getArgument('target');
|
|
||||||
$projectPath = $input->getOption('project-path') ?? getcwd();
|
|
||||||
$dryRun = $input->getOption('dry-run');
|
|
||||||
|
|
||||||
$config = new Config();
|
// 1. Resolve configuration
|
||||||
|
$configPathOption = $input->getOption('config');
|
||||||
|
$configPath = is_string($configPathOption) ? $configPathOption : getcwd() . '/a11y.yaml';
|
||||||
|
$config = Config::fromYaml($configPath);
|
||||||
|
|
||||||
|
$offline = (bool)$input->getOption('offline');
|
||||||
$apiKey = $config->getGeminiApiKey();
|
$apiKey = $config->getGeminiApiKey();
|
||||||
|
if (!$offline && !$apiKey) {
|
||||||
if (!$apiKey) {
|
$io->note("GEMINI_API_KEY not found in .env or environment variables. Running in offline rule-based healing mode (--offline).");
|
||||||
$io->error("GEMINI_API_KEY not found in .env or environment variables. AI fixing requires an API key.");
|
$offline = true;
|
||||||
return Command::FAILURE;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$io->title("AI Self-Healing Mode - Fixing: $target");
|
$levelOption = $input->getOption('level');
|
||||||
|
$level = is_numeric($levelOption) ? (int)$levelOption : $config->getLevel();
|
||||||
|
|
||||||
// 1. Fetch HTML
|
$target = $input->getArgument('target');
|
||||||
$html = @file_get_contents($target);
|
$isUrl = is_string($target) && (str_starts_with($target, 'http://') || str_starts_with($target, 'https://'));
|
||||||
if (!$html) {
|
|
||||||
$io->error("Could not read target: $target");
|
// If target is a URL, run the legacy URL fixing logic
|
||||||
return Command::FAILURE;
|
if ($isUrl) {
|
||||||
|
return $this->executeUrlFix($target, $level, $apiKey, $input, $output, $io, $offline);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Scan
|
// --- LOCAL FILE / DIRECTORY SELF-HEALING ENGINE ---
|
||||||
|
$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');
|
||||||
|
|
||||||
|
// Resolve paths to scan
|
||||||
|
$paths = $config->getPaths();
|
||||||
|
if (is_string($target) && $target !== '') {
|
||||||
|
$paths = [$target];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup Analyser
|
||||||
$scanner = new Scanner();
|
$scanner = new Scanner();
|
||||||
foreach (StandardRuleSet::all() as $rule) {
|
$rules = RuleLevels::getRulesForLevel($level);
|
||||||
|
foreach ($rules as $rule) {
|
||||||
|
$scanner->addRule($rule);
|
||||||
|
}
|
||||||
|
|
||||||
|
// We run without baseline filtering so we can fix ALL errors in the project,
|
||||||
|
// or we can optionally load baseline. Fixing everything is better for a general "fix" run.
|
||||||
|
$analyser = new Analyser($config, $scanner, new \YakNet\AccessibilityConsole\Core\BaselineManager());
|
||||||
|
|
||||||
|
$io->note("Scanning targets for violations...");
|
||||||
|
$result = $analyser->analyse($paths);
|
||||||
|
$violations = $result['violations'];
|
||||||
|
|
||||||
|
if (empty($violations)) {
|
||||||
|
$io->success("Everything looks good! No violations to fix.");
|
||||||
|
return Command::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
$io->note(sprintf("Found %d violations. Starting %s analysis and healing...", count($violations), $offline ? 'offline rule-based' : 'AI'));
|
||||||
|
|
||||||
|
$fixer = !$offline ? new AiFixerManager($apiKey) : null;
|
||||||
|
$diffGenerator = new \YakNet\AccessibilityConsole\Core\Diff\VisualDiffGenerator();
|
||||||
|
$fixedCount = 0;
|
||||||
|
|
||||||
|
// Group violations by file path
|
||||||
|
$groupedViolations = [];
|
||||||
|
foreach ($violations as $v) {
|
||||||
|
$file = $v->location['file'] ?? '';
|
||||||
|
if ($file !== '') {
|
||||||
|
$groupedViolations[$file][] = $v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($groupedViolations as $file => $fileViolations) {
|
||||||
|
$io->section("Fixing file: $file");
|
||||||
|
|
||||||
|
// Sort violations by line number DESCENDING (bottom to top)
|
||||||
|
// This prevents edits at the bottom of the file from invalidating line numbers above them!
|
||||||
|
usort($fileViolations, function ($a, $b) {
|
||||||
|
return ($b->location['line'] ?? 0) <=> ($a->location['line'] ?? 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
$absoluteFile = getcwd() . '/' . $file;
|
||||||
|
if (!file_exists($absoluteFile) || !is_writable($absoluteFile)) {
|
||||||
|
$io->warning("File not found or not writable: $file. Skipping.");
|
||||||
|
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</>... ");
|
||||||
|
|
||||||
|
// 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 (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 (!is_string($suggestion)) {
|
||||||
|
$io->writeln("<fg=red>Skipped (AI could not generate a clean fix)</>");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
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.</>");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply Fix
|
||||||
|
if ($this->applyFix($absoluteFile, $violation->htmlSnippet, $suggestion)) {
|
||||||
|
$io->writeln(" <fg=bright-green>✔ Applied to line $line</>");
|
||||||
|
$fixedCount++;
|
||||||
|
} else {
|
||||||
|
$io->writeln(" <fg=red>✘ Failed to apply fix to file.</>");
|
||||||
|
}
|
||||||
|
$io->writeln("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($fixedCount > 0) {
|
||||||
|
$io->success("Self-healing complete! $fixedCount violations were automatically fixed.");
|
||||||
|
} else {
|
||||||
|
$io->warning("No files were modified.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Command::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Legacy URL scan and fix logic
|
||||||
|
*/
|
||||||
|
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();
|
||||||
|
if ($projectPath === false) {
|
||||||
|
$projectPath = '.';
|
||||||
|
}
|
||||||
|
$dryRun = (bool)$input->getOption('dry-run');
|
||||||
|
$useJs = (bool)$input->getOption('js');
|
||||||
|
|
||||||
|
$io->title($offline ? "Offline Rule-Based Mode - Fixing URL: $target" : "AI Self-Healing Mode - Fixing URL: $target");
|
||||||
|
|
||||||
|
// Fetch HTML
|
||||||
|
if ($useJs) {
|
||||||
|
try {
|
||||||
|
$chromeRenderer = new \YakNet\AccessibilityConsole\Core\ChromeRenderer();
|
||||||
|
$html = $chromeRenderer->render($target);
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$io->error("Failed JavaScript rendering: " . $e->getMessage());
|
||||||
|
return Command::FAILURE;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$html = @file_get_contents($target);
|
||||||
|
}
|
||||||
|
if ($html === false || $html === '') {
|
||||||
|
$io->error("Could not read target URL: $target");
|
||||||
|
return Command::FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scan
|
||||||
|
$scanner = new Scanner();
|
||||||
|
$rules = RuleLevels::getRulesForLevel($level);
|
||||||
|
foreach ($rules as $rule) {
|
||||||
$scanner->addRule($rule);
|
$scanner->addRule($rule);
|
||||||
}
|
}
|
||||||
$violations = $scanner->scan($html);
|
$violations = $scanner->scan($html);
|
||||||
@@ -62,9 +236,10 @@ class FixCommand extends Command
|
|||||||
return Command::SUCCESS;
|
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);
|
$locator = new SourceLocator($projectPath);
|
||||||
$fixedCount = 0;
|
$fixedCount = 0;
|
||||||
|
|
||||||
@@ -78,16 +253,45 @@ class FixCommand extends Command
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get AI Suggestion
|
$localHealer = new \YakNet\AccessibilityConsole\Core\SelfHealing\LocalHealer();
|
||||||
$suggestion = $fixer->suggestFix($violation);
|
$rawSuggestion = $localHealer->heal($violation);
|
||||||
if (!$suggestion) {
|
$isLocalFix = false;
|
||||||
$io->writeln("<fg=red>Skipped (AI could not generate fix)</>");
|
|
||||||
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$io->writeln("<fg=green>Fix Found!</>");
|
$suggestion = $rawSuggestion;
|
||||||
$io->writeln(" <fg=gray>Original:</> <fg=red>" . htmlspecialchars(trim($violation->htmlSnippet)) . "</>");
|
if (is_string($rawSuggestion) && str_contains($rawSuggestion, 'FIX:')) {
|
||||||
$io->writeln(" <fg=gray>AI Fix: </> <fg=green>" . htmlspecialchars(trim($suggestion)) . "</>");
|
preg_match('/FIX:(.*)/s', $rawSuggestion, $matches);
|
||||||
|
$suggestion = trim($matches[1] ?? $rawSuggestion);
|
||||||
|
$suggestion = preg_replace('/^```html\s*|\s*```$/i', '', $suggestion);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!is_string($suggestion)) {
|
||||||
|
$io->writeln("<fg=red>Skipped (AI could not generate a clean fix)</>");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
if ($dryRun) {
|
||||||
$io->writeln(" <fg=blue>[DRY RUN] File modification skipped.</>");
|
$io->writeln(" <fg=blue>[DRY RUN] File modification skipped.</>");
|
||||||
@@ -107,7 +311,7 @@ class FixCommand extends Command
|
|||||||
if ($fixedCount > 0) {
|
if ($fixedCount > 0) {
|
||||||
$io->success("Self-healing complete! $fixedCount violations were automatically fixed.");
|
$io->success("Self-healing complete! $fixedCount violations were automatically fixed.");
|
||||||
} else {
|
} else {
|
||||||
$io->warning("No files were modified. Check error logs for details.");
|
$io->warning("No files were modified.");
|
||||||
}
|
}
|
||||||
|
|
||||||
return Command::SUCCESS;
|
return Command::SUCCESS;
|
||||||
@@ -122,8 +326,7 @@ class FixCommand extends Command
|
|||||||
if (str_contains($content, $originalSnippet)) {
|
if (str_contains($content, $originalSnippet)) {
|
||||||
$newContent = str_replace($originalSnippet, $fixedSnippet, $content);
|
$newContent = str_replace($originalSnippet, $fixedSnippet, $content);
|
||||||
} else {
|
} else {
|
||||||
// Fallback: Fuzzy replacement (simplified for this demo)
|
// Fallback: Fuzzy replacement
|
||||||
// In a real professional lib, we'd use more advanced regex or DOM patching
|
|
||||||
$newContent = str_replace(trim($originalSnippet), trim($fixedSnippet), $content);
|
$newContent = str_replace(trim($originalSnippet), trim($fixedSnippet), $content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
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
|
||||||
|
{
|
||||||
|
protected function configure(): void
|
||||||
|
{
|
||||||
|
$this
|
||||||
|
->setName('init')
|
||||||
|
->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)) {
|
||||||
|
$io->warning("Configuration file 'a11y.yaml' already exists in the current directory.");
|
||||||
|
return Command::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
$defaultConfig = <<<YAML
|
||||||
|
# YakNet Accessibility Console Configuration
|
||||||
|
# For detailed configuration, see: https://forum.yak.net.tr
|
||||||
|
|
||||||
|
# Paths to scan (can be directories or specific files)
|
||||||
|
paths:
|
||||||
|
- .
|
||||||
|
|
||||||
|
# Exclude directories or files
|
||||||
|
exclude_paths:
|
||||||
|
- vendor
|
||||||
|
- node_modules
|
||||||
|
- tests
|
||||||
|
- storage
|
||||||
|
- .git
|
||||||
|
|
||||||
|
# Accessibility scanning level (1-5, default 4)
|
||||||
|
level: 4
|
||||||
|
|
||||||
|
# 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
|
||||||
|
exclude:
|
||||||
|
# - WCAG_1_3_1_FIELDSET
|
||||||
|
# Additional custom rules to run
|
||||||
|
include:
|
||||||
|
# - App\Rules\MyCustomRule
|
||||||
|
YAML;
|
||||||
|
|
||||||
|
if (file_put_contents($configPath, $defaultConfig) !== false) {
|
||||||
|
$io->success("Created configuration file: a11y.yaml");
|
||||||
|
return Command::SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
$io->error("Failed to create configuration file 'a11y.yaml'.");
|
||||||
|
return Command::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
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\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')
|
||||||
|
->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
|
||||||
|
{
|
||||||
|
$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']);
|
||||||
|
|
||||||
|
$matchedCount = 0;
|
||||||
|
foreach ($rules as $rule) {
|
||||||
|
$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</>",
|
||||||
|
$standard,
|
||||||
|
$severity,
|
||||||
|
$level,
|
||||||
|
$description
|
||||||
|
]);
|
||||||
|
$matchedCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
$table->render();
|
||||||
|
$io->newLine();
|
||||||
|
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,111 +3,796 @@
|
|||||||
namespace YakNet\AccessibilityConsole\Console\Command;
|
namespace YakNet\AccessibilityConsole\Console\Command;
|
||||||
|
|
||||||
use Symfony\Component\Console\Command\Command;
|
use Symfony\Component\Console\Command\Command;
|
||||||
|
use Symfony\Component\Console\Helper\ProgressBar;
|
||||||
use Symfony\Component\Console\Input\InputArgument;
|
use Symfony\Component\Console\Input\InputArgument;
|
||||||
use Symfony\Component\Console\Input\InputInterface;
|
use Symfony\Component\Console\Input\InputInterface;
|
||||||
use Symfony\Component\Console\Input\InputOption;
|
use Symfony\Component\Console\Input\InputOption;
|
||||||
use Symfony\Component\Console\Output\OutputInterface;
|
use Symfony\Component\Console\Output\OutputInterface;
|
||||||
use Symfony\Component\Console\Style\SymfonyStyle;
|
use Symfony\Component\Console\Style\SymfonyStyle;
|
||||||
use YakNet\AccessibilityConsole\AI\GeminiFixer;
|
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\Config;
|
||||||
use YakNet\AccessibilityConsole\Core\Scanner;
|
use YakNet\AccessibilityConsole\Core\Scanner;
|
||||||
use YakNet\AccessibilityConsole\Rules\StandardRuleSet;
|
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;
|
use YakNet\AccessibilityConsole\Source\SourceLocator;
|
||||||
|
|
||||||
class ScanCommand extends Command
|
class ScanCommand extends Command
|
||||||
{
|
{
|
||||||
protected static $defaultName = 'scan';
|
|
||||||
|
|
||||||
protected function configure(): void
|
protected function configure(): void
|
||||||
{
|
{
|
||||||
$this
|
$this
|
||||||
->setName('scan')
|
->setName('scan')
|
||||||
->setDescription('Scan a URL or file for accessibility violations')
|
->setAliases(['analyse'])
|
||||||
->addArgument('target', InputArgument::REQUIRED, 'The URL or file path to scan')
|
->setDescription('Scan local files, directories, or a URL for accessibility violations')
|
||||||
|
->addArgument('target', InputArgument::OPTIONAL, 'The URL, file, or directory path to scan')
|
||||||
|
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to the configuration file (default: a11y.yaml)')
|
||||||
|
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-9)')
|
||||||
|
->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Use a 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('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('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping');
|
->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')
|
||||||
|
->addOption('max-pages', null, InputOption::VALUE_REQUIRED, 'Maximum pages to crawl (URL scans only)', '20')
|
||||||
|
->addOption('js', null, InputOption::VALUE_NONE, 'Enable JavaScript rendering using Headless Chrome (URL scans only)');
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||||
{
|
{
|
||||||
$io = new SymfonyStyle($input, $output);
|
$io = new SymfonyStyle($input, $output);
|
||||||
$target = $input->getArgument('target');
|
|
||||||
$enableAi = $input->getOption('ai');
|
|
||||||
$projectPath = $input->getOption('project-path') ?? getcwd();
|
|
||||||
|
|
||||||
$io->title("Accessibility Console - Scanning: $target");
|
// 1. Resolve configuration
|
||||||
|
$configPathOption = $input->getOption('config');
|
||||||
|
$configPath = is_string($configPathOption) ? $configPathOption : getcwd() . '/a11y.yaml';
|
||||||
|
$config = Config::fromYaml($configPath);
|
||||||
|
|
||||||
// 1. Fetch HTML
|
// 2. Resolve parameters (CLI options override config file)
|
||||||
$html = @file_get_contents($target);
|
$levelOption = $input->getOption('level');
|
||||||
if (!$html) {
|
$level = is_numeric($levelOption) ? (int)$levelOption : $config->getLevel();
|
||||||
$io->error("Could not read target: $target");
|
|
||||||
return Command::FAILURE;
|
$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.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Setup Scanner
|
$formatOption = $input->getOption('format');
|
||||||
|
$format = is_string($formatOption) ? $formatOption : $config->getFormat();
|
||||||
|
|
||||||
|
$baselinePathOption = $input->getOption('baseline');
|
||||||
|
$baselinePath = is_string($baselinePathOption) ? $baselinePathOption : $config->getBaselinePath();
|
||||||
|
if (!$baselinePath && $input->getOption('generate-baseline')) {
|
||||||
|
$baselinePath = 'a11y-baseline.json'; // default baseline filename
|
||||||
|
}
|
||||||
|
|
||||||
|
$target = $input->getArgument('target');
|
||||||
|
$isUrl = is_string($target) && (str_starts_with($target, 'http://') || str_starts_with($target, 'https://'));
|
||||||
|
|
||||||
|
// If target is a URL, run the legacy URL scanning / crawling logic
|
||||||
|
if ($isUrl) {
|
||||||
|
return $this->executeUrlScan($target, $level, $input, $output, $io);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- LOCAL DIRECTORY / FILE STATIC ANALYSIS ENGINE ---
|
||||||
|
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();
|
||||||
|
if (is_string($target) && $target !== '') {
|
||||||
|
$paths = [$target];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup Analyser
|
||||||
$scanner = new Scanner();
|
$scanner = new Scanner();
|
||||||
foreach (StandardRuleSet::all() as $rule) {
|
$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 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->getId();
|
||||||
|
|
||||||
|
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 = method_exists($rule, 'getId')
|
||||||
|
? $rule->getId()
|
||||||
|
: $reflection->getShortName();
|
||||||
|
$activeRules[$ruleId] = $rule;
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($activeRules as $rule) {
|
||||||
$scanner->addRule($rule);
|
$scanner->addRule($rule);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Scan
|
// Setup Baseline Manager
|
||||||
$violations = $scanner->scan($html);
|
$baselineManager = new BaselineManager();
|
||||||
|
if ($baselinePath && !$input->getOption('generate-baseline')) {
|
||||||
|
$baselineManager->load(getcwd() . '/' . $baselinePath);
|
||||||
|
}
|
||||||
|
|
||||||
if (empty($violations)) {
|
// 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;
|
||||||
|
$showProgress = !$input->getOption('no-progress') && $format === 'console';
|
||||||
|
$onProgress = null;
|
||||||
|
|
||||||
|
if ($showProgress) {
|
||||||
|
$onProgress = function (string $file, int $index, int $total) use ($io, &$progressBar) {
|
||||||
|
if ($progressBar === null) {
|
||||||
|
$progressBar = new ProgressBar($io, $total);
|
||||||
|
$progressBar->start();
|
||||||
|
}
|
||||||
|
$progressBar->setProgress($index);
|
||||||
|
$progressBar->setMessage(basename($file), 'filename');
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run analysis
|
||||||
|
$result = $analyser->analyse($paths, $onProgress);
|
||||||
|
|
||||||
|
if ($progressBar) {
|
||||||
|
$progressBar->finish();
|
||||||
|
$io->newLine(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
$violations = $result['violations'];
|
||||||
|
$baselinedCount = $result['baselinedCount'];
|
||||||
|
|
||||||
|
// AI Fix generation (if requested)
|
||||||
|
if ($input->getOption('ai') && !empty($violations)) {
|
||||||
|
$apiKey = $config->getGeminiApiKey();
|
||||||
|
if ($apiKey) {
|
||||||
|
$fixer = new GeminiFixer($apiKey);
|
||||||
|
$io->comment("Requesting AI fix suggestions for violations...");
|
||||||
|
foreach ($violations as $v) {
|
||||||
|
$suggestion = $fixer->suggestFix($v);
|
||||||
|
if ($suggestion) {
|
||||||
|
$v->fixSuggestion = $suggestion;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$io->warning("GEMINI_API_KEY not found. AI suggestions skipped.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate baseline if option is present
|
||||||
|
if ($input->getOption('generate-baseline')) {
|
||||||
|
if (!$baselinePath) {
|
||||||
|
$io->error("No baseline path specified.");
|
||||||
|
return Command::FAILURE;
|
||||||
|
}
|
||||||
|
$baselineFile = getcwd() . '/' . $baselinePath;
|
||||||
|
|
||||||
|
// Re-run analysis without baseline filtering to catch all violations
|
||||||
|
$unfilteredAnalyser = new Analyser($config, $scanner, new BaselineManager());
|
||||||
|
$allResult = $unfilteredAnalyser->analyse($paths);
|
||||||
|
$allViolations = $allResult['violations'];
|
||||||
|
|
||||||
|
if ($baselineManager->generate($allViolations, $baselineFile)) {
|
||||||
|
$io->success(sprintf("Baseline generated successfully with %d violations at: %s", count($allViolations), $baselinePath));
|
||||||
|
return Command::SUCCESS;
|
||||||
|
} else {
|
||||||
|
$io->error("Failed to generate baseline file.");
|
||||||
|
return Command::FAILURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 !== '') {
|
||||||
|
$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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Legacy URL scanning and crawling logic
|
||||||
|
*/
|
||||||
|
private function executeUrlScan(string $target, int $level, InputInterface $input, OutputInterface $output, SymfonyStyle $io): int
|
||||||
|
{
|
||||||
|
$enableAi = (bool)$input->getOption('ai');
|
||||||
|
$projectPathOption = $input->getOption('project-path');
|
||||||
|
$projectPath = is_string($projectPathOption) ? $projectPathOption : getcwd();
|
||||||
|
if ($projectPath === false) {
|
||||||
|
$projectPath = '.';
|
||||||
|
}
|
||||||
|
|
||||||
|
$io->title("Accessibility Console - Scanning URL: $target (Level $level)");
|
||||||
|
|
||||||
|
// 1. Setup Scanner
|
||||||
|
$scanner = new Scanner();
|
||||||
|
$rules = RuleLevels::getRulesForLevel($level);
|
||||||
|
foreach ($rules as $rule) {
|
||||||
|
$scanner->addRule($rule);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Fetch and Scan
|
||||||
|
$crawl = (bool)$input->getOption('crawl');
|
||||||
|
$useJs = (bool)$input->getOption('js');
|
||||||
|
$chromeRenderer = $useJs ? new \YakNet\AccessibilityConsole\Core\ChromeRenderer() : null;
|
||||||
|
$results = [];
|
||||||
|
|
||||||
|
if ($crawl) {
|
||||||
|
$depthOption = $input->getOption('depth');
|
||||||
|
$depthLimit = is_numeric($depthOption) ? (int)$depthOption : 3;
|
||||||
|
$maxPagesOption = $input->getOption('max-pages');
|
||||||
|
$maxPages = is_numeric($maxPagesOption) ? (int)$maxPagesOption : 20;
|
||||||
|
|
||||||
|
$io->comment("Starting recursive crawl from: $target (Max Depth: $depthLimit, Max Pages: $maxPages)");
|
||||||
|
|
||||||
|
$parsedBase = parse_url($target);
|
||||||
|
$baseHost = $parsedBase['host'] ?? '';
|
||||||
|
|
||||||
|
$queue = [['url' => $target, 'depth' => 1]];
|
||||||
|
$visited = [];
|
||||||
|
|
||||||
|
$client = new \GuzzleHttp\Client([
|
||||||
|
'timeout' => 10,
|
||||||
|
'allow_redirects' => true,
|
||||||
|
'headers' => [
|
||||||
|
'User-Agent' => 'YakNet Accessibility Console Crawler/1.0',
|
||||||
|
]
|
||||||
|
]);
|
||||||
|
|
||||||
|
while (!empty($queue) && count($visited) < $maxPages) {
|
||||||
|
$current = array_shift($queue);
|
||||||
|
|
||||||
|
$url = $current['url'];
|
||||||
|
$depth = (int)$current['depth'];
|
||||||
|
|
||||||
|
$cleanUrl = strtok($url, '#');
|
||||||
|
if ($cleanUrl === false || isset($visited[$cleanUrl])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$visited[$cleanUrl] = true;
|
||||||
|
$io->write(" <fg=gray>Crawling [Depth $depth]:</> <fg=cyan>$cleanUrl</>... ");
|
||||||
|
|
||||||
|
try {
|
||||||
|
if ($chromeRenderer) {
|
||||||
|
$html = $chromeRenderer->render($cleanUrl);
|
||||||
|
} else {
|
||||||
|
$response = $client->request('GET', $cleanUrl);
|
||||||
|
$html = (string)$response->getBody();
|
||||||
|
}
|
||||||
|
$io->writeln("<fg=green>OK</>");
|
||||||
|
|
||||||
|
$pageViolations = $scanner->scan($html);
|
||||||
|
$results[$cleanUrl] = $pageViolations;
|
||||||
|
|
||||||
|
if ($depth < $depthLimit) {
|
||||||
|
$html5 = new \Masterminds\HTML5(['disable_html_ns' => true]);
|
||||||
|
$doc = $html5->loadHTML($html);
|
||||||
|
$links = $doc->getElementsByTagName('a');
|
||||||
|
|
||||||
|
foreach ($links as $link) {
|
||||||
|
$href = $link->getAttribute('href');
|
||||||
|
if (empty($href) || str_starts_with($href, 'javascript:') || str_starts_with($href, 'mailto:') || str_starts_with($href, 'tel:')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$baseUri = new \GuzzleHttp\Psr7\Uri($cleanUrl);
|
||||||
|
$relativeUri = new \GuzzleHttp\Psr7\Uri($href);
|
||||||
|
$absoluteUri = \GuzzleHttp\Psr7\UriResolver::resolve($baseUri, $relativeUri);
|
||||||
|
$absoluteUrl = (string)$absoluteUri;
|
||||||
|
} catch (\Throwable) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$parsedAbsolute = parse_url($absoluteUrl);
|
||||||
|
$absoluteHost = $parsedAbsolute['host'] ?? '';
|
||||||
|
|
||||||
|
if ($absoluteHost === $baseHost) {
|
||||||
|
$cleanAbsolute = strtok($absoluteUrl, '#');
|
||||||
|
if ($cleanAbsolute !== false && !isset($visited[$cleanAbsolute])) {
|
||||||
|
$inQueue = false;
|
||||||
|
foreach ($queue as $q) {
|
||||||
|
if ($q['url'] === $cleanAbsolute) {
|
||||||
|
$inQueue = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!$inQueue) {
|
||||||
|
$queue[] = ['url' => $cleanAbsolute, 'depth' => $depth + 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$io->writeln("<fg=red>FAIL (" . $e->getMessage() . ")</>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if ($chromeRenderer) {
|
||||||
|
try {
|
||||||
|
$html = $chromeRenderer->render($target);
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
$io->error("Failed JavaScript rendering: " . $e->getMessage());
|
||||||
|
return Command::FAILURE;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$html = @file_get_contents($target);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($html === false || $html === '') {
|
||||||
|
$io->error("Could not read target URL: $target");
|
||||||
|
return Command::FAILURE;
|
||||||
|
}
|
||||||
|
$violations = $scanner->scan($html);
|
||||||
|
$results[$target] = $violations;
|
||||||
|
}
|
||||||
|
|
||||||
|
$totalViolations = 0;
|
||||||
|
foreach ($results as $url => $violations) {
|
||||||
|
$totalViolations += count($violations);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($totalViolations === 0) {
|
||||||
$io->success("No violations found!");
|
$io->success("No violations found!");
|
||||||
return Command::SUCCESS;
|
return Command::SUCCESS;
|
||||||
}
|
}
|
||||||
|
|
||||||
$io->section("Found " . count($violations) . " violations");
|
$io->section("Found a total of $totalViolations violations across " . count($results) . " pages");
|
||||||
|
|
||||||
// 4. Setup Helpers
|
|
||||||
$locator = new SourceLocator($projectPath);
|
$locator = new SourceLocator($projectPath);
|
||||||
$config = new Config();
|
$config = new Config();
|
||||||
$fixer = $enableAi ? new GeminiFixer($config->getGeminiApiKey()) : null;
|
$fixer = $enableAi ? new GeminiFixer($config->getGeminiApiKey()) : null;
|
||||||
|
|
||||||
foreach ($violations as $violation) {
|
foreach ($results as $url => $violations) {
|
||||||
$io->writeln("<fg=white;bg=red;options=bold> {$violation->ruleId} </>\t<fg=red>{$violation->message}</>");
|
if (empty($violations)) {
|
||||||
|
continue;
|
||||||
// Show Snippet
|
|
||||||
$io->writeln(" <fg=gray>Snippet:</> <fg=yellow>" . htmlspecialchars($violation->htmlSnippet) . "</>");
|
|
||||||
|
|
||||||
// Source Mapping
|
|
||||||
$location = $locator->locate($violation->htmlSnippet);
|
|
||||||
if ($location) {
|
|
||||||
$io->writeln(" <fg=gray>Source:</> <fg=cyan>{$location['file']}:{$location['line']}</>");
|
|
||||||
}
|
}
|
||||||
|
$io->section("Page: $url (" . count($violations) . " violations)");
|
||||||
|
|
||||||
// AI Fixer
|
foreach ($violations as $violation) {
|
||||||
if ($enableAi && $fixer) {
|
$io->writeln("<fg=white;bg=red;options=bold> {$violation->ruleId} </>\t<fg=red>{$violation->message}</>");
|
||||||
$io->write(" <fg=gray>AI Fix Suggestion:</> ");
|
$io->writeln(" <fg=gray>Snippet:</> <fg=yellow>" . htmlspecialchars($violation->htmlSnippet) . "</>");
|
||||||
$suggestion = $fixer->suggestFix($violation);
|
|
||||||
if ($suggestion) {
|
$location = $locator->locate($violation->htmlSnippet);
|
||||||
$io->writeln("<fg=green>" . htmlspecialchars($suggestion) . "</>");
|
if ($location) {
|
||||||
} else {
|
$io->writeln(" <fg=gray>Source:</> <fg=cyan>{$location['file']}:{$location['line']}</>");
|
||||||
$io->writeln("<fg=red>Could not generate suggestion (check API key)</>");
|
$violation->location = $location;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($enableAi && $fixer) {
|
||||||
|
$io->write(" <fg=gray>AI Fix Suggestion:</> ");
|
||||||
|
$suggestion = $fixer->suggestFix($violation);
|
||||||
|
if ($suggestion) {
|
||||||
|
$violation->fixSuggestion = $suggestion;
|
||||||
|
$io->writeln("<fg=green>" . htmlspecialchars($suggestion) . "</>");
|
||||||
|
} else {
|
||||||
|
$io->writeln("<fg=red>Could not generate suggestion (check API key)</>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$io->writeln("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$reportPath = $input->getOption('report');
|
||||||
|
if (is_string($reportPath) && $reportPath !== '') {
|
||||||
|
$allViolations = [];
|
||||||
|
foreach ($results as $urlViolations) {
|
||||||
|
$allViolations = array_merge($allViolations, $urlViolations);
|
||||||
|
}
|
||||||
|
$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));
|
||||||
$io->writeln("");
|
} elseif ($extension === 'sarif') {
|
||||||
}
|
$sarifFormatter = new SarifFormatter();
|
||||||
|
file_put_contents($reportPath, $sarifFormatter->render($violations));
|
||||||
$io->warning("Scanned " . count($violations) . " errors. Use --ai to get fix suggestions.");
|
} elseif ($extension === 'checkstyle') {
|
||||||
|
$checkstyleFormatter = new CheckstyleFormatter();
|
||||||
// Export Report
|
file_put_contents($reportPath, $checkstyleFormatter->render($violations));
|
||||||
$reportPath = $input->getOption('report');
|
} elseif ($extension === 'xml' || $extension === 'junit') {
|
||||||
if ($reportPath) {
|
$junitFormatter = new JunitFormatter();
|
||||||
$extension = pathinfo($reportPath, PATHINFO_EXTENSION);
|
file_put_contents($reportPath, $junitFormatter->render($violations));
|
||||||
if ($extension === 'json') {
|
} elseif ($extension === 'pdf') {
|
||||||
$data = array_map(fn($v) => $v->toArray(), $violations);
|
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
|
||||||
file_put_contents($reportPath, json_encode($data, JSON_PRETTY_PRINT));
|
$serialized = [];
|
||||||
} else {
|
foreach ($violations as $v) {
|
||||||
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
|
$serialized[] = $v->toArray();
|
||||||
file_put_contents($reportPath, $reporter->render($violations, $target));
|
|
||||||
}
|
}
|
||||||
$io->success("Report saved to: $reportPath");
|
$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));
|
||||||
}
|
}
|
||||||
|
|
||||||
return Command::SUCCESS;
|
$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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,14 +19,39 @@ abstract class AbstractRule
|
|||||||
*/
|
*/
|
||||||
abstract public function getSeverity(): Severity;
|
abstract public function getSeverity(): Severity;
|
||||||
|
|
||||||
protected function createViolation(string $message, \DOMElement $element): Violation
|
public function getLevel(): int
|
||||||
{
|
{
|
||||||
|
return 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = '';
|
||||||
|
if ($doc !== null) {
|
||||||
|
$htmlVal = $doc->saveHTML($element);
|
||||||
|
if (is_string($htmlVal)) {
|
||||||
|
$html = $htmlVal;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return new Violation(
|
return new Violation(
|
||||||
ruleId: (new \ReflectionClass($this))->getShortName(),
|
ruleId: $this->getId(),
|
||||||
message: $message,
|
message: $message,
|
||||||
severity: $this->getSeverity(),
|
severity: $this->getSeverity(),
|
||||||
standard: $this->getStandard(),
|
standard: $this->getStandard(),
|
||||||
htmlSnippet: $element->ownerDocument->saveHTML($element)
|
htmlSnippet: $html,
|
||||||
|
fixSuggestion: $suggestion
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
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
|
||||||
|
{
|
||||||
|
private Config $config;
|
||||||
|
private Scanner $scanner;
|
||||||
|
private BaselineManager $baselineManager;
|
||||||
|
private TemplatePreprocessor $templatePreprocessor;
|
||||||
|
private PreciseElementLocator $elementLocator;
|
||||||
|
private InlineSuppressionParser $suppressionParser;
|
||||||
|
private ?ScanCache $cache;
|
||||||
|
private string $projectRoot;
|
||||||
|
|
||||||
|
/** @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) : '.';
|
||||||
|
|
||||||
|
if ($baselineManager === null) {
|
||||||
|
$baselinePath = $this->config->getBaselinePath();
|
||||||
|
if ($baselinePath) {
|
||||||
|
$this->baselineManager->load($this->projectRoot . '/' . $baselinePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function setupScanner(): Scanner
|
||||||
|
{
|
||||||
|
$scanner = new Scanner();
|
||||||
|
$rules = RuleLevels::getRulesForLevel($this->config->getLevel());
|
||||||
|
$rulesConfig = $this->config->getRulesConfig();
|
||||||
|
|
||||||
|
$activeRules = [];
|
||||||
|
foreach ($rules as $rule) {
|
||||||
|
$ruleId = $rule->getId();
|
||||||
|
|
||||||
|
if (in_array($ruleId, $rulesConfig['exclude'], true)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$activeRules[$ruleId] = $rule;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Include custom rules
|
||||||
|
foreach ($rulesConfig['include'] as $customRuleClass) {
|
||||||
|
if (class_exists($customRuleClass)) {
|
||||||
|
try {
|
||||||
|
$reflection = new \ReflectionClass($customRuleClass);
|
||||||
|
if ($reflection->isInstantiable()) {
|
||||||
|
$rule = $reflection->newInstance();
|
||||||
|
$ruleId = method_exists($rule, 'getId')
|
||||||
|
? $rule->getId()
|
||||||
|
: $reflection->getShortName();
|
||||||
|
$activeRules[$ruleId] = $rule;
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
// Ignore instantiation failures
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($activeRules as $rule) {
|
||||||
|
$scanner->addRule($rule);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $scanner;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Analyse files and return a list of violations.
|
||||||
|
*
|
||||||
|
* @param array<int, string>|null $pathsOverride
|
||||||
|
* @param callable|null $onProgress Function called for progress tracking: fn(string $file, int $index, int $total)
|
||||||
|
* @return array{violations: Violation[], baselinedCount: int}
|
||||||
|
*/
|
||||||
|
public function analyse(?array $pathsOverride = null, ?callable $onProgress = null): array
|
||||||
|
{
|
||||||
|
$paths = $pathsOverride ?? $this->config->getPaths();
|
||||||
|
$excludePaths = $this->config->getExcludePaths();
|
||||||
|
|
||||||
|
// Resolve all files to scan
|
||||||
|
$filesToScan = [];
|
||||||
|
foreach ($paths as $path) {
|
||||||
|
if (is_file($path)) {
|
||||||
|
$filesToScan[] = str_replace('\\', '/', realpath($path) ?: $path);
|
||||||
|
} elseif (is_dir($path)) {
|
||||||
|
$files = $this->findFiles($path, $excludePaths);
|
||||||
|
$filesToScan = array_merge($filesToScan, $files);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$filesToScan = array_unique($filesToScan);
|
||||||
|
$totalFiles = count($filesToScan);
|
||||||
|
|
||||||
|
$violations = [];
|
||||||
|
$baselinedCount = 0;
|
||||||
|
$this->suppressedAuditLog = [];
|
||||||
|
|
||||||
|
foreach ($filesToScan as $index => $file) {
|
||||||
|
if ($onProgress) {
|
||||||
|
$onProgress($file, $index + 1, $totalFiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
$rawContent = @file_get_contents($file);
|
||||||
|
if ($rawContent === false || trim($rawContent) === '') {
|
||||||
|
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) {
|
||||||
|
$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)) {
|
||||||
|
$baselinedCount++;
|
||||||
|
} else {
|
||||||
|
$violations[] = $violation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->cache?->save();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'violations' => $violations,
|
||||||
|
'baselinedCount' => $baselinedCount
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function makePathRelative(string $absolutePath): string
|
||||||
|
{
|
||||||
|
$absolutePath = str_replace('\\', '/', realpath($absolutePath) ?: $absolutePath);
|
||||||
|
if ($this->projectRoot !== '.' && str_starts_with($absolutePath, $this->projectRoot)) {
|
||||||
|
$relative = ltrim(substr($absolutePath, strlen($this->projectRoot)), '/');
|
||||||
|
return $relative === '' ? '.' : $relative;
|
||||||
|
}
|
||||||
|
return $absolutePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<int, string> $excludePaths
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
private function findFiles(string $dir, array $excludePaths): array
|
||||||
|
{
|
||||||
|
$realDir = realpath($dir);
|
||||||
|
if ($realDir === false) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$files = [];
|
||||||
|
try {
|
||||||
|
$directory = new RecursiveDirectoryIterator($realDir, \FilesystemIterator::SKIP_DOTS);
|
||||||
|
$filter = new \RecursiveCallbackFilterIterator($directory, function ($current) use ($excludePaths) {
|
||||||
|
/** @var SplFileInfo $current */
|
||||||
|
$filename = $current->getFilename();
|
||||||
|
$pathname = str_replace('\\', '/', $current->getPathname());
|
||||||
|
|
||||||
|
// Exclude common directories/files
|
||||||
|
foreach ($excludePaths as $exclude) {
|
||||||
|
$normalizedExclude = str_replace('\\', '/', $exclude);
|
||||||
|
if ($filename === $normalizedExclude || str_contains($pathname, '/' . $normalizedExclude . '/')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
$iterator = new RecursiveIteratorIterator($filter, RecursiveIteratorIterator::SELF_FIRST);
|
||||||
|
|
||||||
|
$extensions = $this->config->getExtensions();
|
||||||
|
|
||||||
|
foreach ($iterator as $file) {
|
||||||
|
/** @var SplFileInfo $file */
|
||||||
|
if ($file->isDir()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$filename = $file->getFilename();
|
||||||
|
$isValidExt = false;
|
||||||
|
foreach ($extensions as $ext) {
|
||||||
|
if (str_ends_with($filename, '.' . $ext) || ($ext === 'blade.php' && str_ends_with($filename, '.blade.php'))) {
|
||||||
|
$isValidExt = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($isValidExt) {
|
||||||
|
$files[] = str_replace('\\', '/', $file->getPathname());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
// Ignore directory iteration errors
|
||||||
|
}
|
||||||
|
|
||||||
|
return $files;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace YakNet\AccessibilityConsole\Core;
|
||||||
|
|
||||||
|
class BaselineManager
|
||||||
|
{
|
||||||
|
/** @var array<string, bool> */
|
||||||
|
private array $ignoredKeys = [];
|
||||||
|
|
||||||
|
public function load(string $baselinePath): bool
|
||||||
|
{
|
||||||
|
if (!file_exists($baselinePath) || !is_readable($baselinePath)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$content = file_get_contents($baselinePath);
|
||||||
|
if ($content === false) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$data = json_decode($content, true);
|
||||||
|
if (!is_array($data) || !isset($data['violations']) || !is_array($data['violations'])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($data['violations'] as $item) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param Violation[] $violations
|
||||||
|
*/
|
||||||
|
public function generate(array $violations, string $baselinePath): bool
|
||||||
|
{
|
||||||
|
$serialized = [
|
||||||
|
'generator' => 'YakNet Accessibility Console',
|
||||||
|
'violations' => []
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($violations as $v) {
|
||||||
|
$file = $v->location['file'] ?? '';
|
||||||
|
$serialized['violations'][] = [
|
||||||
|
'file' => $file,
|
||||||
|
'ruleId' => $v->ruleId,
|
||||||
|
'htmlSnippet' => $v->htmlSnippet
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort baseline violations by file and ruleId for cleaner git diffs
|
||||||
|
usort($serialized['violations'], function ($a, $b) {
|
||||||
|
$fileCmp = strcmp($a['file'], $b['file']);
|
||||||
|
if ($fileCmp !== 0) {
|
||||||
|
return $fileCmp;
|
||||||
|
}
|
||||||
|
return strcmp($a['ruleId'], $b['ruleId']);
|
||||||
|
});
|
||||||
|
|
||||||
|
$json = json_encode($serialized, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||||
|
if ($json === false) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$dir = dirname($baselinePath);
|
||||||
|
if (!is_dir($dir)) {
|
||||||
|
mkdir($dir, 0755, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return file_put_contents($baselinePath, $json) !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isIgnored(string $file, string $ruleId, string $htmlSnippet): bool
|
||||||
|
{
|
||||||
|
$key = $this->calculateKey($file, $ruleId, $htmlSnippet);
|
||||||
|
return isset($this->ignoredKeys[$key]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function calculateKey(string $file, string $ruleId, string $htmlSnippet): string
|
||||||
|
{
|
||||||
|
// Normalize snippet using fuzzy baseline matcher
|
||||||
|
$normalizedSnippet = \YakNet\AccessibilityConsole\Core\Baseline\FuzzyBaselineMatcher::normalize($htmlSnippet);
|
||||||
|
if ($normalizedSnippet === '') {
|
||||||
|
$normalizedSnippet = trim($htmlSnippet);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize file separator to forward slashes for cross-platform compatibility
|
||||||
|
$normalizedFile = str_replace('\\', '/', $file);
|
||||||
|
|
||||||
|
return md5($normalizedFile . '::' . $ruleId . '::' . $normalizedSnippet);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace YakNet\AccessibilityConsole\Core;
|
||||||
|
|
||||||
|
use HeadlessChromium\BrowserFactory;
|
||||||
|
use HeadlessChromium\Navigation;
|
||||||
|
|
||||||
|
class ChromeRenderer
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Navigate to URL using headless Chrome and return fully rendered HTML.
|
||||||
|
*/
|
||||||
|
public function render(string $url): string
|
||||||
|
{
|
||||||
|
$browserFactory = new BrowserFactory();
|
||||||
|
|
||||||
|
$options = [
|
||||||
|
'windowSize' => [1280, 1024],
|
||||||
|
'noSandbox' => true,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Windows Chrome binary path auto-detection override
|
||||||
|
$chromeBinary = $_ENV['CHROME_BINARY'] ?? getenv('CHROME_BINARY') ?: null;
|
||||||
|
if (!$chromeBinary && PHP_OS_FAMILY === 'Windows') {
|
||||||
|
$standardPaths = [
|
||||||
|
'C:/Program Files/Google/Chrome/Application/chrome.exe',
|
||||||
|
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
|
||||||
|
'C:/Program Files/Google/Chrome/Application/chrome.exe'
|
||||||
|
];
|
||||||
|
foreach ($standardPaths as $path) {
|
||||||
|
if (file_exists($path)) {
|
||||||
|
$chromeBinary = $path;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($chromeBinary) {
|
||||||
|
$options['chromeBinary'] = $chromeBinary;
|
||||||
|
}
|
||||||
|
|
||||||
|
$browser = $browserFactory->createBrowser($options);
|
||||||
|
|
||||||
|
try {
|
||||||
|
$page = $browser->createPage();
|
||||||
|
|
||||||
|
// Navigate and wait for onload event
|
||||||
|
$navigation = $page->navigate($url);
|
||||||
|
$navigation->waitForNavigation(\HeadlessChromium\Page::LOAD, 10000); // 10 seconds timeout
|
||||||
|
|
||||||
|
// Extra wait for async JS rendering to complete
|
||||||
|
usleep(1500000); // 1.5s
|
||||||
|
|
||||||
|
$html = $page->getHtml();
|
||||||
|
} finally {
|
||||||
|
$browser->close();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $html;
|
||||||
|
}
|
||||||
|
}
|
||||||
+153
-2
@@ -4,16 +4,44 @@ namespace YakNet\AccessibilityConsole\Core;
|
|||||||
|
|
||||||
class Config
|
class Config
|
||||||
{
|
{
|
||||||
|
/** @var array<string, mixed> */
|
||||||
private array $settings = [];
|
private array $settings = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array<string, mixed> $settings
|
||||||
|
*/
|
||||||
public function __construct(array $settings = [])
|
public function __construct(array $settings = [])
|
||||||
{
|
{
|
||||||
$this->settings = $settings;
|
$this->settings = $settings;
|
||||||
|
$this->loadDotenv();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function loadDotenv(): void
|
||||||
|
{
|
||||||
|
$cwd = getcwd();
|
||||||
|
if ($cwd && file_exists($cwd . '/.env')) {
|
||||||
|
try {
|
||||||
|
$dotenv = \Dotenv\Dotenv::createImmutable($cwd);
|
||||||
|
$dotenv->safeLoad();
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
// Ignore Dotenv errors silently
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function fromYaml(string $path): self
|
public static function fromYaml(string $path): self
|
||||||
{
|
{
|
||||||
// Placeholder for YAML loading logic
|
if (file_exists($path)) {
|
||||||
|
try {
|
||||||
|
$content = \Symfony\Component\Yaml\Yaml::parseFile($path);
|
||||||
|
if (is_array($content)) {
|
||||||
|
/** @var array<string, mixed> $content */
|
||||||
|
return new self($content);
|
||||||
|
}
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
// Ignore parsing errors
|
||||||
|
}
|
||||||
|
}
|
||||||
return new self([]);
|
return new self([]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,8 +50,131 @@ class Config
|
|||||||
return $this->settings[$key] ?? $default;
|
return $this->settings[$key] ?? $default;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public function getPaths(): array
|
||||||
|
{
|
||||||
|
$paths = $this->get('paths');
|
||||||
|
if (is_array($paths)) {
|
||||||
|
return array_values(array_filter($paths, 'is_string'));
|
||||||
|
}
|
||||||
|
if (is_string($paths)) {
|
||||||
|
return [$paths];
|
||||||
|
}
|
||||||
|
return ['.']; // default to current directory
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int, string>
|
||||||
|
*/
|
||||||
|
public function getExcludePaths(): array
|
||||||
|
{
|
||||||
|
$exclude = $this->get('exclude_paths');
|
||||||
|
if (is_array($exclude)) {
|
||||||
|
return array_values(array_filter($exclude, 'is_string'));
|
||||||
|
}
|
||||||
|
if (is_string($exclude)) {
|
||||||
|
return [$exclude];
|
||||||
|
}
|
||||||
|
return ['vendor', 'node_modules', 'tests', 'storage', '.git']; // sensible defaults
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getLevel(): int
|
||||||
|
{
|
||||||
|
$level = $this->get('level', 4);
|
||||||
|
return is_numeric($level) ? (int)$level : 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getBaselinePath(): ?string
|
||||||
|
{
|
||||||
|
$baseline = $this->get('baseline');
|
||||||
|
return is_string($baseline) ? $baseline : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getFormat(): string
|
||||||
|
{
|
||||||
|
$format = $this->get('format', 'console');
|
||||||
|
return is_string($format) ? $format : 'console';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array{include: array<int, string>, exclude: array<int, string>}
|
||||||
|
*/
|
||||||
|
public function getRulesConfig(): array
|
||||||
|
{
|
||||||
|
$rules = $this->get('rules', []);
|
||||||
|
$include = [];
|
||||||
|
$exclude = [];
|
||||||
|
|
||||||
|
if (is_array($rules)) {
|
||||||
|
if (isset($rules['include']) && is_array($rules['include'])) {
|
||||||
|
$include = array_values(array_filter($rules['include'], 'is_string'));
|
||||||
|
}
|
||||||
|
if (isset($rules['exclude']) && is_array($rules['exclude'])) {
|
||||||
|
$exclude = array_values(array_filter($rules['exclude'], 'is_string'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'include' => $include,
|
||||||
|
'exclude' => $exclude
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
public function getGeminiApiKey(): ?string
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+76
-3
@@ -2,26 +2,99 @@
|
|||||||
|
|
||||||
namespace YakNet\AccessibilityConsole\Core;
|
namespace YakNet\AccessibilityConsole\Core;
|
||||||
|
|
||||||
|
use DOMDocument;
|
||||||
|
use DOMElement;
|
||||||
|
use DOMXPath;
|
||||||
|
use YakNet\AccessibilityConsole\Rules\RuleExecutionStats;
|
||||||
|
use YakNet\AccessibilityConsole\Rules\RuleInterface;
|
||||||
|
|
||||||
class RuleEngine
|
class RuleEngine
|
||||||
{
|
{
|
||||||
/** @var AbstractRule[] */
|
/** @var array<int, mixed> */
|
||||||
private array $rules = [];
|
private array $rules = [];
|
||||||
|
|
||||||
public function addRule(AbstractRule $rule): void
|
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;
|
$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[]
|
* @return Violation[]
|
||||||
*/
|
*/
|
||||||
public function run(\DOMDocument $doc): array
|
public function run(DOMDocument $doc): array
|
||||||
{
|
{
|
||||||
$allViolations = [];
|
$allViolations = [];
|
||||||
|
$docRules = [];
|
||||||
|
$elementRules = [];
|
||||||
|
|
||||||
foreach ($this->rules as $rule) {
|
foreach ($this->rules as $rule) {
|
||||||
|
if ($rule instanceof AbstractRule) {
|
||||||
|
$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);
|
$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);
|
$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;
|
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',
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
-7
@@ -4,11 +4,21 @@ namespace YakNet\AccessibilityConsole\Core;
|
|||||||
|
|
||||||
class Scanner
|
class Scanner
|
||||||
{
|
{
|
||||||
public function __construct(private ?RuleEngine $engine = null)
|
private RuleEngine $engine;
|
||||||
|
|
||||||
|
public function __construct(?RuleEngine $engine = null)
|
||||||
{
|
{
|
||||||
if ($this->engine === null) {
|
$this->engine = $engine ?? new RuleEngine();
|
||||||
$this->engine = new RuleEngine();
|
}
|
||||||
}
|
|
||||||
|
public function addRule(mixed $rule): void
|
||||||
|
{
|
||||||
|
$this->engine->addRule($rule);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getEngine(): RuleEngine
|
||||||
|
{
|
||||||
|
return $this->engine;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,9 +33,14 @@ class Scanner
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
$doc = new \DOMDocument();
|
$html5 = new \Masterminds\HTML5([
|
||||||
// Suppress warnings for malformed HTML
|
'disable_html_ns' => true,
|
||||||
@$doc->loadHTML('<?xml encoding="utf-8" ?>' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
|
]);
|
||||||
|
$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);
|
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];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,18 +2,24 @@
|
|||||||
|
|
||||||
namespace YakNet\AccessibilityConsole\Core;
|
namespace YakNet\AccessibilityConsole\Core;
|
||||||
|
|
||||||
readonly class Violation
|
class Violation
|
||||||
{
|
{
|
||||||
|
/**
|
||||||
|
* @param array{file?: string, line: int, column?: int}|null $location
|
||||||
|
*/
|
||||||
public function __construct(
|
public function __construct(
|
||||||
public string $ruleId,
|
public string $ruleId,
|
||||||
public string $message,
|
public string $message,
|
||||||
public Severity $severity,
|
public Severity $severity,
|
||||||
public WCAGStandard $standard,
|
public WCAGStandard $standard,
|
||||||
public string $htmlSnippet,
|
public string $htmlSnippet = '',
|
||||||
public ?array $location = null, // ['file' => '...', 'line' => 0]
|
public ?array $location = null, // ['file' => '...', 'line' => 0]
|
||||||
public ?string $fixSuggestion = null
|
public ?string $fixSuggestion = 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
|
public function toArray(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
|
|||||||
@@ -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 [];
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user