Compare commits

..
13 Commits
Author SHA1 Message Date
Enes Yakıştır 5680882bee feat(v4.0.0): 175 WCAG 2.2 & ARIA rules, VPAT 2.5, 11 presets, PolicyEngine, inline suppressions, cache, CI generator, PHPUnit assertions, and open-source YakNet identity 2026-11-21 09:48:29 +03:00
Enes Yakıştır ef8ccb9f75 feat(v3.3.0): enterprise presets, badges, notifications, rule controller, watch mode, offline healer, and WCAG 2.2 ruleset 2026-09-12 10:12:05 +03:00
Enes Yakıştır 2de1f34878 feat(v3.2.7): expand WCAG ruleset to 127 rules, add HTML syntax linter, single-pass rule engine, template preprocessor, and accessibility analytics 2026-08-16 22:00:30 +03:00
Enes Yakıştır 9a6784ad19 release: v3.2.6 - restore dompdf and phpspreadsheet to require section 2026-08-01 08:12:06 +03:00
Enes Yakıştır 399ba86ca2 Update engine version string to v3.2 in PdfReportGenerator (v3.2.5) 2026-07-31 17:07:27 +03:00
Enes Yakıştır b634e97921 Set Europe/Istanbul timezone in PdfReportGenerator and ensure stable dates (v3.2.4) 2026-07-31 17:03:22 +03:00
Enes Yakıştır a0a0a369b8 Fix Turkish UTF-8 font encoding in PdfReportGenerator for Dompdf (v3.2.3) 2026-07-31 16:59:49 +03:00
Enes Yakıştır 3fb927e211 release: v3.2.2 - Move optional export packages to suggest section to prevent root package conflict errors 2026-07-31 02:11:45 +03:00
Enes Yakıştır c33eca5adf release: v3.2.1 - Widen dependency constraints for universal project compatibility (PhpSpreadsheet, Dompdf, Symfony, Spatie Color) 2026-07-31 02:09:04 +03:00
Enes Yakıştır 73fbf485d2 release: v3.2.0 - Enterprise Edition with Live Web Dashboard, PDF/Excel Exporters, Framework Stubs & 110 WCAG Rules 2026-07-31 00:13:31 +03:00
Enes Yakıştır 58b1618d96 feat: add 15 new WCAG rules, dynamic ARIA checks and bump version to v3.1.4 2026-07-30 20:34:41 +03:00
Enes Yakıştır 164828f9f7 fix: resolve PHPStan level 9 errors and bump version to v3.1.3 2026-07-29 06:31:35 +03:00
Enes Yakıştır 6f4799dc38 fix: bump version to 3.1.2 and resolve Symfony 8 compatibility issue 2026-07-14 00:28:58 +03:00
327 changed files with 20554 additions and 430 deletions
+35
View File
@@ -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.
+42
View File
@@ -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 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2026 YakNet Bilişim <[email protected]>
Copyright (c) 2026 YakNet <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+217 -68
View File
@@ -1,144 +1,293 @@
# YakNet Accessibility Console 2.9 (AI-Powered Static Analysis)
# YakNet Accessibility Console 4.0
[![PHP Version](https://img.shields.io/badge/php-%5E8.2-blue.svg)](https://php.net)
[![PHPStan](https://img.shields.io/badge/PHPStan-Level%209-brightgreen.svg)](https://phpstan.org)
[![Rules](https://img.shields.io/badge/WCAG%20%26%20ARIA%20Rules-175%20Active-purple.svg)](https://www.w3.org/WAI/standards-guidelines/wcag/)
[![Presets](https://img.shields.io/badge/Compliance%20Presets-11-teal.svg)](#-mevzuat-ve-sektörel-ön-ayarlar-presets)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![AI Powered](https://img.shields.io/badge/AI-Powered-purple.svg)](https://gemini.google.com)
[![Open Source](https://img.shields.io/badge/Open%20Source-YakNet-orange.svg)](https://forum.yak.net.tr)
**YakNet Accessibility Console**, web projelerinizdeki erişilebilirlik (WCAG 2.1) hatalarını sadece tespit etmekle kalmayan, aynı zamanda **Yapay Zeka (AI)** desteğiyle bu hataları otomatik olarak düzeltebilen (Self-Healing) profesyonel bir PHP static analysis kütüphanesidir.
**YakNet Accessibility Console**, web uygulamalarındaki erişilebilirlik (WCAG 2.1, WCAG 2.2, WAI-ARIA 1.2, ARIA APG) ve HTML söz dizimi sorunlarını statik ve DOM tabanlı olarak analiz eden, **175 benzersiz kural**, **11 mevzuat/sektör uyumluluk profili**, **VPAT 2.5 (ACR) rapor üreticisi**, **politika yönetim motoru (Policy Engine)** ve **otomatik onarım (Offline & AI Self-Healing)** yetenekleri sunan açık kaynaklı bir PHP erişilebilirlik analiz platformudur.
PHPStan ve PHP-CS-Fixer esintili yapısıyla, yerel görünüm şablonlarınızı (`.blade.php`, `.twig`, `.html`, `.php`) doğrudan tarayabilir, baseline desteğiyle mevcut hataları yok sayabilir ve CI/CD süreçlerinize tam entegre çalışabilir.
**YakNet** tarafından açık kaynak topluluğu ve büyük ölçekli organizasyonların, kamu portallarının, üniversitelerin ve ürün ekiplerinin ortak standartlarla erişilebilir web yazılımları üretebilmesi için geliştirilmektedir.
Laravel Blade (`.blade.php`), Twig (`.twig`), **Vue SFC (`.vue`)**, **React JSX/TSX (`.jsx`, `.tsx`)**, PHP (`.php`) ve standart HTML şablonlarını doğrudan tarar; satır içi gizleme yönergelerini (`<!-- a11y-disable-next-line -->`), baseline yönetimini ve CI/CD kalite kapılarını sıfır ek kurulumla destekler.
---
## 🌟 Öne Çıkan Özellikler
- **🤖 AI Self-Healing:** Tespit edilen WCAG hataları için Google Gemini AI üzerinden akıllı çözüm önerileri alır ve kaynak kodunuzu (Blade, Twig, PHP, HTML) otomatik olarak tamir eder.
- **⚡ PHPStan Tarzı Analiz:** Tüm projeyi veya belirli dizinleri komut satırından tarayarak hataları tam dosya yolu ve satır numarası ile listeler.
- **🛡️ Baseline Desteği:** `a11y-baseline.json` oluşturarak mevcut erişilebilirlik hatalarını yok sayabilir, CI/CD pipeline'ınızın sadece yeni hatalarda kırılmasını sağlayabilirsiniz.
- **⚙️ YAML Konfigürasyonu:** `a11y.yaml` dosyası üzerinden tarama yollarını, hariç tutulacak klasörleri, kural seviyelerini ve özel kural setlerini yapılandırabilirsiniz.
- **🔌 Çoklu Çıktı Formatları:**
- `console`: Renkli ve düzenli terminal tablosu.
- `json`: Makine tarafından okunabilir JSON çıktısı.
- `github`: GitHub Actions PR süreçlerinde doğrudan inline hata göstermek için workflow formatı.
- **📊 Görsel Raporlama:** Sonuçları modern bir HTML Dashboard raporu olarak dışarı aktarın.
- **🛡️ 175 Benzersiz WCAG 2.1 / 2.2, WAI-ARIA 1.2 & APG Kuralı:**
- **WCAG 2.2 Tam Kapsamı:** `FocusAppearance` (2.4.13), `FocusNotObscured` (2.4.11), `TargetSizeMinimum` & `TargetSpacingMinimum` (2.5.8), `DraggingMovements` (2.5.7), `ConsistentHelp` (3.2.6), `RedundantEntry` (3.3.7), `AccessibleAuth` (3.3.8).
- **WAI-ARIA 1.2 & APG Bileşen Desenleri:** Tabs (`AriaTablistPattern`), Combobox (`AriaComboboxPattern`), Switch (`AriaSwitchState`), Slider (`AriaSliderAttributes`), Menu/Menubar (`AriaMenuPattern`), Tree (`AriaTreePattern`), Breadcrumb (`AriaBreadcrumbPattern`), Modal Dialog (`AriaModalBackdrop`), `aria-owns` & `aria-activedescendant` bütünlük doğrulaması, kullanımdan kaldırılmış/soyut rol denetimi (`AriaDeprecatedRoles`).
- **Hareket, Nöbet Güvenliği ve Bilişsel Erişilebilirlik:** `FlashingContentBanned` (2.3.1 — >3Hz yanıp sönme koruması), `MotionAnimationReduced` (2.3.3 — `prefers-reduced-motion`), `OrientationLockBanned` (1.3.4), `CharacterKeyShortcuts` (2.1.4), `PointerCancellation` (2.5.2), `TimeoutWarning` (2.2.1), `HoverFocusContentDismissible` (1.4.13), `ColorContrastAAA` (1.4.6 — 7:1), `JustifiedTextBanned` (1.4.8), `AllCapsLongText` (3.1.5).
- **📋 VPAT 2.5 / ACR Uyumluluk Raporu Üreticisi (`vpat`):**
- WCAG 2.1 / 2.2, Revised Section 508 ve EN 301 549 ile uyumlu **VPAT 2.5 Accessibility Conformance Report** belgelerini tek komutla **Markdown**, **HTML** ve **JSON** formatlarında üretir (`Supports`, `Partially Supports`, `Does Not Support`, `Not Evaluated`).
- **🏛️ 11 Mevzuat ve Sektörel Uyumluluk Ön Ayarı (`presets`):**
- `wcag22-aa`, `wcag22-aaa`, `en301549`, `eaa2025` (European Accessibility Act), `section508`, `bitv2`, `government`, `healthcare`, `banking`, `education`, `ecommerce`.
- **⚖️ Politika Yönetim Motoru (`PolicyEngine`):**
- `a11y.yaml` içinden organizasyon genelinde geçerli kalite kuralları tanımlayın: `min_score`, `max_critical`, `max_errors`, `max_warnings`, `required_standards` (örn. A & AA sıfır hata), `banned_rules` (sıfır toleranslı kurallar), `severity_overrides` (kural ciddiyetini yükseltme/düşürme) ve POUR ilkesi bazlı limitler (`principle_limits`).
- **🔇 Denetlenebilir Satır İçi Gizleme Yönergeleri (`InlineSuppressionParser`):**
- `<!-- a11y-disable-next-line RULE_ID -- gerekçe -->`, `<!-- a11y-disable RULE_ID --> ... <!-- a11y-enable RULE_ID -->`, `<!-- a11y-disable-file -->` yönergelerini destekler ve her gizlemeyi gerekçesiyle birlikte denetim kaydına (`suppressedAuditLog`) işler.
- **📈 Geçmiş Takibi ve Regresyon Karşılaştırması (`compare` & `--save-history`):**
- Tarama sonuçlarını zaman damgalı geçmiş dosyasında saklar, sağlık skoru trendini (`improving` / `stable` / `regressing`) hesaplar ve iki JSON rapor arasındaki yeni eklenen regresyonlar ile çözülen sorunları kıyaslar.
- **🧩 Çoklu Şablon ve Modern Frontend Desteği:**
- Laravel Blade (`.blade.php`), Twig (`.twig`), **Vue SFC (`.vue`)**, **React JSX/TSX (`.jsx`, `.tsx`)**, PHP (`.php`), Latte (`.latte`) ve HTML (`.html`, `.htm`, `.xhtml`) dosyalarını 1:1 satır numarası koruyarak tarar.
- **🩺 Sistem Tanılama (`doctor`) & Kural Rehberi (`explain`):**
- `a11y doctor` ile PHP ortamını, 175 kuralın kayıt tutarlılığını ve opsiyonel bağımlılıkları doğrulayın; `a11y explain <RULE_ID>` ile herhangi bir kuralın W3C bağlantısını, kötü/iyi kod örneklerini ve otomatik onarım durumunu görün.
- **⚡ Tek Geçişli Kural Motoru, Artımlı Önbellek (`--cache`) ve Profilleme (`--profile`):**
- DOM ağacını tek geçişte tarar; içerik özeti tabanlı önbellek (`ScanCache`) ile değişmeyen dosyaları atlar ve `--profile` ile en yavaş çalışan kuralların milisaniye bazında istatistiklerini raporlar.
- **🧪 PHPUnit Erişilebilirlik Doğrulama Trait'i (`AccessibilityAssertions`):**
- Laravel, Symfony ve PHP test sınıflarınıza `use AccessibilityAssertions;` ekleyerek `$this->assertHtmlAccessible($html)` ve `$this->assertMeetsAccessibilityPreset($html, 'wcag22-aa')` kontrollerini doğrudan yazın.
- **🛠️ Otomatik CI/CD Pipeline Üretici (`init --ci=...`):**
- GitHub Actions, GitLab CI, Azure Pipelines ve Bitbucket Pipelines için hazır erişilebilirlik iş akışı dosyaları üretir.
- **🤖 Gelişmiş Çevrimdışı & Yapay Zeka Otomatik Onarım (`fix`):**
- **32+ deterministik çevrimdışı (offline) kural onarımı** (API anahtarı gerekmeden) ve karmaşık şablonlar için **Google Gemini AI** desteği.
- **🔌 Zengin Çıktı, Rapor ve Bildirim Ekosistemi:**
- Çıktı formatları: `console`, `json`, `github`, `gitlab`, `sarif` (OASIS SARIF 2.1.0), `junit`, `checkstyle`, `markdown`, `csv`, `xml`.
- Dosya dışa aktarımları: HTML Dashboard (`.html`), PDF (`.pdf`), Excel (`.xlsx`), VPAT 2.5 (`.md`, `.html`, `.json`), SARIF (`.sarif`), JUnit/Checkstyle (`.xml`), SVG Rozet (`--badge`).
- Bildirimler: **Slack**, **Discord**, **Microsoft Teams** ve **HMAC-SHA256 imzalı genel JSON Webhook** (`--webhook-url`).
- **🏆 PHPStan Level 9 & Tam Test Kapsamı:** Kod tabanı en üst seviye PHPStan Level 9 statik tip analizi (0 hata) ile doğrulanmıştır.
---
## 📦 Kurulum
Composer ile projenize dahil edin:
Composer ile projenize geliştirme bağımlılığı olarak ekleyin:
```bash
composer require yaknet/accessibility-console
composer require --dev yaknet/accessibility-console
```
---
## 🚀 CLI Kullanımı
## 🚀 Komut Satırı (CLI) Kullanımı
### 1. Yapılandırma Dosyası Oluşturma (`init`)
Projenizin kök dizininde varsayılan bir `a11y.yaml` konfigürasyon dosyası oluşturur:
YakNet Accessibility Console **10 komut** sunar: `scan`, `fix`, `vpat`, `compare`, `rules`, `explain`, `presets`, `doctor`, `watch`, `init`.
### 1. Yapılandırma Oluşturma (`init`) ve Sistem Kontrolü (`doctor`)
```bash
# Kapsamlı varsayılan a11y.yaml dosyası oluşturur
bin/a11y init
# Ortam, 175 kural bütünlüğü ve entegrasyon durumunu doğrular
bin/a11y doctor
```
### 2. Projeyi Tarama (`scan` / `analyse`)
`a11y.yaml` dosyasındaki kurallara ve dizinlere göre tüm projeyi tarar:
### 2. Proje, Şablon veya Canlı URL Tarama (`scan`)
```bash
# a11y.yaml yapılandırmasına göre projeyi tara
bin/a11y scan
```
Belirli bir dizini veya dosyayı hedef göstermek için:
```bash
# Belirli bir dizini (Blade, Twig, Vue, JSX/TSX, HTML) tara
bin/a11y scan resources/views
```
URL veya tek bir yerel HTML dosyasını taramak için (crawler desteğiyle):
```bash
bin/a11y scan https://test-siteniz.com --crawl
bin/a11y scan src/components
# Mevzuat / sektör ön ayarıyla tara ve VPAT 2.5 + SVG rozet üret
bin/a11y scan resources/views --preset=wcag22-aa --vpat=reports/vpat-2.5.md --badge=public/a11y.svg
# Performans profillemesi ve geçmiş kaydıyla tara
bin/a11y scan resources/views --profile --save-history=.a11y-history.json
# Canlı bir web sitesini crawler ve opsiyonel Headless Chrome ile tara
bin/a11y scan https://ornek.org --crawl --depth=3 --max-pages=25
```
### 3. Baseline Yönetimi
Projeye ait mevcut tüm hataları `a11y-baseline.json` dosyasına kaydederek sonraki taramalarda yok sayılmasını sağlar:
### 3. VPAT 2.5 Uyumluluk Raporu Üretme (`vpat`)
```bash
bin/a11y scan --generate-baseline
# Markdown formatında VPAT 2.5 raporu üret
bin/a11y vpat resources/views --product="Açık Portal" --product-version="2.4.0" --output=VPAT-2.5.md
# Bağımsız HTML veya JSON VPAT 2.5 raporu üret
bin/a11y vpat resources/views --format=html --output=reports/vpat.html
bin/a11y vpat resources/views --format=json --output=reports/vpat.json
```
### 4. Format ve Raporlama Seçenekleri
Hataları GitHub Actions formatında yazdırmak için:
### 4. Regresyon Karşılaştırması (`compare`)
PR veya sürüm öncesi iki tarama raporunu kıyaslayıp yeni eklenen ihlallerde derlemeyi durdurun:
```bash
bin/a11y scan --format=github
```
HTML Raporu kaydetmek için:
```bash
bin/a11y scan --report=report.html
bin/a11y compare reports/before.json reports/after.json --fail-on-regression
```
### 5. AI Destekli Otomatik Düzeltme (`fix`)
Tespit edilen tüm hataları yapay zekaya analiz ettirip dosyalarınızı otomatik olarak tamir ettirin:
```bash
bin/a11y fix
```
Sadece neyin değişeceğini görmek için (`--dry-run`):
```bash
bin/a11y fix --dry-run
```
### 6. Kuralları Listeleme (`rules`)
Mevcut tüm WCAG kurallarını seviyeleri ve açıklamalarıyla birlikte listeler:
### 5. Kuralları Keşfetme (`rules`), Açıklama (`explain`) ve Ön Ayarlar (`presets`)
```bash
# Tüm 175 kuralı listele
bin/a11y rules
# POUR ilkesine, seviyeye veya çevrimdışı onarım desteğine göre filtrele
bin/a11y rules --principle=Operable --standard=AA
bin/a11y rules --healable
# Belirli bir kuralın W3C rehberini ve kod örneklerini incele
bin/a11y explain WCAG_4_1_2_ARIA_TABLIST
# Tüm 11 mevzuat ve sektörel ön ayarı listele
bin/a11y presets
```
### 6. CI/CD Çıktı Formatları, Raporlar ve Bildirimler
```bash
bin/a11y scan --format=sarif --report=a11y.sarif
bin/a11y scan --format=checkstyle --report=a11y.checkstyle
bin/a11y scan --format=junit --report=a11y.xml
bin/a11y scan --report=rapor.html
bin/a11y scan --report=rapor.pdf
bin/a11y scan --report=rapor.xlsx
# Slack, Discord, Microsoft Teams veya genel webhook bildirimleri
bin/a11y scan --webhook-slack="$SLACK_WEBHOOK" --webhook-teams="$TEAMS_WEBHOOK"
```
### 7. Otomatik Onarım (`fix`) ve Canlı İzleme (`watch`)
```bash
# Çevrimdışı (API anahtarsız) deterministik onarım önizleme & uygulama
bin/a11y fix --offline --dry-run
bin/a11y fix --offline
# Gemini AI destekli onarım
bin/a11y fix
# Dosya değişikliklerini canlı izleme
bin/a11y watch resources/views
```
---
## ⚙️ Yapılandırma (`a11y.yaml`)
## 🏛️ Mevzuat ve Sektörel Ön Ayarlar (Presets)
Projenizi özelleştirmek için `a11y.yaml` dosyasını kullanabilirsiniz:
| Ön Ayar (`--preset`) | Seviye | Kapsam |
| :--- | :---: | :--- |
| `wcag22-aa` | 4 | W3C WCAG 2.2 Level A & AA tam uyumluluk profili |
| `wcag22-aaa` | 5 | En katı W3C WCAG 2.2 Level AAA profili (tüm 175 kural) |
| `en301549` | 4 | Avrupa Birliği EN 301 549 kamu dijital erişilebilirlik standardı |
| `eaa2025` | 4 | European Accessibility Act (Direktif EU 2019/882) dijital hizmet profili |
| `section508` | 3 | ABD Revised Section 508 erişilebilirlik profili |
| `bitv2` | 5 | Almanya BITV 2.0 kamu erişilebilirlik standardı |
| `government` | 5 | Kamu portalları ve e-Devlet hizmetleri profili |
| `healthcare` | 5 | Sağlık ve hasta portalları profili (okunabilirlik ve hareket güvenliği odaklı) |
| `banking` | 4 | Dijital bankacılık ve finansal hizmetler profili |
| `education` | 4 | Üniversite, LMS ve akademik portallar (ADA Title II uyumlu) |
| `ecommerce` | 4 | E-Ticaret mağaza ve ödeme akışları profili |
---
## ⚙️ Yapılandırma (`a11y.yaml`) ve Politika Motoru
```yaml
# Tarama yapılacak dizin veya dosyalar
paths:
- resources/views
- public/templates
- src/components
# Hariç tutulacak dizinler
exclude_paths:
- vendor
- node_modules
- storage
- tests
# WCAG seviyesi (1-9, varsayılan 4)
level: 4
# Varsayılan çıktı formatı (console, json, github)
preset: wcag22-aa
format: console
# Baseline dosyası yolu
baseline: a11y-baseline.json
# Kural özelleştirmeleri
extensions:
- php
- html
- twig
- blade.php
- vue
- jsx
- tsx
# Organizasyon geneli yönetişim politikaları
policy:
min_score: 90
max_critical: 0
max_errors: 0
max_warnings: 10
required_standards:
- A
banned_rules:
- WCAG_1_1_1_ALT
- WCAG_2_3_1_FLASHING_CONTENT
severity_overrides:
WCAG_2_5_8_TARGET_SIZE: error
principle_limits:
Perceivable: 0
notifications:
slack_webhook: ""
discord_webhook: ""
teams_webhook: ""
webhook_url: ""
webhook_secret: ""
rules:
exclude:
- WCAG_1_3_1_FIELDSET # Bu kuralı çalıştırma
- WCAG_1_3_1_FIELDSET
include:
- App\Rules\CustomAccessibilityRule # Özel kural ekle
- App\Rules\CustomAccessibilityRule
```
---
## 🔐 Yapay Zeka API Anahtarı
## 🔇 Satır İçi Gizleme Yönergeleri (Inline Suppressions)
AI düzeltme ve öneri özelliklerini kullanabilmek için projenizin kök dizininde bir `.env` dosyası oluşturup **Google Gemini API** anahtarınızı eklemeniz gerekir:
İstisnai durumlarda belirli satır veya bloklarda kuralı gerekçesiyle birlikte gizleyebilirsiniz; tüm gizlemeler denetim kaydına alınır:
```env
GEMINI_API_KEY=AIzaSyA...your_key_here
```html
<!-- a11y-disable-next-line WCAG_1_1_1_ALT -- Dekoratif arka plan görseli -->
<img src="pattern.svg">
<!-- a11y-disable WCAG_1_4_8_TEXT_JUSTIFY -- Matbu belge önizleme bloğu -->
<p style="text-align: justify;">Resmi belge metni...</p>
<!-- a11y-enable WCAG_1_4_8_TEXT_JUSTIFY -->
```
---
## 🧩 PHP Programatik API
```php
// 1. Hızlı tarama ve skor hesaplama
$violations = a11y_scan($html, level: 4);
$score = a11y_score($html, level: 4);
// 2. Mevzuat ön ayarıyla tarama
$govViolations = a11y_scan_preset($html, 'government');
// 3. VPAT 2.5 raporu ve POUR uyumluluk matrisi üretme
$vpatMarkdown = a11y_vpat($html, format: 'markdown', productName: 'YakNet Portal');
$matrix = a11y_compliance_matrix($html, level: 5);
// 4. Çevrimdışı deterministik hızlı onarım
$fixedHtml = a11y_quick_fix($html);
```
---
## 🧪 Geliştirme ve Test
```bash
# Tüm PHPUnit testlerini çalıştır
vendor/bin/phpunit
# PHPStan Level 9 statik tip analizini çalıştır
vendor/bin/phpstan analyse -l 9 src/
```
---
## 🤝 Katkıda Bulunma
Bu proje açık kaynaklıdır ve katkılarınıza açıktır. Lütfen hata bildirimleri için `Issue` açmaktan veya yeni özellikler için `Pull Request` göndermekten çekinmeyin.
Bu proje açık kaynaklıdır ve her türlü katkıya açıktır:
1. Depoyu forklayın (`fork`).
2. Yeni bir özellik dalı açın (`git checkout -b feature/yeni-kural`).
3. Değişikliklerinizi ve testlerinizi ekleyin (`vendor/bin/phpunit` ve `vendor/bin/phpstan analyse -l 9 src/` ile doğrulayın).
4. Bir **Pull Request** açın.
---
## 📜 Lisans
Bu yazılım **YakNet Bilişim** tarafından geliştirilmiştir ve **MIT Lisansı** altında lisanslanmıştır. Detaylar için [LICENSE](LICENSE) dosyasına göz atabilirsiniz.
Bu proje **YakNet** tarafından geliştirilmiştir ve **MIT Lisansı** altında lisanslanmıştır. Detaylar için [LICENSE](LICENSE) dosyasına göz atabilirsiniz.
+19
View File
@@ -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.
+18 -6
View File
@@ -12,18 +12,30 @@ if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
use Symfony\Component\Console\Application;
use YakNet\AccessibilityConsole\Core\Container\ContainerFactory;
use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\CompareCommand;
use YakNet\AccessibilityConsole\Console\Command\DoctorCommand;
use YakNet\AccessibilityConsole\Console\Command\ExplainCommand;
use YakNet\AccessibilityConsole\Console\Command\FixCommand;
use YakNet\AccessibilityConsole\Console\Command\InitCommand;
use YakNet\AccessibilityConsole\Console\Command\PresetsCommand;
use YakNet\AccessibilityConsole\Console\Command\RulesCommand;
use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\VpatCommand;
use YakNet\AccessibilityConsole\Console\Command\WatchCommand;
$container = ContainerFactory::create();
$application = new Application('YakNet Accessibility Console', '3.1.0');
$application = new Application('YakNet Accessibility Console', '4.0.0');
// Add commands resolved via DI Container
$application->add($container->get(ScanCommand::class));
$application->add($container->get(FixCommand::class));
$application->add($container->get(InitCommand::class));
$application->add($container->get(RulesCommand::class));
$application->addCommand($container->get(ScanCommand::class));
$application->addCommand($container->get(FixCommand::class));
$application->addCommand($container->get(InitCommand::class));
$application->addCommand($container->get(RulesCommand::class));
$application->addCommand($container->get(WatchCommand::class));
$application->addCommand($container->get(VpatCommand::class));
$application->addCommand($container->get(CompareCommand::class));
$application->addCommand($container->get(DoctorCommand::class));
$application->addCommand($container->get(ExplainCommand::class));
$application->addCommand($container->get(PresetsCommand::class));
$application->run();
+22 -12
View File
@@ -1,25 +1,31 @@
{
"name": "yaknet/accessibility-console",
"description": "A professional AI-powered WCAG 2.1 accessibility scanner with self-healing capabilities.",
"description": "An open-source, comprehensive WCAG 2.1/2.2 & WAI-ARIA 1.2 accessibility analysis, VPAT 2.5 reporting, policy governance, and self-healing platform by YakNet.",
"keywords": [
"accessibility",
"wcag",
"wcag22",
"wai-aria",
"vpat",
"en301549",
"section508",
"a11y",
"scanner",
"linter",
"static-analysis",
"ai",
"gemini",
"self-healing",
"yaknet"
],
"homepage": "https://forum.yak.net.tr",
"version": "3.1.1",
"version": "4.0.0",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "YakNet Bilişim",
"name": "YakNet",
"email": "[email protected]",
"role": "Developer"
"role": "Organization"
}
],
"require": {
@@ -27,23 +33,27 @@
"ext-dom": "*",
"ext-libxml": "*",
"ext-mbstring": "*",
"symfony/console": "^6.4|^7.0|^8.0",
"symfony/yaml": "^6.4|^7.0|^8.0",
"symfony/console": "^6.4 || ^7.0 || ^8.0",
"symfony/yaml": "^6.4 || ^7.0 || ^8.0",
"monolog/monolog": "^3.0",
"vlucas/phpdotenv": "^5.6",
"google-gemini-php/client": "^1.0|^2.0",
"google-gemini-php/client": "^1.0 || ^2.0",
"guzzlehttp/guzzle": "^7.8",
"masterminds/html5": "^2.8",
"sabberworm/php-css-parser": "^9.4",
"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": "^8.1",
"symfony/dom-crawler": "^8.1"
"symfony/css-selector": "^6.4 || ^7.0 || ^8.0",
"symfony/dom-crawler": "^6.4 || ^7.0 || ^8.0",
"spatie/color": "^1.5 || ^2.0",
"intervention/image": "^2.7 || ^3.0",
"dompdf/dompdf": "^2.0 || ^3.0",
"phpoffice/phpspreadsheet": "^1.28 || ^2.0 || ^3.0"
},
"require-dev": {
"phpunit/phpunit": "^10.5",
"phpstan/phpstan": "^1.10"
"phpstan/phpstan": "^2.2"
},
"autoload": {
"files": [
+103
View File
@@ -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>
+23
View File
@@ -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);
}
}
+31
View File
@@ -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.
+25
View File
@@ -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).
+3
View File
@@ -2,3 +2,6 @@ parameters:
level: 9
paths:
- src
bootstrapFiles:
- vendor/autoload.php
+12 -5
View File
@@ -44,11 +44,18 @@ EXPLANATION: [A short explanation of what you fixed and why]
FIX: [Only the corrected HTML snippet]
PROMPT;
try {
$result = $this->client->generativeModel('gemini-3.1-flash-lite')->generateContent($prompt);
return trim($result->text());
} catch (\Throwable $e) {
return "AI Düzeltme Hatası: " . $e->getMessage();
$models = ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-1.5-pro', 'gemini-1.5-flash'];
$lastError = null;
foreach ($models as $model) {
try {
$result = $this->client->generativeModel($model)->generateContent($prompt);
return trim($result->text());
} catch (\Throwable $e) {
$lastError = $e;
}
}
return "AI Düzeltme Hatası: " . $lastError->getMessage();
}
}
+5 -1
View File
@@ -51,7 +51,11 @@ class ClaudeProvider implements AiProviderInterface
]);
$data = json_decode($response->getBody()->getContents(), true);
if (is_array($data) && isset($data['content'][0]['text']) && is_string($data['content'][0]['text'])) {
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;
+12 -5
View File
@@ -35,11 +35,18 @@ class GeminiProvider implements AiProviderInterface
$prompt = PromptBuilder::build($violation);
try {
$result = $this->client->generativeModel('gemini-3.1-flash-lite')->generateContent($prompt);
return trim($result->text());
} catch (\Throwable $e) {
return "Gemini Error: " . $e->getMessage();
$models = ['gemini-2.5-pro', 'gemini-2.5-flash', 'gemini-1.5-pro', 'gemini-1.5-flash'];
$lastError = null;
foreach ($models as $model) {
try {
$result = $this->client->generativeModel($model)->generateContent($prompt);
return trim($result->text());
} catch (\Throwable $e) {
$lastError = $e;
}
}
return "Gemini Error: " . $lastError->getMessage();
}
}
+6 -1
View File
@@ -50,7 +50,12 @@ class OpenAiProvider implements AiProviderInterface
]);
$data = json_decode($response->getBody()->getContents(), true);
if (is_array($data) && isset($data['choices'][0]['message']['content']) && is_string($data['choices'][0]['message']['content'])) {
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;
+49
View File
@@ -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,
];
}
}
+245
View File
@@ -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);
}
}
+42
View File
@@ -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,
];
}
}
+76
View File
@@ -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,
];
}
}
+49
View File
@@ -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,
];
}
}
+105
View File
@@ -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;
}
}
+27
View File
@@ -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,
) {
}
}
+53
View File
@@ -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,
];
}
}
+184
View File
@@ -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;
}
}
+189
View File
@@ -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))
);
}
}
+381
View File
@@ -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 &amp; 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']} &nbsp;|&nbsp;
<strong>Partially Supports:</strong> {$data['summary']['partially_supports']} &nbsp;|&nbsp;
<strong>Does Not Support:</strong> {$data['summary']['does_not_support']} &nbsp;|&nbsp;
<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',
};
}
}
+124
View File
@@ -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;
}
}
+113
View File
@@ -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;
}
}
+106
View File
@@ -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;
}
}
+23 -15
View File
@@ -26,6 +26,7 @@ class FixCommand extends Command
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to the configuration file (default: a11y.yaml)')
->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping (URL scans only)')
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Show what would be fixed without modifying files')
->addOption('offline', null, InputOption::VALUE_NONE, 'Perform deterministic offline rule-based fixes without calling AI')
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-9)')
->addOption('js', null, InputOption::VALUE_NONE, 'Enable JavaScript rendering using Headless Chrome (URL scans only)');
}
@@ -39,10 +40,11 @@ class FixCommand extends Command
$configPath = is_string($configPathOption) ? $configPathOption : getcwd() . '/a11y.yaml';
$config = Config::fromYaml($configPath);
$offline = (bool)$input->getOption('offline');
$apiKey = $config->getGeminiApiKey();
if (!$apiKey) {
$io->error("GEMINI_API_KEY not found in .env or environment variables. AI fixing requires an API key.");
return Command::FAILURE;
if (!$offline && !$apiKey) {
$io->note("GEMINI_API_KEY not found in .env or environment variables. Running in offline rule-based healing mode (--offline).");
$offline = true;
}
$levelOption = $input->getOption('level');
@@ -53,11 +55,11 @@ class FixCommand extends Command
// If target is a URL, run the legacy URL fixing logic
if ($isUrl) {
return $this->executeUrlFix($target, $level, $apiKey, $input, $output, $io);
return $this->executeUrlFix($target, $level, $apiKey, $input, $output, $io, $offline);
}
// --- LOCAL FILE / DIRECTORY SELF-HEALING ENGINE ---
$io->title("AI Self-Healing Mode - Directory Static Analysis");
$io->title($offline ? "Offline Rule-Based Self-Healing Mode" : "AI Self-Healing Mode - Directory Static Analysis");
$io->writeln("<fg=gray>Configuration loaded from:</> <fg=cyan>$configPath</>");
$dryRun = (bool)$input->getOption('dry-run');
@@ -87,9 +89,9 @@ class FixCommand extends Command
return Command::SUCCESS;
}
$io->note(sprintf("Found %d violations. Starting AI analysis and healing...", count($violations)));
$io->note(sprintf("Found %d violations. Starting %s analysis and healing...", count($violations), $offline ? 'offline rule-based' : 'AI'));
$fixer = new AiFixerManager($apiKey);
$fixer = !$offline ? new AiFixerManager($apiKey) : null;
$diffGenerator = new \YakNet\AccessibilityConsole\Core\Diff\VisualDiffGenerator();
$fixedCount = 0;
@@ -129,9 +131,12 @@ class FixCommand extends Command
if ($rawSuggestion !== null) {
$isLocalFix = true;
} else {
} 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;
@@ -146,7 +151,7 @@ class FixCommand extends Command
continue;
}
if (is_string($rawSuggestion) && $suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
if ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
$io->writeln("<fg=red>Skipped (AI could not generate a clean fix)</>");
continue;
}
@@ -189,7 +194,7 @@ class FixCommand extends Command
/**
* Legacy URL scan and fix logic
*/
private function executeUrlFix(string $target, int $level, string $apiKey, InputInterface $input, OutputInterface $output, SymfonyStyle $io): int
private function executeUrlFix(string $target, int $level, ?string $apiKey, InputInterface $input, OutputInterface $output, SymfonyStyle $io, bool $offline = false): int
{
$projectPathOption = $input->getOption('project-path');
$projectPath = is_string($projectPathOption) ? $projectPathOption : getcwd();
@@ -199,7 +204,7 @@ class FixCommand extends Command
$dryRun = (bool)$input->getOption('dry-run');
$useJs = (bool)$input->getOption('js');
$io->title("AI Self-Healing Mode - Fixing URL: $target");
$io->title($offline ? "Offline Rule-Based Mode - Fixing URL: $target" : "AI Self-Healing Mode - Fixing URL: $target");
// Fetch HTML
if ($useJs) {
@@ -231,9 +236,9 @@ class FixCommand extends Command
return Command::SUCCESS;
}
$io->note("Found " . count($violations) . " violations. Starting AI analysis...");
$io->note(sprintf("Found %d violations. Starting %s analysis...", count($violations), $offline ? 'offline' : 'AI'));
$fixer = new AiFixerManager($apiKey);
$fixer = (!$offline && is_string($apiKey) && $apiKey !== '') ? new AiFixerManager($apiKey) : null;
$diffGenerator = new \YakNet\AccessibilityConsole\Core\Diff\VisualDiffGenerator();
$locator = new SourceLocator($projectPath);
$fixedCount = 0;
@@ -254,8 +259,11 @@ class FixCommand extends Command
if ($rawSuggestion !== null) {
$isLocalFix = true;
} else {
} elseif ($fixer !== null) {
$rawSuggestion = $fixer->suggestFix($violation);
} else {
$io->writeln("<fg=yellow>Skipped (Rule requires AI or manual intervention)</>");
continue;
}
$suggestion = $rawSuggestion;
@@ -270,7 +278,7 @@ class FixCommand extends Command
continue;
}
if (is_string($rawSuggestion) && $suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
if ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
$io->writeln("<fg=red>Skipped (AI could not generate a clean fix)</>");
continue;
}
+69 -3
View File
@@ -4,8 +4,10 @@ namespace YakNet\AccessibilityConsole\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\CI\CiWorkflowGenerator;
class InitCommand extends Command
{
@@ -13,12 +15,36 @@ class InitCommand extends Command
{
$this
->setName('init')
->setDescription('Initialize a default a11y.yaml configuration file');
->setDescription('Initialize a default a11y.yaml configuration file and optional CI/CD workflow')
->addOption('ci', null, InputOption::VALUE_REQUIRED, 'Generate CI/CD workflow template (github, gitlab, azure, bitbucket)')
->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Default compliance preset for generated CI workflow', 'wcag22-aa');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
// Optional CI/CD pipeline workflow scaffolding
$ciOption = $input->getOption('ci');
if (is_string($ciOption) && $ciOption !== '') {
$preset = is_string($input->getOption('preset')) ? $input->getOption('preset') : 'wcag22-aa';
try {
$generator = new CiWorkflowGenerator();
$yaml = $generator->generate($ciOption, $preset);
$relPath = CiWorkflowGenerator::getDefaultPath($ciOption);
$fullPath = getcwd() . '/' . $relPath;
$dir = dirname($fullPath);
if (!is_dir($dir)) {
@mkdir($dir, 0775, true);
}
file_put_contents($fullPath, $yaml);
$io->success("Generated CI/CD workflow ({$ciOption}) at: {$relPath}");
} catch (\InvalidArgumentException $e) {
$io->error($e->getMessage());
return Command::FAILURE;
}
}
$configPath = getcwd() . '/a11y.yaml';
if (file_exists($configPath)) {
@@ -42,15 +68,55 @@ exclude_paths:
- storage
- .git
# Accessibility scanning level (1-9, default 4)
# Accessibility scanning level (1-5, default 4)
level: 4
# Output format (console, json, html, github)
# Optional regulatory or sectoral compliance preset
# Available: section508, en301549, eaa2025, bitv2, wcag22-aa, wcag22-aaa,
# government, healthcare, banking, education, ecommerce
# preset: wcag22-aa
# Output format (console, json, github, gitlab, sarif, junit, checkstyle, markdown, csv, xml)
format: console
# File extensions to analyse (Blade, Twig, Vue, JSX/TSX, PHP, HTML)
extensions:
- php
- html
- htm
- twig
- blade.php
- vue
- jsx
- tsx
# Path to the baseline file for ignoring existing violations
# baseline: a11y-baseline.json
# Governance policy thresholds (enforced automatically during `a11y scan`)
# policy:
# min_score: 90
# max_critical: 0
# max_errors: 0
# max_warnings: 10
# required_standards:
# - A
# banned_rules:
# - WCAG_1_1_1_ALT
# - WCAG_2_3_1_FLASHING_CONTENT
# severity_overrides:
# WCAG_2_5_8_TARGET_SIZE: error
# principle_limits:
# Perceivable: 0
# Optional CI/CD webhook notifications
# notifications:
# slack_webhook: ""
# discord_webhook: ""
# teams_webhook: ""
# webhook_url: ""
# webhook_secret: ""
# Rule adjustments
rules:
# Rules to exclude from analysis
+49
View File
@@ -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;
}
}
+76 -6
View File
@@ -7,15 +7,24 @@ use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\SelfHealing\LocalHealer;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
use Symfony\Component\Console\Input\InputOption;
class RulesCommand extends Command
{
protected function configure(): void
{
$this
->setName('rules')
->setDescription('List all available accessibility scanning rules');
->setDescription('List all available accessibility scanning rules')
->addOption('search', 's', InputOption::VALUE_REQUIRED, 'Search rules by ID or description')
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Filter rules by maximum level (1-5)')
->addOption('standard', null, InputOption::VALUE_REQUIRED, 'Filter rules by standard (A, AA, AAA)')
->addOption('severity', null, InputOption::VALUE_REQUIRED, 'Filter rules by severity (critical, error, warning, info)')
->addOption('principle', null, InputOption::VALUE_REQUIRED, 'Filter rules by POUR principle (Perceivable, Operable, Understandable, Robust)')
->addOption('healable', null, InputOption::VALUE_NONE, 'Show only rules with deterministic offline auto-fix support');
}
protected function execute(InputInterface $input, OutputInterface $output): int
@@ -23,19 +32,71 @@ class RulesCommand extends Command
$io = new SymfonyStyle($input, $output);
$io->title("Accessibility Console - Available Rules");
$searchQuery = $input->getOption('search');
$levelFilter = $input->getOption('level');
$standardFilter = $input->getOption('standard');
$severityFilter = $input->getOption('severity');
$principleFilter = $input->getOption('principle');
$healableOnly = (bool)$input->getOption('healable');
$healableIds = LocalHealer::getSupportedRuleIds();
$maxLevel = is_numeric($levelFilter) ? (int)$levelFilter : 9;
$rules = RuleLevels::getRulesForLevel($maxLevel);
$table = new Table($output);
$table->setHeaders(['Rule ID', 'Standard', 'Severity', 'Level', 'Description']);
$rules = RuleLevels::getRulesForLevel(9);
$matchedCount = 0;
foreach ($rules as $rule) {
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
: (new \ReflectionClass($rule))->getShortName();
$ruleId = $rule->getId();
$description = method_exists($rule, 'getDescription') ? $rule->getDescription() : '';
$standard = method_exists($rule, 'getStandard') ? $rule->getStandard()->value : '';
$severity = method_exists($rule, 'getSeverity') ? $rule->getSeverity()->value : '';
$level = method_exists($rule, 'getLevel') ? $rule->getLevel() : 4;
// Search filter
if (is_string($searchQuery) && $searchQuery !== '') {
$query = strtolower($searchQuery);
if (!str_contains(strtolower($ruleId), $query) && !str_contains(strtolower($description), $query)) {
continue;
}
}
// Standard filter
if (is_string($standardFilter) && $standardFilter !== '') {
if (strcasecmp($standard, $standardFilter) !== 0) {
continue;
}
}
// Severity filter
if (is_string($severityFilter) && $severityFilter !== '') {
if (strcasecmp($severity, $severityFilter) !== 0) {
continue;
}
}
// Principle filter
if (is_string($principleFilter) && $principleFilter !== '') {
$rulePrinciple = 'Robust';
if (preg_match('/WCAG_([1-4])_/', $ruleId, $m)) {
$rulePrinciple = match ((int)$m[1]) {
1 => 'Perceivable',
2 => 'Operable',
3 => 'Understandable',
default => 'Robust',
};
}
if (strcasecmp($rulePrinciple, $principleFilter) !== 0) {
continue;
}
}
// Healable filter
if ($healableOnly && !in_array($ruleId, $healableIds, true)) {
continue;
}
$table->addRow([
"<fg=cyan;options=bold>$ruleId</>",
@@ -44,11 +105,20 @@ class RulesCommand extends Command
$level,
$description
]);
$matchedCount++;
}
$table->render();
$io->newLine();
$io->note("Total rules available: " . count($rules));
$hasFilter = is_string($searchQuery) || $levelFilter !== null || is_string($standardFilter)
|| is_string($severityFilter) || is_string($principleFilter) || $healableOnly;
if ($hasFilter) {
$io->note(sprintf("Showing %d matching rules (out of %d total rules).", $matchedCount, count(RuleLevels::getRulesForLevel(9))));
} else {
$io->note("Total rules available: " . count($rules));
}
return Command::SUCCESS;
}
+382 -44
View File
@@ -10,11 +10,24 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\AI\GeminiFixer;
use YakNet\AccessibilityConsole\Analytics\HistoryTracker;
use YakNet\AccessibilityConsole\Cache\ScanCache;
use YakNet\AccessibilityConsole\Compliance\VpatReportGenerator;
use YakNet\AccessibilityConsole\Core\Analyser;
use YakNet\AccessibilityConsole\Core\BaselineManager;
use YakNet\AccessibilityConsole\Core\Config;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Notifications\DiscordNotifier;
use YakNet\AccessibilityConsole\Notifications\GenericWebhookNotifier;
use YakNet\AccessibilityConsole\Notifications\MicrosoftTeamsNotifier;
use YakNet\AccessibilityConsole\Notifications\NotificationDispatcher;
use YakNet\AccessibilityConsole\Notifications\NotificationPayload;
use YakNet\AccessibilityConsole\Notifications\SlackNotifier;
use YakNet\AccessibilityConsole\Policy\PolicyEngine;
use YakNet\AccessibilityConsole\Rules\RuleExecutionStats;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
use YakNet\AccessibilityConsole\Reporting\CheckstyleFormatter;
use YakNet\AccessibilityConsole\Reporting\ConsoleFormatter;
use YakNet\AccessibilityConsole\Reporting\GithubFormatter;
use YakNet\AccessibilityConsole\Reporting\JsonFormatter;
@@ -22,6 +35,12 @@ use YakNet\AccessibilityConsole\Reporting\XmlFormatter;
use YakNet\AccessibilityConsole\Reporting\MarkdownFormatter;
use YakNet\AccessibilityConsole\Reporting\CsvFormatter;
use YakNet\AccessibilityConsole\Reporting\GitLabCodeQualityFormatter;
use YakNet\AccessibilityConsole\Reporting\SarifFormatter;
use YakNet\AccessibilityConsole\Reporting\JunitFormatter;
use YakNet\AccessibilityConsole\Reporting\PdfReportGenerator;
use YakNet\AccessibilityConsole\Reporting\ExcelReportExporter;
use YakNet\AccessibilityConsole\Badges\BadgeGenerator;
use YakNet\AccessibilityConsole\Presets\PresetRegistry;
use YakNet\AccessibilityConsole\Source\SourceLocator;
class ScanCommand extends Command
@@ -35,12 +54,26 @@ class ScanCommand extends Command
->addArgument('target', InputArgument::OPTIONAL, 'The URL, file, or directory path to scan')
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to the configuration file (default: a11y.yaml)')
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-9)')
->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (console, json, github)')
->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Use a compliance preset (section508, en301549, eaa2025, bitv2, wcag22-aa, wcag22-aaa, government, healthcare, banking, education, ecommerce)')
->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (console, json, github, xml, markdown, csv, gitlab, sarif, junit, checkstyle)')
->addOption('min-score', null, InputOption::VALUE_REQUIRED, 'Minimum required accessibility health score (0-100) to pass the quality gate')
->addOption('max-warnings', null, InputOption::VALUE_REQUIRED, 'Maximum allowed warnings before failing the quality gate')
->addOption('fail-on', null, InputOption::VALUE_REQUIRED, 'Minimum severity to fail on (error, warning, info)')
->addOption('generate-baseline', null, InputOption::VALUE_NONE, 'Generate a baseline file containing all current violations')
->addOption('baseline', null, InputOption::VALUE_REQUIRED, 'Path to the baseline file')
->addOption('no-progress', null, InputOption::VALUE_NONE, 'Disable progress bar')
->addOption('ai', null, InputOption::VALUE_NONE, 'Enable AI-powered fix suggestions')
->addOption('report', null, InputOption::VALUE_REQUIRED, 'Save report to file (html or json)')
->addOption('report', null, InputOption::VALUE_REQUIRED, 'Save report to file (html, json, sarif, xml, junit, checkstyle, pdf, xlsx)')
->addOption('vpat', null, InputOption::VALUE_REQUIRED, 'Export a VPAT 2.5 Conformance Report to file (.md, .html, or .json)')
->addOption('save-history', null, InputOption::VALUE_REQUIRED, 'Append scan snapshot to a JSON history file for trend tracking')
->addOption('cache', null, InputOption::VALUE_REQUIRED, 'Path to incremental content-hash cache file (e.g. .a11y-cache.json)')
->addOption('clear-cache', null, InputOption::VALUE_NONE, 'Clear the incremental scan cache before scanning')
->addOption('profile', null, InputOption::VALUE_NONE, 'Display rule execution timing profile (top slowest rules)')
->addOption('webhook-slack', null, InputOption::VALUE_REQUIRED, 'Send scan summary to a Slack Incoming Webhook URL')
->addOption('webhook-discord', null, InputOption::VALUE_REQUIRED, 'Send scan summary to a Discord Webhook URL')
->addOption('webhook-teams', null, InputOption::VALUE_REQUIRED, 'Send scan summary to a Microsoft Teams Webhook URL')
->addOption('webhook-url', null, InputOption::VALUE_REQUIRED, 'Send JSON payload to a generic webhook URL')
->addOption('badge', null, InputOption::VALUE_REQUIRED, 'Save SVG accessibility health badge to file (e.g. a11y-badge.svg)')
->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping (URL scans only)')
->addOption('crawl', null, InputOption::VALUE_NONE, 'Crawl internal links recursively (URL scans only)')
->addOption('depth', null, InputOption::VALUE_REQUIRED, 'Maximum crawling depth (URL scans only)', '3')
@@ -61,6 +94,19 @@ class ScanCommand extends Command
$levelOption = $input->getOption('level');
$level = is_numeric($levelOption) ? (int)$levelOption : $config->getLevel();
$presetOption = $input->getOption('preset');
$presetName = (is_string($presetOption) && $presetOption !== '') ? $presetOption : $config->getPreset();
$activePreset = null;
if (is_string($presetName) && $presetName !== '') {
$presetRegistry = new PresetRegistry();
$activePreset = $presetRegistry->get($presetName);
if ($activePreset !== null) {
$level = $activePreset->getLevel();
} else {
$io->warning("Preset '{$presetName}' not found. Using default rules.");
}
}
$formatOption = $input->getOption('format');
$format = is_string($formatOption) ? $formatOption : $config->getFormat();
@@ -79,9 +125,14 @@ class ScanCommand extends Command
}
// --- LOCAL DIRECTORY / FILE STATIC ANALYSIS ENGINE ---
$io->title("Accessibility Console - Static Analysis");
$io->writeln("<fg=gray>Configuration loaded from:</> <fg=cyan>$configPath</>");
$io->writeln("<fg=gray>Rule Level:</> <fg=yellow>$level</>");
if ($format === 'console') {
$io->title("Accessibility Console - Static Analysis");
$io->writeln("<fg=gray>Configuration loaded from:</> <fg=cyan>$configPath</>");
$io->writeln("<fg=gray>Rule Level:</> <fg=yellow>$level</>");
if ($activePreset !== null) {
$io->writeln("<fg=gray>Compliance Preset:</> <fg=magenta>" . $activePreset->getName() . " (" . $activePreset->getDescription() . ")</>");
}
}
// Resolve paths to scan
$paths = $config->getPaths();
@@ -91,30 +142,53 @@ class ScanCommand extends Command
// Setup Analyser
$scanner = new Scanner();
$enableProfile = (bool)$input->getOption('profile');
$executionStats = $enableProfile ? new RuleExecutionStats() : null;
if ($executionStats !== null) {
$scanner->getEngine()->setStats($executionStats);
}
$rules = RuleLevels::getRulesForLevel($level);
// Filter rules based on config
// Filter rules based on config and active preset
$rulesConfig = $config->getRulesConfig();
$excludedIds = $rulesConfig['exclude'];
if ($activePreset !== null) {
$excludedIds = array_values(array_unique(array_merge($excludedIds, $activePreset->getExcludedRules())));
}
$activeRules = [];
foreach ($rules as $rule) {
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
: (new \ReflectionClass($rule))->getShortName();
$ruleId = $rule->getId();
if (in_array($ruleId, $rulesConfig['exclude'], true)) {
if (in_array($ruleId, $excludedIds, true)) {
continue;
}
$activeRules[$ruleId] = $rule;
}
// Ensure preset-included priority rules are active even if they belong to a higher scan level
if ($activePreset !== null && !empty($activePreset->getIncludedRules())) {
$allRulesById = [];
foreach (RuleLevels::getRulesForLevel(9) as $candidateRule) {
$cid = $candidateRule->getId();
$allRulesById[$cid] = $candidateRule;
}
foreach ($activePreset->getIncludedRules() as $priorityRuleId) {
if (!isset($activeRules[$priorityRuleId]) && isset($allRulesById[$priorityRuleId]) && !in_array($priorityRuleId, $excludedIds, true)) {
$activeRules[$priorityRuleId] = $allRulesById[$priorityRuleId];
}
}
}
foreach ($rulesConfig['include'] as $customRuleClass) {
if (class_exists($customRuleClass)) {
try {
$reflection = new \ReflectionClass($customRuleClass);
if ($reflection->isInstantiable()) {
$rule = $reflection->newInstance();
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
$ruleId = method_exists($rule, 'getId')
? $rule->getId()
: $reflection->getShortName();
$activeRules[$ruleId] = $rule;
}
@@ -132,7 +206,20 @@ class ScanCommand extends Command
$baselineManager->load(getcwd() . '/' . $baselinePath);
}
$analyser = new Analyser($config, $scanner, $baselineManager);
// Setup Incremental Scan Cache (if --cache is passed)
$scanCache = null;
$cachePathOption = $input->getOption('cache');
if (is_string($cachePathOption) && $cachePathOption !== '') {
$rulesSig = hash('sha256', implode('|', array_keys($activeRules)));
$scanCache = new ScanCache($cachePathOption, $rulesSig);
if ($input->getOption('clear-cache')) {
$scanCache->clear();
} else {
$scanCache->load();
}
}
$analyser = new Analyser($config, $scanner, $baselineManager, null, null, null, $scanCache);
// Progress bar setup
$progressBar = null;
@@ -200,6 +287,10 @@ class ScanCommand extends Command
}
}
// Apply governance policy severity overrides before formatting & scoring
$policyEngine = new PolicyEngine($config->getPolicyConfig());
$policyEngine->applySeverityOverrides($violations);
// Select formatter
$formatter = new ConsoleFormatter();
if ($format === 'json') {
@@ -214,40 +305,154 @@ class ScanCommand extends Command
$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') {
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
$io->section("Accessibility Ratings");
$color = $metrics['score'] >= 90 ? 'green' : ($metrics['score'] >= 70 ? 'yellow' : 'red');
$io->writeln(sprintf("Health Score: <fg=%s>%d/100</>", $color, $metrics['score']));
$color = $score >= 90 ? 'green' : ($score >= 70 ? 'yellow' : 'red');
$io->writeln(sprintf("Health Score: <fg=%s>%d/100</>", $color, $score));
$io->writeln(sprintf(" - Screen Reader / Visual Impact: <fg=cyan>%d%%</>", $metrics['visualImpact']));
$io->writeln(sprintf(" - Keyboard / Motor Impact: <fg=cyan>%d%%</>", $metrics['motorImpact']));
$io->writeln(sprintf(" - Cognitive / Distraction Impact: <fg=cyan>%d%%</>", $metrics['cognitiveImpact']));
if (!empty($suppressedLog)) {
$io->writeln(sprintf(" - Inline Suppressed Violations: <fg=yellow>%d</>", count($suppressedLog)));
}
$io->newLine();
}
// Execution profiling summary (--profile)
if ($executionStats !== null && $format === 'console') {
$slowest = $executionStats->getSlowestRules(10);
if (!empty($slowest)) {
$io->section('Rule Execution Profile (Top 10 Slowest)');
$profileTable = new \Symfony\Component\Console\Helper\Table($output);
$profileTable->setHeaders(['Rule ID', 'Invocations', 'Total (ms)', 'Avg (ms)', 'Violations']);
foreach ($slowest as $rId => $stat) {
$profileTable->addRow([
$rId,
(string)$stat['invocations'],
sprintf('%.3f', $stat['total_time_ms']),
sprintf('%.4f', $stat['avg_time_ms']),
(string)$stat['violations'],
]);
}
$profileTable->render();
$io->newLine();
}
}
// Quality Gate & Policy Engine evaluation
$minScoreOption = $input->getOption('min-score');
$maxWarningsOption = $input->getOption('max-warnings');
$failOnOption = $input->getOption('fail-on');
$errorCount = 0;
$warningCount = 0;
foreach ($violations as $v) {
if ($v->severity === Severity::CRITICAL || $v->severity === Severity::ERROR) {
$errorCount++;
} elseif ($v->severity === Severity::WARNING) {
$warningCount++;
}
}
$qualityGateFailed = false;
/** @var string[] $gateFailures */
$gateFailures = [];
if ($policyEngine->hasPolicies()) {
$policyResult = $policyEngine->evaluate($violations);
if (!$policyResult->passed) {
$qualityGateFailed = true;
$gateFailures = array_merge($gateFailures, $policyResult->failures);
}
}
if ($minScoreOption !== null && is_numeric($minScoreOption)) {
$minScore = (int)$minScoreOption;
if ($score < $minScore) {
$qualityGateFailed = true;
$gateFailures[] = sprintf("Accessibility score (%d/100) is lower than the minimum required threshold of %d/100.", $score, $minScore);
}
}
if ($maxWarningsOption !== null && is_numeric($maxWarningsOption)) {
$maxWarnings = (int)$maxWarningsOption;
if ($warningCount > $maxWarnings) {
$qualityGateFailed = true;
$gateFailures[] = sprintf("Warning count (%d) exceeds the maximum allowed limit of %d.", $warningCount, $maxWarnings);
}
}
if (is_string($failOnOption)) {
$failOn = strtolower($failOnOption);
if ($failOn === 'error') {
$exitCode = ($errorCount > 0) ? Command::FAILURE : Command::SUCCESS;
} elseif ($failOn === 'warning') {
$exitCode = ($errorCount > 0 || $warningCount > 0) ? Command::FAILURE : Command::SUCCESS;
}
}
if ($qualityGateFailed) {
$io->newLine();
$io->error("CI/CD Quality Gate Failed:\n- " . implode("\n- ", $gateFailures));
$exitCode = Command::FAILURE;
}
// Export report if --report is specified
$reportPath = $input->getOption('report');
if (is_string($reportPath) && $reportPath !== '') {
$extension = pathinfo($reportPath, PATHINFO_EXTENSION);
if ($extension === 'json') {
$serialized = [];
foreach ($violations as $v) {
$serialized[] = $v->toArray();
}
file_put_contents($reportPath, json_encode($serialized, JSON_PRETTY_PRINT));
} else {
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
// Map violations into page format
$mappedViolations = ['Static Analysis' => $violations];
file_put_contents($reportPath, $reporter->render($mappedViolations, 'Static Analysis'));
}
$io->success("Report saved to: $reportPath");
$this->exportReport($reportPath, $violations, 'Static Analysis', $io);
}
// Export VPAT 2.5 report if --vpat is specified
$vpatPath = $input->getOption('vpat');
if (is_string($vpatPath) && $vpatPath !== '') {
$vpatGenerator = new VpatReportGenerator();
$vpatExt = strtolower(pathinfo($vpatPath, PATHINFO_EXTENSION));
$vpatContent = match ($vpatExt) {
'html', 'htm' => $vpatGenerator->renderHtml($violations, basename((string)getcwd()) ?: 'Web Application'),
'json' => $vpatGenerator->renderJson($violations, basename((string)getcwd()) ?: 'Web Application'),
default => $vpatGenerator->renderMarkdown($violations, basename((string)getcwd()) ?: 'Web Application'),
};
file_put_contents($vpatPath, $vpatContent);
$io->success("VPAT 2.5 Conformance Report saved to: $vpatPath");
}
// Save history snapshot if --save-history is specified
$historyPath = $input->getOption('save-history');
if (is_string($historyPath) && $historyPath !== '') {
$tracker = new HistoryTracker();
$tracker->record($violations, $historyPath, implode(', ', $paths), $activePreset?->getName());
$trend = $tracker->computeTrend($tracker->load($historyPath));
if ($format === 'console') {
$deltaStr = $trend['score_delta'] > 0 ? '+' . $trend['score_delta'] : (string)$trend['score_delta'];
$io->note(sprintf('History saved (%d total runs, trend: %s, delta: %s).', $trend['runs'], $trend['trend'], $deltaStr));
}
}
// Export SVG badge if --badge is specified
$badgePath = $input->getOption('badge');
if (is_string($badgePath) && $badgePath !== '') {
file_put_contents($badgePath, BadgeGenerator::generateScoreBadge($score));
$io->success("SVG Badge saved to: $badgePath");
}
// Dispatch webhook notifications (CLI flags or a11y.yaml notifications block)
$this->dispatchNotifications($input, $config, implode(', ', $paths), $score, $violations, $errorCount, $warningCount);
return $exitCode;
}
@@ -302,9 +507,6 @@ class ScanCommand extends Command
while (!empty($queue) && count($visited) < $maxPages) {
$current = array_shift($queue);
if (!is_array($current)) {
continue;
}
$url = $current['url'];
$depth = (int)$current['depth'];
@@ -441,20 +643,156 @@ class ScanCommand extends Command
$reportPath = $input->getOption('report');
if (is_string($reportPath) && $reportPath !== '') {
$extension = pathinfo($reportPath, PATHINFO_EXTENSION);
if ($extension === 'json') {
$serialized = [];
foreach ($results as $url => $violations) {
$serialized[$url] = array_map(fn($v) => $v->toArray(), $violations);
}
file_put_contents($reportPath, json_encode($serialized, JSON_PRETTY_PRINT));
} else {
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
file_put_contents($reportPath, $reporter->render($results, $target));
$allViolations = [];
foreach ($results as $urlViolations) {
$allViolations = array_merge($allViolations, $urlViolations);
}
$io->success("Report saved to: $reportPath");
$this->exportReport($reportPath, $allViolations, $target, $io, $results);
}
return Command::FAILURE;
}
/**
* Export violations to various file formats (HTML, JSON, SARIF, XML/JUnit, PDF, Excel).
*
* @param string $reportPath
* @param \YakNet\AccessibilityConsole\Core\Violation[] $violations
* @param string $targetName
* @param SymfonyStyle $io
* @param array<string, \YakNet\AccessibilityConsole\Core\Violation[]>|null $pageResults
*/
private function exportReport(
string $reportPath,
array $violations,
string $targetName,
SymfonyStyle $io,
?array $pageResults = null
): void {
$extension = strtolower(pathinfo($reportPath, PATHINFO_EXTENSION));
if ($extension === 'json') {
if ($pageResults !== null) {
$serialized = [];
foreach ($pageResults as $url => $pageViolations) {
$serialized[$url] = array_map(fn($v) => $v->toArray(), $pageViolations);
}
} else {
$serialized = [];
foreach ($violations as $v) {
$serialized[] = $v->toArray();
}
}
file_put_contents($reportPath, (string)json_encode($serialized, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
} elseif ($extension === 'sarif') {
$sarifFormatter = new SarifFormatter();
file_put_contents($reportPath, $sarifFormatter->render($violations));
} elseif ($extension === 'checkstyle') {
$checkstyleFormatter = new CheckstyleFormatter();
file_put_contents($reportPath, $checkstyleFormatter->render($violations));
} elseif ($extension === 'xml' || $extension === 'junit') {
$junitFormatter = new JunitFormatter();
file_put_contents($reportPath, $junitFormatter->render($violations));
} elseif ($extension === 'pdf') {
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
$serialized = [];
foreach ($violations as $v) {
$serialized[] = $v->toArray();
}
$scanResult = [
'score' => $metrics['score'],
'violations' => $serialized,
];
file_put_contents($reportPath, PdfReportGenerator::generatePdf($scanResult, $targetName));
} elseif ($extension === 'xlsx' || $extension === 'xls') {
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
$serialized = [];
foreach ($violations as $v) {
$serialized[] = $v->toArray();
}
$scanResult = [
'score' => $metrics['score'],
'violations' => $serialized,
];
file_put_contents($reportPath, ExcelReportExporter::exportExcel($scanResult, $targetName));
} else {
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
$mapped = $pageResults ?? [$targetName => $violations];
file_put_contents($reportPath, $reporter->render($mapped, $targetName));
}
$io->success("Report saved to: $reportPath");
}
/**
* Dispatch configured webhook notifications (Slack, Discord, Microsoft Teams, generic JSON webhook).
*
* @param \YakNet\AccessibilityConsole\Core\Violation[] $violations
*/
private function dispatchNotifications(
InputInterface $input,
Config $config,
string $target,
int $score,
array $violations,
int $errorCount,
int $warningCount
): void {
$notifConfig = $config->getNotificationsConfig();
$dispatcher = new NotificationDispatcher();
$slackUrl = $input->getOption('webhook-slack');
if (!is_string($slackUrl) || $slackUrl === '') {
$slackUrl = is_string($notifConfig['slack_webhook'] ?? null) ? $notifConfig['slack_webhook'] : '';
}
if ($slackUrl !== '') {
$dispatcher->addNotifier('slack', new SlackNotifier($slackUrl));
}
$discordUrl = $input->getOption('webhook-discord');
if (!is_string($discordUrl) || $discordUrl === '') {
$discordUrl = is_string($notifConfig['discord_webhook'] ?? null) ? $notifConfig['discord_webhook'] : '';
}
if ($discordUrl !== '') {
$dispatcher->addNotifier('discord', new DiscordNotifier($discordUrl));
}
$teamsUrl = $input->getOption('webhook-teams');
if (!is_string($teamsUrl) || $teamsUrl === '') {
$teamsUrl = is_string($notifConfig['teams_webhook'] ?? null) ? $notifConfig['teams_webhook'] : '';
}
if ($teamsUrl !== '') {
$dispatcher->addNotifier('teams', new MicrosoftTeamsNotifier($teamsUrl));
}
$genericUrl = $input->getOption('webhook-url');
if (!is_string($genericUrl) || $genericUrl === '') {
$genericUrl = is_string($notifConfig['webhook_url'] ?? null) ? $notifConfig['webhook_url'] : '';
}
$secret = is_string($notifConfig['webhook_secret'] ?? null) ? $notifConfig['webhook_secret'] : null;
if ($genericUrl !== '') {
$dispatcher->addNotifier('webhook', new GenericWebhookNotifier($genericUrl, $secret));
}
if (!$dispatcher->hasNotifiers()) {
return;
}
$topViolations = array_map(
static fn($v): array => $v->toArray(),
array_slice($violations, 0, 5)
);
$payload = new NotificationPayload(
target: $target,
healthScore: $score,
totalViolations: count($violations),
errorCount: $errorCount,
warningCount: $warningCount,
topViolations: $topViolations
);
$dispatcher->dispatch($payload);
}
}
+96
View File
@@ -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;
}
}
+217
View File
@@ -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));
}
}
+14 -3
View File
@@ -24,7 +24,17 @@ abstract class AbstractRule
return 4;
}
protected function createViolation(string $message, \DOMElement $element): Violation
public function getId(): string
{
return (new \ReflectionClass($this))->getShortName();
}
public function getDescription(): string
{
return '';
}
protected function createViolation(string $message, \DOMElement $element, ?string $suggestion = null): Violation
{
$doc = $element->ownerDocument;
$html = '';
@@ -36,11 +46,12 @@ abstract class AbstractRule
}
return new Violation(
ruleId: (new \ReflectionClass($this))->getShortName(),
ruleId: $this->getId(),
message: $message,
severity: $this->getSeverity(),
standard: $this->getStandard(),
htmlSnippet: $html
htmlSnippet: $html,
fixSuggestion: $suggestion
);
}
}
+93 -93
View File
@@ -5,6 +5,10 @@ namespace YakNet\AccessibilityConsole\Core;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
use YakNet\AccessibilityConsole\Cache\ScanCache;
use YakNet\AccessibilityConsole\Core\Locator\PreciseElementLocator;
use YakNet\AccessibilityConsole\Core\Suppression\InlineSuppressionParser;
use YakNet\AccessibilityConsole\Parser\TemplatePreprocessor;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
class Analyser
@@ -12,13 +16,31 @@ class Analyser
private Config $config;
private Scanner $scanner;
private BaselineManager $baselineManager;
private TemplatePreprocessor $templatePreprocessor;
private PreciseElementLocator $elementLocator;
private InlineSuppressionParser $suppressionParser;
private ?ScanCache $cache;
private string $projectRoot;
public function __construct(?Config $config = null, ?Scanner $scanner = null, ?BaselineManager $baselineManager = null)
{
/** @var array<int, array{file: string, line: int, ruleId: string, reason: string}> */
private array $suppressedAuditLog = [];
public function __construct(
?Config $config = null,
?Scanner $scanner = null,
?BaselineManager $baselineManager = null,
?TemplatePreprocessor $templatePreprocessor = null,
?PreciseElementLocator $elementLocator = null,
?InlineSuppressionParser $suppressionParser = null,
?ScanCache $cache = null
) {
$this->config = $config ?? new Config();
$this->scanner = $scanner ?? $this->setupScanner();
$this->baselineManager = $baselineManager ?? new BaselineManager();
$this->templatePreprocessor = $templatePreprocessor ?? new TemplatePreprocessor();
$this->elementLocator = $elementLocator ?? new PreciseElementLocator();
$this->suppressionParser = $suppressionParser ?? new InlineSuppressionParser();
$this->cache = $cache;
$cwd = getcwd();
$this->projectRoot = $cwd ? str_replace('\\', '/', realpath($cwd) ?: $cwd) : '.';
@@ -39,9 +61,7 @@ class Analyser
$activeRules = [];
foreach ($rules as $rule) {
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
: (new \ReflectionClass($rule))->getShortName();
$ruleId = $rule->getId();
if (in_array($ruleId, $rulesConfig['exclude'], true)) {
continue;
@@ -56,8 +76,8 @@ class Analyser
$reflection = new \ReflectionClass($customRuleClass);
if ($reflection->isInstantiable()) {
$rule = $reflection->newInstance();
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
$ruleId = method_exists($rule, 'getId')
? $rule->getId()
: $reflection->getShortName();
$activeRules[$ruleId] = $rule;
}
@@ -102,36 +122,70 @@ class Analyser
$violations = [];
$baselinedCount = 0;
$this->suppressedAuditLog = [];
foreach ($filesToScan as $index => $file) {
if ($onProgress) {
$onProgress($file, $index + 1, $totalFiles);
}
$content = @file_get_contents($file);
if ($content === false || trim($content) === '') {
$rawContent = @file_get_contents($file);
if ($rawContent === false || trim($rawContent) === '') {
continue;
}
// Scan file content
try {
$fileViolations = $this->scanner->scan($content);
} catch (\Throwable $e) {
// Skip if parsing failed dramatically
continue;
}
$relativeFile = $this->makePathRelative($file);
// Parse inline suppression directives (<!-- a11y-disable... -->)
$suppressions = $this->suppressionParser->parse($rawContent);
// Try incremental cache hit first
$cachedViolations = $this->cache?->get($relativeFile, $rawContent);
if ($cachedViolations !== null) {
$fileViolations = $cachedViolations;
} else {
// Preprocess templates (Blade, Twig, Vue, JSX, PHP) into scan-ready HTML preserving line numbers
$scanContent = $this->templatePreprocessor->preprocess($rawContent, $file);
// Scan file content
try {
$fileViolations = $this->scanner->scan($scanContent);
} catch (\Throwable $e) {
// Skip if parsing failed dramatically
continue;
}
// Enrich line/column locations before caching
foreach ($fileViolations as $violation) {
if (!isset($violation->location['line']) || $violation->location['line'] <= 1) {
$location = $this->elementLocator->locate($rawContent, $violation->htmlSnippet);
$violation->location = [
'file' => $relativeFile,
'line' => $location['line'],
'column' => $location['column'],
];
} else {
$violation->location['file'] = $relativeFile;
}
}
$this->cache?->put($relativeFile, $rawContent, $fileViolations);
}
foreach ($fileViolations as $violation) {
// Find line number using line-by-line helper
$line = $this->locateLineInContent($content, $violation->htmlSnippet);
// Store location in violation
$violation->location = [
'file' => $relativeFile,
'line' => $line
];
$lineNum = $violation->location['line'] ?? 1;
// Check inline suppression directives
$suppressionReason = $this->suppressionParser->getSuppressionReason($suppressions, $violation->ruleId, $lineNum);
if ($suppressionReason !== null) {
$this->suppressedAuditLog[] = [
'file' => $relativeFile,
'line' => $lineNum,
'ruleId' => $violation->ruleId,
'reason' => $suppressionReason,
];
continue;
}
// Check if ignored in baseline
if ($this->baselineManager->isIgnored($relativeFile, $violation->ruleId, $violation->htmlSnippet)) {
@@ -141,6 +195,8 @@ class Analyser
}
}
}
$this->cache?->save();
return [
'violations' => $violations,
@@ -148,6 +204,16 @@ class Analyser
];
}
/**
* Audit trail of violations suppressed via inline comments during the latest analysis run.
*
* @return array<int, array{file: string, line: int, ruleId: string, reason: string}>
*/
public function getSuppressedAuditLog(): array
{
return $this->suppressedAuditLog;
}
public function getBaselineManager(): BaselineManager
{
return $this->baselineManager;
@@ -194,7 +260,7 @@ class Analyser
$iterator = new RecursiveIteratorIterator($filter, RecursiveIteratorIterator::SELF_FIRST);
$extensions = ['php', 'html', 'twig', 'blade.php'];
$extensions = $this->config->getExtensions();
foreach ($iterator as $file) {
/** @var SplFileInfo $file */
@@ -221,70 +287,4 @@ class Analyser
return $files;
}
private function locateLineInContent(string $content, string $snippet): int
{
$replaced = preg_replace('/\s+/', ' ', $snippet);
$cleanSnippet = is_string($replaced) ? trim($replaced) : '';
if ($cleanSnippet === '') {
return 1;
}
$searchSnippet = mb_strlen($cleanSnippet) > 150 ? mb_substr($cleanSnippet, 0, 150) : $cleanSnippet;
$lines = explode("\n", $content);
// 1. Exact match pass
foreach ($lines as $index => $line) {
$replacedLine = preg_replace('/\s+/', ' ', $line);
$cleanLine = is_string($replacedLine) ? trim($replacedLine) : '';
if (str_contains($cleanLine, $searchSnippet)) {
return $index + 1;
}
}
// 2. Parse snippet to find tag and attributes for fuzzy match pass
preg_match('/<([a-zA-Z0-9]+)/', $snippet, $matches);
$tagName = $matches[1] ?? null;
if (!$tagName) {
return 1;
}
preg_match_all('/([a-zA-Z0-9-]+)=["\']([^"\']*)["\']/', $snippet, $attrMatches, PREG_SET_ORDER);
$attributes = [];
foreach ($attrMatches as $match) {
$attributes[$match[1]] = $match[2];
}
$bestLine = 1;
$maxScore = 0;
foreach ($lines as $index => $line) {
$replacedLine = preg_replace('/\s+/', ' ', $line);
$cleanLine = is_string($replacedLine) ? trim($replacedLine) : '';
if (!str_contains(strtolower($cleanLine), '<' . strtolower($tagName))) {
continue;
}
$score = 1.0;
if (in_array(strtolower($tagName), ['html', 'head', 'body', 'title'], true)) {
$score += 1.0;
}
foreach ($attributes as $name => $value) {
if (str_contains($cleanLine, "$name=\"$value\"") || str_contains($cleanLine, "$name='$value'")) {
$score += 2.0;
} elseif (str_contains($cleanLine, $name . '=')) {
$score += 0.5;
}
}
if ($score > $maxScore) {
$maxScore = $score;
$bestLine = $index + 1;
}
}
return $bestLine;
}
}
+6 -1
View File
@@ -24,7 +24,12 @@ class BaselineManager
}
foreach ($data['violations'] as $item) {
if (isset($item['file'], $item['ruleId'], $item['htmlSnippet'])) {
if (!is_array($item)) {
continue;
}
if (isset($item['file'], $item['ruleId'], $item['htmlSnippet'])
&& is_string($item['file']) && is_string($item['ruleId']) && is_string($item['htmlSnippet'])
) {
$key = $this->calculateKey($item['file'], $item['ruleId'], $item['htmlSnippet']);
$this->ignoredKeys[$key] = true;
}
+57 -5
View File
@@ -35,6 +35,7 @@ class Config
try {
$content = \Symfony\Component\Yaml\Yaml::parseFile($path);
if (is_array($content)) {
/** @var array<string, mixed> $content */
return new self($content);
}
} catch (\Throwable $e) {
@@ -56,7 +57,7 @@ class Config
{
$paths = $this->get('paths');
if (is_array($paths)) {
return $paths;
return array_values(array_filter($paths, 'is_string'));
}
if (is_string($paths)) {
return [$paths];
@@ -71,7 +72,7 @@ class Config
{
$exclude = $this->get('exclude_paths');
if (is_array($exclude)) {
return $exclude;
return array_values(array_filter($exclude, 'is_string'));
}
if (is_string($exclude)) {
return [$exclude];
@@ -108,10 +109,10 @@ class Config
if (is_array($rules)) {
if (isset($rules['include']) && is_array($rules['include'])) {
$include = $rules['include'];
$include = array_values(array_filter($rules['include'], 'is_string'));
}
if (isset($rules['exclude']) && is_array($rules['exclude'])) {
$exclude = $rules['exclude'];
$exclude = array_values(array_filter($rules['exclude'], 'is_string'));
}
}
@@ -123,6 +124,57 @@ class Config
public function getGeminiApiKey(): ?string
{
return $this->get('gemini_api_key') ?? $_ENV['GEMINI_API_KEY'] ?? getenv('GEMINI_API_KEY') ?: null;
$key = $this->get('gemini_api_key') ?? $_ENV['GEMINI_API_KEY'] ?? getenv('GEMINI_API_KEY') ?: null;
return is_string($key) ? $key : null;
}
public function getPreset(): ?string
{
$preset = $this->get('preset');
return is_string($preset) && $preset !== '' ? $preset : null;
}
/**
* Governance policy configuration block from a11y.yaml.
*
* @return array<string, mixed>
*/
public function getPolicyConfig(): array
{
$policy = $this->get('policy', []);
if (!is_array($policy)) {
return [];
}
/** @var array<string, mixed> $policy */
return $policy;
}
/**
* Notification webhook configuration block from a11y.yaml.
*
* @return array<string, mixed>
*/
public function getNotificationsConfig(): array
{
$notifications = $this->get('notifications', []);
if (!is_array($notifications)) {
return [];
}
/** @var array<string, mixed> $notifications */
return $notifications;
}
/**
* File extensions to include during directory scans.
*
* @return array<int, string>
*/
public function getExtensions(): array
{
$extensions = $this->get('extensions');
if (is_array($extensions)) {
return array_values(array_filter($extensions, 'is_string'));
}
return ['php', 'html', 'htm', 'xhtml', 'twig', 'blade.php', 'vue', 'jsx', 'tsx', 'latte'];
}
}
+25 -1
View File
@@ -7,10 +7,16 @@ use Psr\Container\ContainerInterface;
use YakNet\AccessibilityConsole\Core\Config;
use YakNet\AccessibilityConsole\Core\Analyser;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\CompareCommand;
use YakNet\AccessibilityConsole\Console\Command\DoctorCommand;
use YakNet\AccessibilityConsole\Console\Command\ExplainCommand;
use YakNet\AccessibilityConsole\Console\Command\FixCommand;
use YakNet\AccessibilityConsole\Console\Command\InitCommand;
use YakNet\AccessibilityConsole\Console\Command\PresetsCommand;
use YakNet\AccessibilityConsole\Console\Command\RulesCommand;
use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\VpatCommand;
use YakNet\AccessibilityConsole\Console\Command\WatchCommand;
class ContainerFactory
{
@@ -51,6 +57,24 @@ class ContainerFactory
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();
+107
View File
@@ -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];
}
}
+71 -15
View File
@@ -2,43 +2,99 @@
namespace YakNet\AccessibilityConsole\Core;
use DOMDocument;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Rules\RuleExecutionStats;
use YakNet\AccessibilityConsole\Rules\RuleInterface;
class RuleEngine
{
/** @var array<int, mixed> */
private array $rules = [];
private ?RuleExecutionStats $stats = null;
public function setStats(?RuleExecutionStats $stats): void
{
$this->stats = $stats;
}
public function getStats(): ?RuleExecutionStats
{
return $this->stats;
}
public function addRule(mixed $rule): void
{
$this->rules[] = $rule;
}
/**
* @return array<int, mixed>
*/
public function getRules(): array
{
return $this->rules;
}
/**
* Run all registered rules against the DOMDocument using single-pass DOM traversal.
*
* @param DOMDocument $doc
* @return Violation[]
*/
public function run(\DOMDocument $doc): array
public function run(DOMDocument $doc): array
{
$allViolations = [];
$docRules = [];
$elementRules = [];
foreach ($this->rules as $rule) {
if ($rule instanceof AbstractRule) {
// Document-level rule (Core\AbstractRule style)
$violations = $rule->check($doc);
$allViolations = array_merge($allViolations, $violations);
} elseif ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface) {
// Element-level rule (Rules\RuleInterface style)
$xpath = new \DOMXPath($doc);
$elements = $xpath->query('//*');
if ($elements !== false) {
foreach ($elements as $element) {
if ($element instanceof \DOMElement) {
$violation = $rule->check($element);
if ($violation) {
$allViolations[] = $violation;
}
$docRules[] = $rule;
} elseif ($rule instanceof RuleInterface) {
$elementRules[] = $rule;
}
}
// 1. Run Document-level rules
foreach ($docRules as $rule) {
$start = $this->stats !== null ? hrtime(true) : 0;
$violations = $rule->check($doc);
if ($this->stats !== null) {
$elapsedMs = (hrtime(true) - $start) / 1_000_000;
$this->stats->record($rule->getId(), $elapsedMs, !empty($violations));
}
$allViolations = array_merge($allViolations, $violations);
}
// 2. Run Element-level rules in a single DOM pass
if (!empty($elementRules)) {
$xpath = new DOMXPath($doc);
$elements = $xpath->query('//*');
if ($elements !== false) {
foreach ($elements as $element) {
if (!$element instanceof DOMElement) {
continue;
}
foreach ($elementRules as $rule) {
$start = $this->stats !== null ? hrtime(true) : 0;
$violation = $rule->check($element);
if ($this->stats !== null) {
$elapsedMs = (hrtime(true) - $start) / 1_000_000;
$this->stats->record($rule->getId(), $elapsedMs, $violation !== null);
}
if ($violation !== null) {
$allViolations[] = $violation;
}
}
}
}
}
return $allViolations;
}
}
+89
View File
@@ -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',
];
}
}
+9
View File
@@ -16,6 +16,11 @@ class Scanner
$this->engine->addRule($rule);
}
public function getEngine(): RuleEngine
{
return $this->engine;
}
/**
* Scan HTML content for accessibility violations.
*
@@ -33,6 +38,10 @@ class Scanner
]);
$doc = $html5->loadHTML($html);
// Attach raw HTML property for syntax/token level analysis
/** @phpstan-ignore-next-line */
@$doc->rawHtml = $html;
return $this->engine->run($doc);
}
}
+254 -2
View File
@@ -18,7 +18,80 @@ class LocalHealer
$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>'],
@@ -27,14 +100,17 @@ class LocalHealer
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;
@@ -42,6 +118,7 @@ class LocalHealer
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;
@@ -53,13 +130,188 @@ class LocalHealer
break;
case 'WCAG_3_1_1_LANG':
case 'HtmlHasLang':
if (preg_match('/<html(\s+[^>]*>|>)/i', $snippet)) {
$fixed = preg_replace('/<html/i', '<html lang="en"', $snippet) ?: $snippet;
return "EXPLANATION: Injected default lang=\"en\" to HTML element.\nFIX: " . $fixed;
$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];
}
}
+3 -3
View File
@@ -5,20 +5,20 @@ namespace YakNet\AccessibilityConsole\Core;
class Violation
{
/**
* @param array{file: string, line: int}|null $location
* @param array{file?: string, line: int, column?: int}|null $location
*/
public function __construct(
public string $ruleId,
public string $message,
public Severity $severity,
public WCAGStandard $standard,
public string $htmlSnippet,
public string $htmlSnippet = '',
public ?array $location = null, // ['file' => '...', 'line' => 0]
public ?string $fixSuggestion = null
) {}
/**
* @return array{ruleId: string, message: string, severity: string, standard: string, htmlSnippet: string, location: array{file: string, line: int}|null, fixSuggestion: string|null}
* @return array{ruleId: string, message: string, severity: string, standard: string, htmlSnippet: string, location: array{file?: string, line: int, column?: int}|null, fixSuggestion: string|null}
*/
public function toArray(): array
{
@@ -0,0 +1,32 @@
<?php
namespace YakNet\AccessibilityConsole\Integrations;
class GitHubActionsReporter
{
/**
* Format WCAG violations as GitHub Actions Workflow Command Annotations.
*
* @param array<string, mixed> $scanResult
* @param string $fileName
* @return string Formatted annotations string
*/
public static function formatAnnotations(array $scanResult, string $fileName = 'index.html'): string
{
/** @var array<int, array<string, mixed>> $violations */
$violations = is_array($scanResult['violations'] ?? null) ? $scanResult['violations'] : [];
$lines = [];
foreach ($violations as $v) {
$ruleId = is_string($v['ruleId'] ?? null) ? $v['ruleId'] : 'WCAG';
$desc = is_string($v['description'] ?? null) ? $v['description'] : '';
$line = is_numeric($v['line'] ?? null) ? intval($v['line']) : 1;
$severity = is_string($v['severity'] ?? null) ? strtolower($v['severity']) : 'error';
$level = $severity === 'error' ? 'error' : 'warning';
$lines[] = sprintf('::%s file=%s,line=%d::[%s] %s', $level, $fileName, $line, $ruleId, $desc);
}
return implode("\n", $lines);
}
}
+66
View File
@@ -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);
}
}
+18
View File
@@ -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 = []
) {}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace YakNet\AccessibilityConsole\Notifications;
interface NotifierInterface
{
public function send(NotificationPayload $payload): bool;
}
+55
View File
@@ -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;
}
}
}
+22 -9
View File
@@ -6,15 +6,28 @@ class BladeParser implements ParserInterface
{
public function parse(string $content): string
{
// Replace {!! ... !!} with static text
$content = preg_replace('/\{\!\!(.*?)\!\!\}/s', 'StaticRawBladeContent', $content) ?? $content;
// Replace {{ ... }} with static text
$content = preg_replace('/\{\{\s*(.*?)\s*\}\}/s', 'StaticBladeContent', $content) ?? $content;
// Strip Blade directives like @if, @else, @endif, @foreach, @endforeach, etc.
$content = preg_replace('/@[a-zA-Z0-9_]+\s*(\(.*?\))?/i', '', $content) ?? $content;
// 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;
}
}
+60
View File
@@ -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;
}
}
+86
View File
@@ -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;
}
}
+16 -9
View File
@@ -6,15 +6,22 @@ class TwigParser implements ParserInterface
{
public function parse(string $content): string
{
// Strip Twig comments {# ... #}
$content = preg_replace('/\{\#.*?\#\}/s', '', $content) ?? $content;
// Replace Twig output {{ ... }} with static text
$content = preg_replace('/\{\{\s*(.*?)\s*\}\}/s', 'StaticTwigOutput', $content) ?? $content;
// Strip Twig statements {% ... %}
$content = preg_replace('/\{\%.*?\%\}/s', '', $content) ?? $content;
// 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;
}
}
+46
View File
@@ -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;
}
}
+171
View File
@@ -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);
}
}
+31
View File
@@ -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,
];
}
}
+43
View File
@@ -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 [];
}
}
+42
View File
@@ -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 [];
}
}
+39
View File
@@ -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 [];
}
}
+43
View File
@@ -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 [];
}
}
+44
View File
@@ -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 [];
}
}
+37
View File
@@ -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 [];
}
}
+44
View File
@@ -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 [];
}
}
+44
View File
@@ -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 [];
}
}
+22
View File
@@ -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;
}
+44
View File
@@ -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;
}
}
+39
View File
@@ -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 [];
}
}
+40
View File
@@ -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 [];
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Presets;
class Wcag22AAPreset implements PresetInterface
{
public function getName(): string
{
return 'wcag22-aa';
}
public function getDescription(): string
{
return 'Full W3C WCAG 2.2 Level A & AA compliance profile.';
}
public function getLevel(): int
{
return 4;
}
public function getIncludedRules(): array
{
return [
'WCAG_2_4_11_FOCUS_NOT_OBSCURED',
'WCAG_2_5_7_DRAGGING_MOVEMENTS',
'WCAG_2_5_8_TARGET_SIZE',
'WCAG_2_5_8_TARGET_SPACING',
'WCAG_3_2_6_CONSISTENT_HELP',
'WCAG_3_3_7_REDUNDANT_ENTRY',
'WCAG_3_3_8_ACCESSIBLE_AUTH',
'WCAG_1_4_3_CONTRAST',
'WCAG_2_4_7_FOCUS_OUTLINE',
];
}
public function getExcludedRules(): array
{
return [];
}
}
+285 -2
View File
@@ -70,7 +70,7 @@ class WcagDatabase
url: 'https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html',
description: 'Alt attributes must not contain placeholder words or file names. They should provide a meaningful description of the image content.',
badExample: '<img src="logo.png" alt="logo">',
goodExample: '<img src="logo.png" alt="YakNet Company Logo">'
goodExample: '<img src="logo.png" alt="YakNet Logo">'
));
self::add(new WcagCriterion(
@@ -112,6 +112,275 @@ class WcagDatabase
badExample: '<input name="search" autofocus>',
goodExample: '<input name="search">'
));
self::add(new WcagCriterion(
id: 'WCAG_2_5_8_TARGET_SIZE',
title: '2.5.8 Target Size (Minimum)',
level: 'AA',
url: 'https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html',
description: 'The size of the target for pointer inputs is at least 24 by 24 CSS pixels.',
badExample: '<button style="width: 16px; height: 16px;">X</button>',
goodExample: '<button style="width: 24px; height: 24px;">X</button>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_3_1_DETAILS_SUMMARY',
title: '1.3.1 Info and Relationships',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships.html',
description: '<details> elements must have a <summary> element to serve as an accessible disclosure trigger.',
badExample: '<details><p>Details content</p></details>',
goodExample: '<details><summary>More info</summary><p>Details content</p></details>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_CURRENT',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: 'The aria-current attribute must have a valid value indicating the current item in a set.',
badExample: '<a href="/home" aria-current="active">Home</a>',
goodExample: '<a href="/home" aria-current="page">Home</a>'
));
self::add(new WcagCriterion(
id: 'WCAG_3_3_1_ARIA_ERRORMESSAGE',
title: '3.3.1 Error Identification',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/error-identification.html',
description: 'aria-errormessage must reference a valid error element and control must have aria-invalid="true".',
badExample: '<input name="email" aria-errormessage="email_error">',
goodExample: '<input name="email" aria-invalid="true" aria-errormessage="email_err"><span id="email_err">Invalid email</span>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_ROLEDESCRIPTION',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: 'aria-roledescription must only be used on elements with a non-generic role.',
badExample: '<div aria-roledescription="slide">Slide 1</div>',
goodExample: '<div role="region" aria-roledescription="slide" aria-label="Slide 1">Slide 1</div>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_PROHIBITED_ATTR',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: 'Prohibited ARIA attributes must not be used on presentation or generic roles.',
badExample: '<div role="presentation" aria-label="decorative"></div>',
goodExample: '<div role="presentation"></div>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_3_2_HTML_DIR',
title: '1.3.2 Meaningful Sequence',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/meaningful-sequence.html',
description: 'The dir attribute must only use valid values: ltr, rtl, or auto.',
badExample: '<p dir="left">Text</p>',
goodExample: '<p dir="ltr">Text</p>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_3_1_SELECT_CHILDREN',
title: '1.3.1 Info and Relationships',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships.html',
description: '<select> elements must only contain valid child elements (<option>, <optgroup>).',
badExample: '<select><div>Option 1</div></select>',
goodExample: '<select><option>Option 1</option></select>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_1_1_ROLE_IMG',
title: '1.1.1 Non-text Content',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html',
description: 'Elements with role="img" must have an accessible name.',
badExample: '<span role="img" class="icon-star"></span>',
goodExample: '<span role="img" class="icon-star" aria-label="5 stars rating"></span>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_4_2_MEDIA_CONTROLS',
title: '1.4.2 Audio Control',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/audio-control.html',
description: 'Audio and video media elements should provide user controls for playback and volume.',
badExample: '<audio src="podcast.mp3"></audio>',
goodExample: '<audio src="podcast.mp3" controls></audio>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_2_2_TRACK_VALIDATION',
title: '1.2.2 Captions (Prerecorded)',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/captions-prerecorded.html',
description: '<track> elements must have valid kind, srclang, and label attributes.',
badExample: '<track src="sub.vtt" kind="captions">',
goodExample: '<track src="sub.vtt" kind="captions" srclang="en" label="English">'
));
self::add(new WcagCriterion(
id: 'WCAG_2_1_1_ACCESSKEY_DUPLICATE',
title: '2.1.1 Keyboard',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/keyboard.html',
description: 'accesskey attribute values must be unique across the document.',
badExample: '<a href="/" accesskey="h">Home</a><a href="/help" accesskey="h">Help</a>',
goodExample: '<a href="/" accesskey="h">Home</a><a href="/help" accesskey="p">Help</a>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_BUTTON_NESTED_INTERACTIVE',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: '<button> elements must not contain nested interactive elements.',
badExample: '<button><a href="/cart">Checkout</a></button>',
goodExample: '<a href="/cart" class="btn">Checkout</a>'
));
self::add(new WcagCriterion(
id: 'WCAG_2_4_11_FOCUS_NOT_OBSCURED',
title: '2.4.11 Focus Not Obscured (Minimum)',
level: 'AA',
url: 'https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-minimum.html',
description: 'Fixed or sticky headers and overlays must not completely obscure keyboard-focused elements.',
badExample: '<header style="position: fixed; top: 0; width: 100%; height: 80px;"></header>',
goodExample: '<html style="scroll-padding-top: 80px;"><header style="position: fixed; top: 0; width: 100%; height: 80px;"></header></html>'
));
self::add(new WcagCriterion(
id: 'WCAG_2_5_7_DRAGGING_MOVEMENTS',
title: '2.5.7 Dragging Movements',
level: 'AA',
url: 'https://www.w3.org/WAI/WCAG22/Understanding/dragging-movements.html',
description: 'Elements supporting drag-and-drop operations must provide a single-pointer alternative.',
badExample: '<div draggable="true" class="list-item">Item 1</div>',
goodExample: '<div draggable="true" class="list-item">Item 1 <button>Move Up</button> <button>Move Down</button></div>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_LABEL_GENERIC',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: 'Generic <div> or <span> elements should not use aria-label without an explicit ARIA role.',
badExample: '<div aria-label="Important Notice">Text</div>',
goodExample: '<div role="region" aria-label="Important Notice">Text</div>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_3_5_AUTOCOMPLETE_APPROPRIATE',
title: '1.3.5 Identify Input Purpose',
level: 'AA',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/identify-input-purpose.html',
description: 'Input autocomplete value must be semantically appropriate for the input type.',
badExample: '<input type="number" autocomplete="email">',
goodExample: '<input type="email" autocomplete="email">'
));
self::add(new WcagCriterion(
id: 'WCAG_2_4_13_FOCUS_APPEARANCE',
title: '2.4.13 Focus Appearance',
level: 'AAA',
url: 'https://www.w3.org/WAI/WCAG22/Understanding/focus-appearance.html',
description: 'Focus indicators must enclose the element with at least a 2px perimeter and sufficient contrast.',
badExample: '<style>a:focus { outline: 1px dotted #ccc; }</style>',
goodExample: '<style>a:focus-visible { outline: 2px solid #005fcc; outline-offset: 2px; }</style>'
));
self::add(new WcagCriterion(
id: 'WCAG_2_3_1_FLASHING_CONTENT',
title: '2.3.1 Three Flashes or Below Threshold',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/three-flashes-or-below-threshold.html',
description: 'Web pages must not contain anything that flashes more than three times in any one second period.',
badExample: '<div style="animation: flash 0.15s infinite;">Alert</div>',
goodExample: '<div style="animation: fade 1.2s ease-in-out;">Alert</div>'
));
self::add(new WcagCriterion(
id: 'WCAG_2_3_3_REDUCED_MOTION',
title: '2.3.3 Animation from Interactions',
level: 'AAA',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/animation-from-interactions.html',
description: 'Motion animation triggered by interaction can be disabled unless essential.',
badExample: '<style>@keyframes slide { from { left: 0; } to { left: 100px; } }</style>',
goodExample: '<style>@keyframes slide { from { left: 0; } to { left: 100px; } } @media (prefers-reduced-motion: reduce) { * { animation: none !important; } }</style>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_3_4_ORIENTATION_LOCK',
title: '1.3.4 Orientation',
level: 'AA',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/orientation.html',
description: 'Content does not restrict its view and operation to a single display orientation such as portrait or landscape.',
badExample: '<style>@media (orientation: landscape) { body { display: none; } }</style>',
goodExample: '<style>.layout { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); }</style>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_TABLIST',
title: '4.1.2 Name, Role, Value (APG Tabs)',
level: 'A',
url: 'https://www.w3.org/WAI/ARIA/apg/patterns/tabs/',
description: 'ARIA Tabs require role="tablist", child role="tab" with aria-selected & aria-controls, and role="tabpanel" with aria-labelledby.',
badExample: '<div role="tablist"><button role="tab">Tab 1</button></div>',
goodExample: '<div role="tablist"><button id="t1" role="tab" aria-selected="true" aria-controls="p1">Tab 1</button></div><div id="p1" role="tabpanel" aria-labelledby="t1">Panel</div>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_COMBOBOX',
title: '4.1.2 Name, Role, Value (APG Combobox)',
level: 'A',
url: 'https://www.w3.org/WAI/ARIA/apg/patterns/combobox/',
description: 'Combobox controls require aria-expanded, aria-controls (or aria-owns), and an accessible name.',
badExample: '<input role="combobox">',
goodExample: '<input role="combobox" aria-expanded="false" aria-controls="city-list" aria-label="Select City">'
));
self::add(new WcagCriterion(
id: 'WCAG_3_2_6_CONSISTENT_HELP',
title: '3.2.6 Consistent Help',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG22/Understanding/consistent-help.html',
description: 'Help mechanisms appear in the same relative order across pages where they are provided.',
badExample: '<body><header><nav><a href="/">Home</a></nav></header><form><input type="text"></form></body>',
goodExample: '<body><header><nav><a href="/">Home</a><a href="/help">Help</a></nav></header><form><input type="text"></form></body>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_4_6_CONTRAST_AAA',
title: '1.4.6 Contrast (Enhanced)',
level: 'AAA',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/contrast-enhanced.html',
description: 'Visual presentation of text has a contrast ratio of at least 7:1 (4.5:1 for large text).',
badExample: '<p style="color: #767676; background-color: #ffffff;">Gray text</p>',
goodExample: '<p style="color: #333333; background-color: #ffffff;">High contrast text</p>'
));
self::add(new WcagCriterion(
id: 'WCAG_2_5_2_POINTER_CANCELLATION',
title: '2.5.2 Pointer Cancellation',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/pointer-cancellation.html',
description: 'Functions operated using a single pointer should not execute on the down-event.',
badExample: '<button onmousedown="deleteItem()">Delete</button>',
goodExample: '<button onclick="deleteItem()">Delete</button>'
));
self::add(new WcagCriterion(
id: 'WCAG_2_1_4_CHAR_KEY_SHORTCUTS',
title: '2.1.4 Character Key Shortcuts',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/character-key-shortcuts.html',
description: 'Single printable character keyboard shortcuts must use a modifier or be remappable/disableable.',
badExample: '<button aria-keyshortcuts="s">Save</button>',
goodExample: '<button aria-keyshortcuts="Control+S">Save</button>'
));
}
public static function add(WcagCriterion $criterion): void
@@ -122,7 +391,21 @@ class WcagDatabase
public static function get(string $ruleId): ?WcagCriterion
{
self::load();
return self::$criteria[$ruleId] ?? null;
if (isset(self::$criteria[$ruleId])) {
return self::$criteria[$ruleId];
}
// Prefix fallback: match by WCAG success criterion prefix (e.g. WCAG_1_1_1_* -> any WCAG_1_1_1_*)
if (preg_match('/^(WCAG_\d+_\d+_\d+)/', $ruleId, $m)) {
$prefix = $m[1];
foreach (self::$criteria as $id => $criterion) {
if (str_starts_with($id, $prefix)) {
return $criterion;
}
}
}
return null;
}
/**
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Reporting;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
/**
* Formats accessibility violations in standard Checkstyle XML format
* for integration with Jenkins, PhpStorm, SonarQube, and GitLab CI.
*/
class CheckstyleFormatter implements FormatterInterface
{
/**
* @param Violation[] $violations
* @param int $baselinedCount
* @param SymfonyStyle $io
* @return int
*/
public function format(array $violations, int $baselinedCount, SymfonyStyle $io): int
{
$io->write($this->render($violations));
return empty($violations) ? Command::SUCCESS : Command::FAILURE;
}
/**
* Render Checkstyle XML string.
*
* @param Violation[] $violations
*/
public function render(array $violations): string
{
/** @var array<string, Violation[]> $grouped */
$grouped = [];
foreach ($violations as $v) {
$file = $v->location['file'] ?? 'unknown';
$grouped[$file][] = $v;
}
$xml = [];
$xml[] = '<?xml version="1.0" encoding="UTF-8"?>';
$xml[] = '<checkstyle version="4.0.0">';
foreach ($grouped as $file => $fileViolations) {
$xml[] = sprintf(' <file name="%s">', $this->escapeAttr($file));
foreach ($fileViolations as $v) {
$line = isset($v->location['line']) ? max(1, (int)$v->location['line']) : 1;
$col = isset($v->location['column']) ? max(1, (int)$v->location['column']) : 1;
$sev = match ($v->severity) {
Severity::CRITICAL, Severity::ERROR => 'error',
Severity::WARNING => 'warning',
Severity::INFO => 'info',
};
$source = 'YakNet.Accessibility.' . $v->ruleId;
$xml[] = sprintf(
' <error line="%d" column="%d" severity="%s" message="%s" source="%s"/>',
$line,
$col,
$sev,
$this->escapeAttr($v->message),
$this->escapeAttr($source)
);
}
$xml[] = ' </file>';
}
$xml[] = '</checkstyle>';
return implode("\n", $xml) . "\n";
}
private function escapeAttr(string $value): string
{
return htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
}
}
+371
View File
@@ -0,0 +1,371 @@
<?php
namespace YakNet\AccessibilityConsole\Reporting;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use YakNet\AccessibilityConsole\Analytics\ComplianceMatrixGenerator;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Reference\WcagDatabase;
class ExcelReportExporter
{
/**
* Export WCAG audit results as a multi-tab Excel (.xlsx) workbook.
*
* @param array<string, mixed> $scanResult
* @param string $targetUrl
* @return string Binary Excel content
*/
public static function exportExcel(array $scanResult, string $targetUrl): string
{
if (!class_exists(Spreadsheet::class)) {
throw new \RuntimeException('To export Excel audit reports, please install phpspreadsheet via: composer require phpoffice/phpspreadsheet');
}
date_default_timezone_set('Europe/Istanbul');
/** @var int $score */
$score = is_numeric($scanResult['score'] ?? null) ? intval($scanResult['score']) : 0;
/** @var array<int, array<string, mixed>> $violations */
$violations = is_array($scanResult['violations'] ?? null) ? $scanResult['violations'] : [];
$violationsCount = count($violations);
$dateStr = date('d.m.Y H:i:s');
$reportId = 'YAK-A11Y-' . date('Ymd') . '-' . strtoupper(substr(md5($targetUrl . date('Ymd')), 0, 6));
// Severity counters
$criticalCount = 0;
$warningCount = 0;
$infoCount = 0;
foreach ($violations as $v) {
$rawSev = $v['severity'] ?? 'ERROR';
$sev = strtoupper(is_scalar($rawSev) ? (string)$rawSev : 'ERROR');
if ($sev === 'ERROR' || $sev === 'CRITICAL') {
$criticalCount++;
} elseif ($sev === 'WARNING' || $sev === 'WARN') {
$warningCount++;
} else {
$infoCount++;
}
}
// Compliance Matrix
$rawMatrix = $scanResult['complianceMatrix'] ?? null;
/** @var array<string, mixed>|null $matrix */
$matrix = is_array($rawMatrix) ? $rawMatrix : null;
if (!$matrix) {
$gen = new ComplianceMatrixGenerator();
$pseudoViolations = [];
foreach ($violations as $v) {
$rawStd = $v['standard'] ?? 'WCAG 2.1 AA';
$stdStr = is_scalar($rawStd) ? (string)$rawStd : 'WCAG 2.1 AA';
$std = match($stdStr) {
'A' => \YakNet\AccessibilityConsole\Core\WCAGStandard::A,
'AAA' => \YakNet\AccessibilityConsole\Core\WCAGStandard::AAA,
default => \YakNet\AccessibilityConsole\Core\WCAGStandard::AA,
};
$rawRule = $v['ruleId'] ?? '';
$ruleId = is_scalar($rawRule) ? (string)$rawRule : '';
$rawDesc = $v['description'] ?? '';
$desc = is_scalar($rawDesc) ? (string)$rawDesc : '';
$rawLine = $v['line'] ?? 0;
$line = is_numeric($rawLine) ? (int)$rawLine : 0;
$rawSnippet = $v['htmlSnippet'] ?? '';
$snippet = is_scalar($rawSnippet) ? (string)$rawSnippet : '';
$pseudoViolations[] = new Violation(
ruleId: $ruleId,
message: $desc,
severity: \YakNet\AccessibilityConsole\Core\Severity::ERROR,
standard: $std,
location: ['line' => $line],
htmlSnippet: $snippet
);
}
$matrix = $gen->generate($pseudoViolations, max(1, count($violations)));
}
$rawPrinciples = (isset($matrix['principles']) && is_array($matrix['principles']))
? $matrix['principles']
: [
'Perceivable' => ['violations' => 0, 'status' => 'Pass'],
'Operable' => ['violations' => 0, 'status' => 'Pass'],
'Understandable' => ['violations' => 0, 'status' => 'Pass'],
'Robust' => ['violations' => 0, 'status' => 'Pass'],
];
$statusText = $score >= 80 ? 'WCAG 2.1 AA Uyumlu (Pass)' : ($score >= 50 ? 'İyileştirme Gerekli (Warning)' : 'Kritik İhlaller (Fail)');
$scoreHexColor = $score >= 80 ? '059669' : ($score >= 50 ? 'D97706' : 'DC2626');
$spreadsheet = new Spreadsheet();
// -------------------------------------------------------------
// SHEET 1: ÖZET VE DENETİM KARNESİ (Executive Summary)
// -------------------------------------------------------------
$sheetSummary = $spreadsheet->getActiveSheet();
$sheetSummary->setTitle('Denetim Özeti & Karne');
$sheetSummary->setShowGridLines(true);
// Header Banner
$sheetSummary->setCellValue('A1', '♿ YAKNET ACCESSIBILITY CONSOLE — ERİŞİLEBİLİRLİK DENETİM RAPORU');
$sheetSummary->mergeCells('A1:F1');
$sheetSummary->getStyle('A1')->getFont()->setBold(true)->setSize(14)->getColor()->setRGB('FFFFFF');
$sheetSummary->getStyle('A1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('0F172A');
$sheetSummary->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
$sheetSummary->getRowDimension(1)->setRowHeight(32);
$sheetSummary->setCellValue('A2', 'WCAG 2.1 / 2.2 Uyumluluk ve Erişilebilirlik Karnesi (YakNet Open Source)');
$sheetSummary->mergeCells('A2:F2');
$sheetSummary->getStyle('A2')->getFont()->setSize(10)->getColor()->setRGB('64748B');
$sheetSummary->getStyle('A2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheetSummary->getRowDimension(2)->setRowHeight(20);
// Metadata Table
$sheetSummary->setCellValue('A4', 'Rapor Bilgileri');
$sheetSummary->mergeCells('A4:B4');
$sheetSummary->getStyle('A4')->getFont()->setBold(true)->getColor()->setRGB('FFFFFF');
$sheetSummary->getStyle('A4')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('1E293B');
$metaRows = [
['Rapor Referans No', $reportId],
['Denetlenen Web Adresi', $targetUrl],
['Denetim Zamanı', $dateStr],
['Denetim Standardı', 'W3C WCAG 2.1 / 2.2 (Level AA) & EN 301 549'],
['Denetim Motoru', 'YakNet Accessibility Console v4.0'],
];
$r = 5;
foreach ($metaRows as $m) {
$sheetSummary->setCellValue("A{$r}", $m[0]);
$sheetSummary->setCellValue("B{$r}", $m[1]);
$sheetSummary->getStyle("A{$r}")->getFont()->setBold(true)->getColor()->setRGB('334155');
$sheetSummary->getStyle("A{$r}:B{$r}")->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN)->getColor()->setRGB('CBD5E1');
$r++;
}
// Score KPI Card (Columns D:F, Rows 4:7)
$sheetSummary->setCellValue('D4', 'Genel Sağlık Skoru');
$sheetSummary->mergeCells('D4:F4');
$sheetSummary->getStyle('D4')->getFont()->setBold(true)->getColor()->setRGB('FFFFFF');
$sheetSummary->getStyle('D4')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('1E293B');
$sheetSummary->getStyle('D4')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheetSummary->setCellValue('D5', $score . ' / 100');
$sheetSummary->mergeCells('D5:F6');
$sheetSummary->getStyle('D5')->getFont()->setBold(true)->setSize(24)->getColor()->setRGB($scoreHexColor);
$sheetSummary->getStyle('D5')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
$sheetSummary->getStyle('D5:F6')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('F8FAFC');
$sheetSummary->setCellValue('D7', $statusText);
$sheetSummary->mergeCells('D7:F7');
$sheetSummary->getStyle('D7')->getFont()->setBold(true)->getColor()->setRGB('FFFFFF');
$sheetSummary->getStyle('D7')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($scoreHexColor);
$sheetSummary->getStyle('D7')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheetSummary->getStyle('D4:F7')->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_MEDIUM)->getColor()->setRGB($scoreHexColor);
// Findings Statistics Table (Row 11)
$sheetSummary->setCellValue('A11', 'İhlal Dağılım İstatistikleri');
$sheetSummary->mergeCells('A11:C11');
$sheetSummary->getStyle('A11')->getFont()->setBold(true)->getColor()->setRGB('FFFFFF');
$sheetSummary->getStyle('A11')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('1E293B');
$statRows = [
['Toplam İhlal Sayısı', $violationsCount, '0F172A'],
['Kritik Hatalar (Error)', $criticalCount, 'DC2626'],
['Uyarılar (Warning)', $warningCount, 'D97706'],
['Bilgilendirmeler (Info)', $infoCount, '2563EB'],
];
$r = 12;
foreach ($statRows as $st) {
$sheetSummary->setCellValue("A{$r}", $st[0]);
$sheetSummary->mergeCells("A{$r}:B{$r}");
$sheetSummary->setCellValue("C{$r}", $st[1]);
$sheetSummary->getStyle("A{$r}")->getFont()->setBold(true);
$sheetSummary->getStyle("C{$r}")->getFont()->setBold(true)->getColor()->setRGB($st[2]);
$sheetSummary->getStyle("C{$r}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheetSummary->getStyle("A{$r}:C{$r}")->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN)->getColor()->setRGB('CBD5E1');
$r++;
}
// WCAG 4 Principles Table (Row 11, Cols D:F)
$sheetSummary->setCellValue('D11', 'WCAG 2.1 Dört Temel İlke Dağılımı');
$sheetSummary->mergeCells('D11:F11');
$sheetSummary->getStyle('D11')->getFont()->setBold(true)->getColor()->setRGB('FFFFFF');
$sheetSummary->getStyle('D11')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('1E293B');
$principleTr = [
'Perceivable' => '1. Algılanabilir (Perceivable)',
'Operable' => '2. Çalıştırılabilir (Operable)',
'Understandable' => '3. Anlaşılabilir (Understandable)',
'Robust' => '4. Sağlam (Robust)'
];
$r = 12;
foreach ($rawPrinciples as $pKey => $pData) {
$pKeyStr = (string)$pKey;
$pName = $principleTr[$pKeyStr] ?? $pKeyStr;
$vNum = (is_array($pData) && isset($pData['violations']) && is_numeric($pData['violations'])) ? (int)$pData['violations'] : 0;
$sheetSummary->setCellValue("D{$r}", $pName);
$sheetSummary->setCellValue("E{$r}", $vNum . ' İhlal');
$sheetSummary->setCellValue("F{$r}", $vNum === 0 ? '✓ Geçti' : '⚠ İncele');
$sheetSummary->getStyle("F{$r}")->getFont()->setBold(true)->getColor()->setRGB($vNum === 0 ? '059669' : 'DC2626');
$sheetSummary->getStyle("D{$r}:F{$r}")->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN)->getColor()->setRGB('CBD5E1');
$r++;
}
$sheetSummary->getColumnDimension('A')->setWidth(22);
$sheetSummary->getColumnDimension('B')->setWidth(38);
$sheetSummary->getColumnDimension('C')->setWidth(14);
$sheetSummary->getColumnDimension('D')->setWidth(26);
$sheetSummary->getColumnDimension('E')->setWidth(14);
$sheetSummary->getColumnDimension('F')->setWidth(18);
// -------------------------------------------------------------
// SHEET 2: TÜM İHLAL DETAYLARI (Detailed Violations Table)
// -------------------------------------------------------------
$sheetViolations = $spreadsheet->createSheet();
$sheetViolations->setTitle('İhlal Detayları');
$sheetViolations->setShowGridLines(true);
$vHeaders = ['#', 'Kural ID', 'Standart', 'Ciddiyet', 'Satır', 'İhlal Açıklaması', 'Hatalı Kod Snippet', 'Çözüm ve Düzeltme Önerisi'];
$vCols = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];
// Table Header
$vRow = 1;
foreach ($vHeaders as $i => $h) {
$col = $vCols[$i];
$sheetViolations->setCellValue("{$col}{$vRow}", $h);
$sheetViolations->getStyle("{$col}{$vRow}")->getFont()->setBold(true)->getColor()->setRGB('FFFFFF');
$sheetViolations->getStyle("{$col}{$vRow}")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('0F172A');
$sheetViolations->getStyle("{$col}{$vRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER)->setVertical(Alignment::VERTICAL_CENTER);
}
$sheetViolations->getRowDimension($vRow)->setRowHeight(28);
// Populate Table Rows
$vRow = 2;
foreach ($violations as $idx => $v) {
$rawRule = $v['ruleId'] ?? '';
$ruleId = is_scalar($rawRule) ? (string)$rawRule : '';
$rawStd = $v['standard'] ?? 'WCAG 2.1 AA';
$standard = is_scalar($rawStd) ? (string)$rawStd : 'WCAG 2.1 AA';
$rawSev = $v['severity'] ?? 'ERROR';
$severity = strtoupper(is_scalar($rawSev) ? (string)$rawSev : 'ERROR');
$rawLine = $v['line'] ?? 0;
$line = is_numeric($rawLine) ? (int)$rawLine : 0;
$rawDesc = $v['description'] ?? '';
$desc = is_scalar($rawDesc) ? (string)$rawDesc : '';
$rawSnippet = $v['htmlSnippet'] ?? '';
$snippet = is_scalar($rawSnippet) ? (string)$rawSnippet : '';
$rawSug = $v['suggestion'] ?? '';
$suggestion = is_scalar($rawSug) ? (string)$rawSug : '';
$isCrit = ($severity === 'ERROR' || $severity === 'CRITICAL');
$sevLabel = $isCrit ? 'KRİTİK' : 'UYARI';
$sevColor = $isCrit ? 'DC2626' : 'D97706';
$rowBg = ($idx % 2 === 1) ? 'F8FAFC' : 'FFFFFF';
$sheetViolations->setCellValue("A{$vRow}", $idx + 1);
$sheetViolations->setCellValue("B{$vRow}", $ruleId);
$sheetViolations->setCellValue("C{$vRow}", $standard);
$sheetViolations->setCellValue("D{$vRow}", $sevLabel);
$sheetViolations->setCellValue("E{$vRow}", $line > 0 ? $line : '-');
$sheetViolations->setCellValue("F{$vRow}", $desc);
$sheetViolations->setCellValue("G{$vRow}", $snippet);
$sheetViolations->setCellValue("H{$vRow}", $suggestion);
// Row styling
$sheetViolations->getStyle("A{$vRow}:H{$vRow}")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB($rowBg);
$sheetViolations->getStyle("A{$vRow}:H{$vRow}")->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN)->getColor()->setRGB('E2E8F0');
$sheetViolations->getStyle("A{$vRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheetViolations->getStyle("C{$vRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheetViolations->getStyle("D{$vRow}")->getFont()->setBold(true)->getColor()->setRGB($sevColor);
$sheetViolations->getStyle("D{$vRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheetViolations->getStyle("E{$vRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
// Monospace font for code snippet
$sheetViolations->getStyle("G{$vRow}")->getFont()->setName('Consolas')->setSize(9.5);
$sheetViolations->getStyle("F{$vRow}")->getAlignment()->setWrapText(true);
$sheetViolations->getStyle("G{$vRow}")->getAlignment()->setWrapText(true);
$sheetViolations->getStyle("H{$vRow}")->getAlignment()->setWrapText(true);
$sheetViolations->getRowDimension($vRow)->setRowHeight(36);
$vRow++;
}
// Enable auto-filter
if ($vRow > 2) {
$sheetViolations->setAutoFilter("A1:H" . ($vRow - 1));
}
$sheetViolations->getColumnDimension('A')->setWidth(6);
$sheetViolations->getColumnDimension('B')->setWidth(26);
$sheetViolations->getColumnDimension('C')->setWidth(14);
$sheetViolations->getColumnDimension('D')->setWidth(12);
$sheetViolations->getColumnDimension('E')->setWidth(8);
$sheetViolations->getColumnDimension('F')->setWidth(40);
$sheetViolations->getColumnDimension('G')->setWidth(35);
$sheetViolations->getColumnDimension('H')->setWidth(40);
// -------------------------------------------------------------
// SHEET 3: STANDARTLAR VE KURALLAR KATALOĞU (Rules Reference)
// -------------------------------------------------------------
$sheetRules = $spreadsheet->createSheet();
$sheetRules->setTitle('WCAG Kural Kataloğu');
$sheetRules->setShowGridLines(true);
WcagDatabase::load();
$criteria = WcagDatabase::all();
$sheetRules->setCellValue('A1', '#');
$sheetRules->setCellValue('B1', 'Kural Kodu');
$sheetRules->setCellValue('C1', 'WCAG Kriteri');
$sheetRules->setCellValue('D1', 'Seviye');
$sheetRules->setCellValue('E1', 'Açıklama');
$sheetRules->setCellValue('F1', 'W3C Resmi Kılavuz Bağlantısı');
$sheetRules->getStyle('A1:F1')->getFont()->setBold(true)->getColor()->setRGB('FFFFFF');
$sheetRules->getStyle('A1:F1')->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('0F172A');
$sheetRules->getRowDimension(1)->setRowHeight(26);
$rRow = 2;
$idx = 1;
foreach ($criteria as $code => $cr) {
$sheetRules->setCellValue("A{$rRow}", $idx);
$sheetRules->setCellValue("B{$rRow}", $cr->id);
$sheetRules->setCellValue("C{$rRow}", $cr->title);
$sheetRules->setCellValue("D{$rRow}", $cr->level);
$sheetRules->setCellValue("E{$rRow}", $cr->description);
$sheetRules->setCellValue("F{$rRow}", $cr->url);
$sheetRules->getStyle("A{$rRow}:F{$rRow}")->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN)->getColor()->setRGB('E2E8F0');
$sheetRules->getStyle("D{$rRow}")->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheetRules->getStyle("F{$rRow}")->getFont()->getColor()->setRGB('2563EB');
$sheetRules->getStyle("F{$rRow}")->getFont()->setUnderline(true);
$rRow++;
$idx++;
}
$sheetRules->getColumnDimension('A')->setWidth(6);
$sheetRules->getColumnDimension('B')->setWidth(26);
$sheetRules->getColumnDimension('C')->setWidth(24);
$sheetRules->getColumnDimension('D')->setWidth(10);
$sheetRules->getColumnDimension('E')->setWidth(50);
$sheetRules->getColumnDimension('F')->setWidth(40);
// Set active sheet back to Summary
$spreadsheet->setActiveSheetIndex(0);
$writer = new Xlsx($spreadsheet);
ob_start();
$writer->save('php://output');
return strval(ob_get_clean());
}
}
+10 -2
View File
@@ -92,6 +92,7 @@ class HtmlDashboardReporter
$explanation = '';
$fixedCode = '';
$explanation = '';
if ($aiSuggestion && str_contains($aiSuggestion, 'FIX:')) {
preg_match('/EXPLANATION:(.*)FIX:(.*)/s', $aiSuggestion, $matches);
$explanation = trim($matches[1] ?? '');
@@ -103,8 +104,15 @@ class HtmlDashboardReporter
$escapedSnippet = htmlspecialchars($v->htmlSnippet, ENT_QUOTES, 'UTF-8');
$escapedFixed = $fixedCode ? htmlspecialchars($fixedCode, ENT_QUOTES, 'UTF-8') : '';
$escapedExplanation = $explanation ? htmlspecialchars($explanation, ENT_QUOTES, 'UTF-8') : '';
$locationStr = $v->location ? htmlspecialchars($v->location['file'] . ':' . (string)$v->location['line'], ENT_QUOTES, 'UTF-8') : 'N/A';
$escapedExplanation = $explanation !== '' ? htmlspecialchars($explanation, ENT_QUOTES, 'UTF-8') : '';
$locationStr = 'N/A';
if ($v->location !== null) {
$filePart = $v->location['file'] ?? '';
$lineNum = (string)$v->location['line'];
$locText = $filePart !== '' ? $filePart . ':' . $lineNum : 'Line ' . $lineNum;
$locationStr = htmlspecialchars($locText, ENT_QUOTES, 'UTF-8');
}
$escapedRuleId = htmlspecialchars($v->ruleId, ENT_QUOTES, 'UTF-8');
$escapedMessage = htmlspecialchars($v->message, ENT_QUOTES, 'UTF-8');
+122
View File
@@ -0,0 +1,122 @@
<?php
namespace YakNet\AccessibilityConsole\Reporting;
use SimpleXMLElement;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\Violation;
class JunitFormatter implements FormatterInterface
{
/**
* @param Violation[] $violations
* @param int $baselinedCount
* @param SymfonyStyle $io
* @return int
*/
public function format(array $violations, int $baselinedCount, SymfonyStyle $io): int
{
$xml = $this->render($violations, $baselinedCount);
$io->write($xml);
return empty($violations) ? Command::SUCCESS : Command::FAILURE;
}
/**
* Render the violations in JUnit XML format.
*
* @param Violation[] $violations
* @param int $baselinedCount
* @return string
*/
public function render(array $violations, int $baselinedCount = 0): string
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$testsuites = $dom->createElement('testsuites');
$testsuites->setAttribute('name', 'YakNet Accessibility Console');
$testsuites->setAttribute('tests', (string)max(1, count($violations)));
$testsuites->setAttribute('failures', (string)count($violations));
$testsuites->setAttribute('errors', '0');
$testsuites->setAttribute('time', '0.000');
$dom->appendChild($testsuites);
if (empty($violations)) {
$testsuite = $dom->createElement('testsuite');
$testsuite->setAttribute('name', 'AccessibilityScan');
$testsuite->setAttribute('tests', '1');
$testsuite->setAttribute('failures', '0');
$testsuite->setAttribute('errors', '0');
$testsuite->setAttribute('time', '0.000');
$testcase = $dom->createElement('testcase');
$testcase->setAttribute('name', 'AccessibilityCompliant');
$testcase->setAttribute('classname', 'YakNet.AccessibilityConsole');
$testcase->setAttribute('time', '0.000');
$testsuite->appendChild($testcase);
$testsuites->appendChild($testsuite);
return (string)$dom->saveXML();
}
// Group violations by file
/** @var array<string, Violation[]> $grouped */
$grouped = [];
foreach ($violations as $v) {
$file = $v->location['file'] ?? 'unknown';
$grouped[$file][] = $v;
}
foreach ($grouped as $file => $fileViolations) {
$testsuite = $dom->createElement('testsuite');
$testsuite->setAttribute('name', str_replace('\\', '/', $file));
$testsuite->setAttribute('tests', (string)count($fileViolations));
$testsuite->setAttribute('failures', (string)count($fileViolations));
$testsuite->setAttribute('errors', '0');
$testsuite->setAttribute('time', '0.000');
foreach ($fileViolations as $v) {
$line = $v->location['line'] ?? 1;
$col = $v->location['column'] ?? 1;
$testcase = $dom->createElement('testcase');
$testcase->setAttribute('name', sprintf('[%s] %s', $v->ruleId, $v->message));
$testcase->setAttribute('classname', str_replace(['/', '\\'], '.', $file));
$testcase->setAttribute('time', '0.000');
$failure = $dom->createElement('failure');
$failure->setAttribute('type', $v->severity->value);
$failure->setAttribute('message', $v->message);
$details = sprintf(
"Rule: %s (%s)\nStandard: %s\nSeverity: %s\nLocation: %s:%d:%d\n\nSnippet:\n%s",
$v->ruleId,
$v->message,
$v->standard->value,
$v->severity->value,
$file,
$line,
$col,
$v->htmlSnippet
);
if ($v->fixSuggestion !== null && $v->fixSuggestion !== '') {
$details .= "\n\nSuggested Fix:\n" . $v->fixSuggestion;
}
$cdata = $dom->createCDATASection($details);
$failure->appendChild($cdata);
$testcase->appendChild($failure);
$testsuite->appendChild($testcase);
}
$testsuites->appendChild($testsuite);
}
return (string)$dom->saveXML();
}
}
+335
View File
@@ -0,0 +1,335 @@
<?php
namespace YakNet\AccessibilityConsole\Reporting;
use Dompdf\Dompdf;
use Dompdf\Options;
use YakNet\AccessibilityConsole\Analytics\ComplianceMatrixGenerator;
use YakNet\AccessibilityConsole\Core\Violation;
class PdfReportGenerator
{
/**
* Generate a detailed PDF Accessibility Audit & Conformance Report.
*
* @param array<string, mixed> $scanResult Scan result metrics, compliance matrix, and violations array
* @param string $targetUrl Target URL or file name audited
* @return string Raw PDF binary data
*/
public static function generatePdf(array $scanResult, string $targetUrl): string
{
if (!class_exists(Dompdf::class)) {
throw new \RuntimeException('To generate PDF certificates, please install dompdf via: composer require dompdf/dompdf');
}
date_default_timezone_set('Europe/Istanbul');
/** @var int $score */
$score = is_numeric($scanResult['score'] ?? null) ? intval($scanResult['score']) : 0;
/** @var array<int, array<string, mixed>> $violations */
$violations = is_array($scanResult['violations'] ?? null) ? $scanResult['violations'] : [];
$violationsCount = count($violations);
$dateStr = date('d.m.Y H:i:s');
$reportId = 'YAK-A11Y-' . date('Ymd') . '-' . strtoupper(substr(md5($targetUrl . date('Ymd')), 0, 6));
// Calculate severity counts
$criticalCount = 0;
$warningCount = 0;
$infoCount = 0;
foreach ($violations as $v) {
$rawSev = $v['severity'] ?? 'ERROR';
$sev = strtoupper(is_scalar($rawSev) ? (string)$rawSev : 'ERROR');
if ($sev === 'ERROR' || $sev === 'CRITICAL') {
$criticalCount++;
} elseif ($sev === 'WARNING' || $sev === 'WARN') {
$warningCount++;
} else {
$infoCount++;
}
}
// Compliance Matrix (Principles and Levels)
$rawMatrix = $scanResult['complianceMatrix'] ?? null;
/** @var array<string, mixed>|null $matrix */
$matrix = is_array($rawMatrix) ? $rawMatrix : null;
if (!$matrix) {
$gen = new ComplianceMatrixGenerator();
$pseudoViolations = [];
foreach ($violations as $v) {
$rawStd = $v['standard'] ?? 'WCAG 2.1 AA';
$stdStr = is_scalar($rawStd) ? (string)$rawStd : 'WCAG 2.1 AA';
$std = match($stdStr) {
'A' => \YakNet\AccessibilityConsole\Core\WCAGStandard::A,
'AAA' => \YakNet\AccessibilityConsole\Core\WCAGStandard::AAA,
default => \YakNet\AccessibilityConsole\Core\WCAGStandard::AA,
};
$rawRule = $v['ruleId'] ?? '';
$ruleId = is_scalar($rawRule) ? (string)$rawRule : '';
$rawDesc = $v['description'] ?? '';
$desc = is_scalar($rawDesc) ? (string)$rawDesc : '';
$rawLine = $v['line'] ?? 0;
$line = is_numeric($rawLine) ? (int)$rawLine : 0;
$rawSnippet = $v['htmlSnippet'] ?? '';
$snippet = is_scalar($rawSnippet) ? (string)$rawSnippet : '';
$pseudoViolations[] = new Violation(
ruleId: $ruleId,
message: $desc,
severity: \YakNet\AccessibilityConsole\Core\Severity::ERROR,
standard: $std,
location: ['line' => $line],
htmlSnippet: $snippet
);
}
$matrix = $gen->generate($pseudoViolations, max(1, count($violations)));
}
$scoreColor = $score >= 80 ? '#059669' : ($score >= 50 ? '#d97706' : '#dc2626');
$scoreBg = $score >= 80 ? '#ecfdf5' : ($score >= 50 ? '#fffbeb' : '#fef2f2');
$statusText = $score >= 80 ? 'WCAG 2.1 AA UYUMLU (PASS)' : ($score >= 50 ? 'KISMİ UYUMLU - İYİLEŞTİRME GEREKLİ' : 'UYUMSUZ - KRİTİK İHLALLER MEVCUT');
$rawPrinciples = (isset($matrix['principles']) && is_array($matrix['principles']))
? $matrix['principles']
: [
'Perceivable' => ['violations' => 0, 'status' => 'Pass'],
'Operable' => ['violations' => 0, 'status' => 'Pass'],
'Understandable' => ['violations' => 0, 'status' => 'Pass'],
'Robust' => ['violations' => 0, 'status' => 'Pass'],
];
$principleTrNames = [
'Perceivable' => '1. Algılanabilir (Perceivable)',
'Operable' => '2. Çalıştırılabilir (Operable)',
'Understandable' => '3. Anlaşılabilir (Understandable)',
'Robust' => '4. Sağlam (Robust)'
];
// Build Principles Table Rows
$principlesRowsHtml = '';
foreach ($rawPrinciples as $pKey => $pData) {
$pKeyStr = (string)$pKey;
$name = $principleTrNames[$pKeyStr] ?? $pKeyStr;
$vCount = (is_array($pData) && isset($pData['violations']) && is_numeric($pData['violations'])) ? (int)$pData['violations'] : 0;
$statusBadge = $vCount === 0
? "<span style='color:#059669; font-weight:bold;'>✓ Başarılı</span>"
: "<span style='color:#dc2626; font-weight:bold;'>⚠ {$vCount} İhlal</span>";
$principlesRowsHtml .= "
<tr>
<td style='padding:7px 10px; border-bottom:1px solid #e2e8f0; font-weight:600;'>{$name}</td>
<td style='padding:7px 10px; border-bottom:1px solid #e2e8f0; text-align:center;'>{$vCount}</td>
<td style='padding:7px 10px; border-bottom:1px solid #e2e8f0; text-align:center;'>{$statusBadge}</td>
</tr>";
}
// Build Violations Detailed Listing (All Violations)
$violationsHtml = '';
if ($violationsCount === 0) {
$violationsHtml = "
<div style='background:#ecfdf5; border:1px solid #a7f3d0; border-radius:6px; padding:16px; text-align:center; color:#065f46; margin-top:15px;'>
<div style='font-size:16px; font-weight:bold;'>🎉 Tebrikler! Hiçbir Erişilebilirlik İhlali Tespit Edilmedi</div>
<div style='font-size:11px; margin-top:4px;'>Bu web sayfası W3C WCAG 2.1 standartlarına tam uyumluluk göstermektedir.</div>
</div>";
} else {
foreach ($violations as $idx => $v) {
$num = $idx + 1;
$rawRule = $v['ruleId'] ?? '';
$ruleId = htmlspecialchars(is_scalar($rawRule) ? (string)$rawRule : '');
$rawDesc = $v['description'] ?? '';
$desc = htmlspecialchars(is_scalar($rawDesc) ? (string)$rawDesc : '');
$rawSnippet = $v['htmlSnippet'] ?? '';
$snippet = htmlspecialchars(is_scalar($rawSnippet) ? (string)$rawSnippet : '');
$rawSug = $v['suggestion'] ?? 'İlgili erişilebilirlik kuralını W3C standartlarına uygun olarak düzeltin.';
$suggestion = htmlspecialchars(is_scalar($rawSug) ? (string)$rawSug : '');
$rawStd = $v['standard'] ?? 'WCAG 2.1 AA';
$standard = htmlspecialchars(is_scalar($rawStd) ? (string)$rawStd : 'WCAG 2.1 AA');
$rawSev = $v['severity'] ?? 'ERROR';
$severity = strtoupper(is_scalar($rawSev) ? (string)$rawSev : 'ERROR');
$rawLine = $v['line'] ?? 0;
$line = is_numeric($rawLine) ? (int)$rawLine : 0;
$sevBadgeColor = ($severity === 'ERROR' || $severity === 'CRITICAL') ? '#dc2626' : '#d97706';
$sevBgColor = ($severity === 'ERROR' || $severity === 'CRITICAL') ? '#fef2f2' : '#fffbeb';
$sevText = ($severity === 'ERROR' || $severity === 'CRITICAL') ? 'KRİTİK HATA' : 'UYARI';
$violationsHtml .= "
<div style='page-break-inside:avoid; margin-bottom:12px; border:1px solid #e2e8f0; border-left:4px solid {$sevBadgeColor}; border-radius:4px; background:#ffffff;'>
<div style='padding:8px 12px; background:{$sevBgColor}; border-bottom:1px solid #e2e8f0;'>
<span style='font-weight:bold; color:#0f172a; font-size:11px;'>#{$num} [{$ruleId}]</span>
<span style='float:right;'>
<span style='background:#0f172a; color:#ffffff; padding:2px 6px; border-radius:3px; font-size:9px; font-weight:bold;'>{$standard}</span>
<span style='background:{$sevBadgeColor}; color:#ffffff; padding:2px 6px; border-radius:3px; font-size:9px; font-weight:bold;'>{$sevText}</span>
" . ($line > 0 ? "<span style='color:#64748b; font-size:9px; margin-left:6px;'>Satır: {$line}</span>" : "") . "
</span>
</div>
<div style='padding:10px 12px;'>
<div style='color:#1e293b; font-size:11px; margin-bottom:6px;'><b>İhlal Açıklaması:</b> {$desc}</div>
" . (!empty($snippet) ? "
<div style='background:#f8fafc; border:1px solid #cbd5e1; border-radius:3px; padding:6px 8px; font-family:monospace; font-size:9.5px; color:#be123c; margin-bottom:6px; word-wrap:break-word;'>
{$snippet}
</div>" : "") . "
<div style='color:#0f766e; font-size:10.5px; background:#f0fdfa; padding:6px 8px; border-radius:3px;'>
<b>💡 Çözüm ve Düzeltme Önerisi:</b> {$suggestion}
</div>
</div>
</div>";
}
}
$html = "
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>YakNet Erişilebilirlik Denetim Raporu</title>
<style>
@page { margin: 16mm 14mm 16mm 14mm; }
* { font-family: 'DejaVu Sans', sans-serif; box-sizing: border-box; }
body { color: #0f172a; line-height: 1.45; font-size: 10.5px; margin: 0; padding: 0; }
.header-table { width: 100%; border-collapse: collapse; border-bottom: 2px solid #0f172a; padding-bottom: 10px; margin-bottom: 14px; }
.brand-title { font-size: 16px; font-weight: bold; color: #0f172a; letter-spacing: 0.5px; }
.brand-sub { font-size: 9.5px; color: #475569; text-transform: uppercase; letter-spacing: 1px; margin-top: 2px; }
.report-meta { text-align: right; font-size: 9.5px; color: #475569; }
.scorecard-table { width: 100%; border-collapse: collapse; margin-bottom: 14px; }
.score-box { background: {$scoreBg}; border: 1.5px solid {$scoreColor}; border-radius: 6px; padding: 12px; text-align: center; }
.score-number { font-size: 34px; font-weight: bold; color: {$scoreColor}; line-height: 1; }
.score-status-badge { display: inline-block; background: {$scoreColor}; color: #ffffff; padding: 4px 12px; border-radius: 12px; font-weight: bold; font-size: 10.5px; margin-top: 6px; }
.info-table { width: 100%; border-collapse: collapse; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 6px; }
.info-table td { padding: 6px 10px; font-size: 10px; border-bottom: 1px solid #e2e8f0; }
.section-header { font-size: 12px; font-weight: bold; color: #0f172a; border-bottom: 1.5px solid #cbd5e1; padding-bottom: 4px; margin: 16px 0 10px 0; text-transform: uppercase; letter-spacing: 0.5px; }
.matrix-table { width: 100%; border-collapse: collapse; margin-bottom: 14px; }
.matrix-table th { background: #1e293b; color: #ffffff; padding: 7px 10px; font-size: 10px; font-weight: bold; text-align: left; }
.footer-table { width: 100%; border-collapse: collapse; border-top: 1px solid #cbd5e1; padding-top: 10px; margin-top: 20px; font-size: 8.5px; color: #64748b; }
.signature-box { border: 1px dashed #94a3b8; background: #f8fafc; border-radius: 4px; padding: 10px; text-align: center; margin-top: 15px; }
</style>
</head>
<body>
<!-- Başlık -->
<table class='header-table'>
<tr>
<td style='vertical-align:middle;'>
<div class='brand-title'>♿ YAKNET</div>
<div class='brand-sub'>Open-Source Accessibility Console • yak.net.tr</div>
</td>
<td class='report-meta' style='vertical-align:middle;'>
<div><b>Rapor Ref:</b> {$reportId}</div>
<div><b>Tarih:</b> {$dateStr}</div>
<div><b>Standart:</b> W3C WCAG 2.1 / 2.2 (Level AA)</div>
</td>
</tr>
</table>
<!-- Başlık -->
<div style='text-align:center; margin-bottom:14px;'>
<div style='font-size:15px; font-weight:bold; color:#0f172a; text-transform:uppercase;'>WEB ERİŞİLEBİLİRLİK DENETİM VE UYUMLULUK RAPORU</div>
<div style='font-size:9.5px; color:#64748b; margin-top:2px;'>W3C Web İçeriği Erişilebilirlik Kılavuzları (WCAG 2.1 &amp; 2.2) Uyarınca Hazırlanmıştır</div>
</div>
<!-- Skor ve Denetim Bilgisi Kartları -->
<table class='scorecard-table'>
<tr>
<td style='width:38%; vertical-align:top; padding-right:10px;'>
<div class='score-box'>
<div style='font-size:9.5px; font-weight:bold; color:#64748b; text-transform:uppercase;'>Genel Sağlık Skoru</div>
<div class='score-number'>{$score}<span style='font-size:16px; color:#64748b; font-weight:normal;'>/100</span></div>
<div class='score-status-badge'>{$statusText}</div>
</div>
</td>
<td style='width:62%; vertical-align:top;'>
<table class='info-table'>
<tr>
<td style='width:35%; font-weight:bold; color:#475569;'>Hedef URL / Adres:</td>
<td style='font-weight:bold; color:#0f172a; word-break:break-all;'>" . htmlspecialchars($targetUrl) . "</td>
</tr>
<tr>
<td style='font-weight:bold; color:#475569;'>Denetim Zamanı:</td>
<td>{$dateStr}</td>
</tr>
<tr>
<td style='font-weight:bold; color:#475569;'>Toplam İhlal Sayısı:</td>
<td><b>{$violationsCount}</b> Adet (Kritik: <b style='color:#dc2626;'>{$criticalCount}</b>, Uyarı: <b style='color:#d97706;'>{$warningCount}</b>)</td>
</tr>
<tr>
<td style='font-weight:bold; color:#475569;'>Denetim Motoru:</td>
<td>YakNet Accessibility Console v4.0</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- WCAG 4 Temel Prensip Uyumluluk Karnesi -->
<div class='section-header'>📊 WCAG 2.1 Dört Temel İlke ve Uyumluluk Karnesi</div>
<table class='matrix-table'>
<thead>
<tr>
<th style='width:60%;'>WCAG Temel İlkesi</th>
<th style='width:20%; text-align:center;'>İhlal Sayısı</th>
<th style='width:20%; text-align:center;'>Durum</th>
</tr>
</thead>
<tbody>
{$principlesRowsHtml}
</tbody>
</table>
<!-- Detaylı İhlal Listesi -->
<div class='section-header'>📋 Tespit Edilen Erişilebilirlik Bulguları ve Çözüm Planı ({$violationsCount} Kayıt)</div>
{$violationsHtml}
<!-- Doğrulama ve Rapor Özeti Bölümü -->
<div style='page-break-inside:avoid; margin-top:20px;'>
<div class='signature-box'>
<div style='font-weight:bold; font-size:10.5px; color:#0f172a;'>YAKNET ACCESSIBILITY CONSOLE — OTOMATİK DENETİM DOĞRULAMASI</div>
<div style='font-size:9px; color:#475569; margin:4px 0 8px 0;'>
Bu rapor, yukarıda belirtilen hedef için W3C Web Content Accessibility Guidelines (WCAG 2.1 / 2.2),
WAI-ARIA 1.2 ve EN 301 549 kılavuzlarına dayalı açık kaynaklı otomatik denetim sonucunu yansıtmaktadır.
</div>
<table style='width:100%; margin-top:8px;'>
<tr>
<td style='text-align:left; font-size:9px; color:#64748b;'>
<b>Doğrulama Özeti (SHA-256):</b> " . hash('sha256', $reportId . $targetUrl) . "<br>
<b>Organizasyon:</b> YakNet (Open Source)
</td>
<td style='text-align:right; font-size:9px;'>
<div style='font-weight:bold; color:#0f172a;'>YakNet Accessibility Console</div>
<div style='color:#059669; font-weight:bold;'>[ Otomatik Doğrulama Özeti Oluşturuldu ]</div>
</td>
</tr>
</table>
</div>
</div>
<!-- Alt Bilgi -->
<table class='footer-table'>
<tr>
<td style='text-align:left;'>
YakNet Accessibility Console • Açık Kaynak Erişilebilirlik Denetim Platformu • https://forum.yak.net.tr
</td>
<td style='text-align:right;'>
Belge No: {$reportId}
</td>
</tr>
</table>
</body>
</html>";
$options = new Options();
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);
$options->set('defaultFont', 'DejaVu Sans');
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
return strval($dompdf->output());
}
}
+155
View File
@@ -0,0 +1,155 @@
<?php
namespace YakNet\AccessibilityConsole\Reporting;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
class SarifFormatter implements FormatterInterface
{
/**
* @param Violation[] $violations
* @param int $baselinedCount
* @param SymfonyStyle $io
* @return int
*/
public function format(array $violations, int $baselinedCount, SymfonyStyle $io): int
{
$sarifJson = $this->render($violations, $baselinedCount);
$io->write($sarifJson);
return empty($violations) ? Command::SUCCESS : Command::FAILURE;
}
/**
* Render the violations in SARIF 2.1.0 JSON format.
*
* @param Violation[] $violations
* @param int $baselinedCount
* @return string
*/
public function render(array $violations, int $baselinedCount = 0): string
{
$rulesMap = [];
$results = [];
foreach ($violations as $v) {
$ruleId = $v->ruleId;
// Register rule metadata if not already present
if (!isset($rulesMap[$ruleId])) {
$rulesMap[$ruleId] = [
'id' => $ruleId,
'name' => $this->sanitizeRuleName($ruleId),
'shortDescription' => [
'text' => $v->message,
],
'fullDescription' => [
'text' => $v->message,
],
'defaultConfiguration' => [
'level' => $this->mapSeverityToSarifLevel($v->severity),
],
'properties' => [
'tags' => [
'accessibility',
'a11y',
'wcag',
'wcag-' . strtolower($v->standard->value),
],
],
];
}
// Location details
$file = $v->location['file'] ?? 'unknown';
$line = isset($v->location['line']) ? max(1, (int)$v->location['line']) : 1;
$column = isset($v->location['column']) ? max(1, (int)$v->location['column']) : 1;
/** @var array<string, mixed> $region */
$region = [
'startLine' => $line,
'startColumn' => $column,
];
if ($v->htmlSnippet !== '') {
$region['snippet'] = [
'text' => $v->htmlSnippet,
];
}
/** @var array<string, mixed> $locationEntry */
$locationEntry = [
'physicalLocation' => [
'artifactLocation' => [
'uri' => str_replace('\\', '/', $file),
],
'region' => $region,
],
];
/** @var array<string, mixed> $resultItem */
$resultItem = [
'ruleId' => $ruleId,
'level' => $this->mapSeverityToSarifLevel($v->severity),
'message' => [
'text' => $v->message,
],
'locations' => [
$locationEntry,
],
];
if ($v->fixSuggestion !== null && $v->fixSuggestion !== '') {
$resultItem['fixes'] = [
[
'description' => [
'text' => 'Suggested accessibility fix',
],
],
];
}
$results[] = $resultItem;
}
$sarif = [
'$schema' => 'https://json.schemastore.org/sarif-2.1.0.json',
'version' => '2.1.0',
'runs' => [
[
'tool' => [
'driver' => [
'name' => 'YakNet Accessibility Console',
'informationUri' => 'https://forum.yak.net.tr',
'semanticVersion' => '4.0.0',
'rules' => array_values($rulesMap),
],
],
'results' => $results,
],
],
];
return (string)json_encode($sarif, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
private function mapSeverityToSarifLevel(Severity $severity): string
{
return match ($severity) {
Severity::CRITICAL, Severity::ERROR => 'error',
Severity::WARNING => 'warning',
Severity::INFO => 'note',
};
}
private function sanitizeRuleName(string $ruleId): string
{
$cleaned = preg_replace('/^WCAG_\d+_\d+_\d+_?/', '', $ruleId);
$cleaned = is_string($cleaned) ? $cleaned : $ruleId;
$words = explode('_', strtolower($cleaned));
return implode('', array_map('ucfirst', $words));
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AbbreviationExpansion extends AbstractRule
{
public function getId(): string
{
return 'WCAG_3_1_4_ABBR_TITLE';
}
public function getDescription(): string
{
return '<abbr> elements must include a non-empty title attribute providing the expanded form of the abbreviation (WCAG 3.1.4).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AAA;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 5;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'abbr') {
return null;
}
$title = trim($element->getAttribute('title'));
if ($title === '') {
return $this->createViolation(
$element,
'<abbr> element is missing a non-empty title attribute to explain the abbreviation (WCAG 3.1.4 Abbreviations).',
'Add a title attribute with the full expansion (e.g., <abbr title="Web Content Accessibility Guidelines">WCAG</abbr>).'
);
}
return null;
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\AbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AccesskeyDuplicate extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_1_1_ACCESSKEY_DUPLICATE';
}
public function getDescription(): string
{
return 'accesskey attribute values must be unique across the document.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 2;
}
public function check(\DOMDocument $doc): array
{
$violations = [];
$xpath = new \DOMXPath($doc);
$elements = $xpath->query('//*[@accesskey]');
if ($elements === false || $elements->length === 0) {
return [];
}
$keys = [];
foreach ($elements as $el) {
if (!$el instanceof DOMElement) {
continue;
}
$val = trim($el->getAttribute('accesskey'));
if ($val === '') {
continue;
}
if (!isset($keys[$val])) {
$keys[$val] = [];
}
$keys[$val][] = $el;
}
foreach ($keys as $key => $elementsWithKey) {
if (count($elementsWithKey) > 1) {
foreach ($elementsWithKey as $el) {
$violations[] = $this->createViolation(
"Duplicate accesskey=\"{$key}\" found. Access keys must be unique across the document.",
$el,
"Assign a unique accesskey to each interactive element, or avoid using accesskey entirely."
);
}
}
}
return $violations;
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AllCapsLongText extends AbstractRule
{
public function getId(): string
{
return 'WCAG_3_1_5_ALL_CAPS_LONG';
}
public function getDescription(): string
{
return 'Avoid styling long passages of text (> 100 characters) in all-uppercase (text-transform: uppercase), which hinders readability for dyslexic users.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AAA;
}
public function getSeverity(): Severity
{
return Severity::INFO;
}
public function getLevel(): int
{
return 5;
}
public function check(DOMElement $element): ?Violation
{
$tag = strtolower($element->tagName);
if (!in_array($tag, ['p', 'div', 'span', 'li', 'blockquote', 'section', 'article'], true)) {
return null;
}
$style = $element->getAttribute('style');
if (!preg_match('/text-transform\s*:\s*uppercase\b/i', $style)) {
return null;
}
$text = trim((string)preg_replace('/\s+/', ' ', $element->textContent));
if (mb_strlen($text) > 100) {
return $this->createViolation(
$element,
sprintf('Long text block (%d characters) uses text-transform: uppercase, reducing reading speed and comprehension for dyslexic users.', mb_strlen($text)),
'Use normal sentence case for long text passages and reserve uppercase styling for short labels or headings.'
);
}
return null;
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AnchorMissingHref extends AbstractRule
{
public function getId(): string { return 'WCAG_4_1_2_ANCHOR_HREF'; }
public function getDescription(): string { return 'Anchor elements (<a>) acting as links must have a valid href attribute.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::WARNING; }
public function getLevel(): int { return 2; }
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'a') {
return null;
}
if ($element->hasAttribute('name') || $element->hasAttribute('role')) {
return null;
}
if (!$element->hasAttribute('href') || trim($element->getAttribute('href')) === '') {
return $this->createViolation(
$element,
$this->getDescription(),
'Add a valid href attribute to the <a> element, or use a <button> element if it triggers an action.'
);
}
return null;
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AppletBanned extends AbstractRule
{
public function getId(): string { return 'WCAG_4_1_2_APPLET_BANNED'; }
public function getDescription(): string { return 'The <applet> element is obsolete and non-accessible. Use modern HTML5 elements instead.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 1; }
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) === 'applet') {
return $this->createViolation(
$element,
$this->getDescription(),
'Remove the <applet> element and replace it with modern HTML5 or accessible media embeddings.'
);
}
return null;
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AreaAlt extends AbstractRule
{
public function getId(): string { return 'WCAG_1_1_1_AreaAlt'; }
public function getDescription(): string { return 'Checks that <area> elements in image maps have non-empty alt attributes.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 2; }
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'area') {
return null;
}
$alt = $element->getAttribute('alt');
$ariaLabel = $element->getAttribute('aria-label');
if (empty(trim($alt)) && empty(trim($ariaLabel))) {
return $this->createViolation(
$element,
'<area> öğesinde alt veya aria-label eksik.',
'Provide a non-empty alt or aria-label attribute for the <area> element.'
);
}
return null;
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaActivedescendantValid extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_ACTIVEDESCENDANT';
}
public function getDescription(): string
{
return 'The aria-activedescendant attribute must reference an existing element ID and be placed on a focusable composite widget.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
if (!$element->hasAttribute('aria-activedescendant')) {
return null;
}
$targetId = trim($element->getAttribute('aria-activedescendant'));
if ($targetId === '' || preg_match('/\{\{|\{%|<\?php/', $targetId)) {
return null;
}
$doc = $element->ownerDocument;
if ($doc === null) {
return null;
}
if (preg_match('/^[a-zA-Z0-9_\-:.]+$/', $targetId)) {
$xpath = new DOMXPath($doc);
$found = $xpath->query('//*[@id="' . $targetId . '"]');
if ($found !== false && $found->length === 0) {
return $this->createViolation(
$element,
sprintf('Attribute aria-activedescendant="%s" references a non-existent element ID.', $targetId),
sprintf('Ensure an element with id="%s" exists inside or is owned by this composite widget.', $targetId)
);
}
}
$tag = strtolower($element->tagName);
$nativelyFocusable = in_array($tag, ['input', 'select', 'textarea', 'button', 'a'], true);
$hasTabindex = $element->hasAttribute('tabindex');
if (!$nativelyFocusable && !$hasTabindex) {
return $this->createViolation(
$element,
sprintf('Element <%s> uses aria-activedescendant="%s" without being keyboard focusable (missing tabindex="0").', $tag, $targetId),
'Add tabindex="0" to the composite widget container so keyboard focus can manage the active descendant.'
);
}
return null;
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaBrailleEquivalent extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_BRAILLE';
}
public function getDescription(): string
{
return 'Elements with aria-braillelabel or aria-brailleroledescription must provide a standard accessible equivalent.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if ($element->hasAttribute('aria-braillelabel')) {
$hasName = false;
if ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '') {
$hasName = true;
} elseif ($element->hasAttribute('aria-labelledby') && trim($element->getAttribute('aria-labelledby')) !== '') {
$hasName = true;
} elseif ($element->hasAttribute('title') && trim($element->getAttribute('title')) !== '') {
$hasName = true;
} elseif ($element->hasAttribute('alt') && trim($element->getAttribute('alt')) !== '') {
$hasName = true;
} elseif (trim($element->textContent) !== '') {
$hasName = true;
}
if (!$hasName) {
return $this->createViolation(
$element,
"Element has aria-braillelabel but is missing a standard accessible name (aria-label, aria-labelledby, or text content).",
"Add a standard aria-label or aria-labelledby in addition to the aria-braillelabel."
);
}
}
if ($element->hasAttribute('aria-brailleroledescription')) {
if (!$element->hasAttribute('aria-roledescription') || trim($element->getAttribute('aria-roledescription')) === '') {
return $this->createViolation(
$element,
"Element has aria-brailleroledescription but is missing the standard aria-roledescription attribute.",
"Add an aria-roledescription attribute to accompany aria-brailleroledescription."
);
}
}
return null;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaBreadcrumbPattern extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_4_8_BREADCRUMB';
}
public function getDescription(): string
{
return 'Breadcrumb navigation landmarks must provide an accessible label (aria-label="Breadcrumb") and mark the current page with aria-current="page" (WCAG 2.4.8).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
$tag = strtolower($element->tagName);
if ($tag !== 'nav' && strtolower($element->getAttribute('role')) !== 'navigation') {
return null;
}
$classAndId = strtolower($element->getAttribute('class') . ' ' . $element->getAttribute('id'));
$ariaLabel = strtolower(trim($element->getAttribute('aria-label')));
$isBreadcrumb = str_contains($classAndId, 'breadcrumb') || str_contains($ariaLabel, 'breadcrumb');
if (!$isBreadcrumb) {
return null;
}
if ($ariaLabel === '' && trim($element->getAttribute('aria-labelledby')) === '') {
return $this->createViolation(
$element,
'Breadcrumb navigation landmark is missing an aria-label (e.g., aria-label="Breadcrumb").',
'Add aria-label="Breadcrumb" to the <nav> element.'
);
}
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new DOMXPath($doc);
$items = $xpath->query('.//li | .//a', $element);
if ($items !== false && $items->length >= 2) {
$current = $xpath->query('.//*[@aria-current="page"]', $element);
if ($current !== false && $current->length === 0) {
return $this->createViolation(
$element,
'Breadcrumb navigation does not mark the active page with aria-current="page" (WCAG 2.4.8 Location).',
'Add aria-current="page" to the last breadcrumb item representing the current page.'
);
}
}
}
return null;
}
}
+75
View File
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaComboboxPattern extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_COMBOBOX';
}
public function getDescription(): string
{
return 'Elements with role="combobox" must specify aria-expanded, aria-controls (or aria-owns), and an accessible name (WAI-ARIA 1.2).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower(trim($element->getAttribute('role'))) !== 'combobox') {
return null;
}
$missing = [];
if (!$element->hasAttribute('aria-expanded') || !in_array(strtolower(trim($element->getAttribute('aria-expanded'))), ['true', 'false'], true)) {
$missing[] = 'aria-expanded="true|false"';
}
$hasPopupRef = ($element->hasAttribute('aria-controls') && trim($element->getAttribute('aria-controls')) !== '')
|| ($element->hasAttribute('aria-owns') && trim($element->getAttribute('aria-owns')) !== '');
if (!$hasPopupRef) {
$missing[] = 'aria-controls="<popup-id>"';
}
$hasName = ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '')
|| ($element->hasAttribute('aria-labelledby') && trim($element->getAttribute('aria-labelledby')) !== '')
|| ($element->hasAttribute('title') && trim($element->getAttribute('title')) !== '')
|| ($element->hasAttribute('id') && trim($element->getAttribute('id')) !== '');
if (!$hasName) {
$missing[] = 'accessible name (aria-label / aria-labelledby / associated <label>)';
}
if (!empty($missing)) {
return $this->createViolation(
$element,
'Combobox widget (role="combobox") is missing required WAI-ARIA 1.2 properties: ' . implode(', ', $missing) . '.',
'Add aria-expanded="false", aria-controls="<listbox-id>", and an accessible name to the combobox element.'
);
}
return null;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaCurrentValid extends AbstractRule
{
/** @var array<int, string> */
private static array $validValues = [
'page', 'step', 'location', 'date', 'time', 'true', 'false'
];
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_CURRENT';
}
public function getDescription(): string
{
return 'The aria-current attribute must have a valid token value.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
if (!$element->hasAttribute('aria-current')) {
return null;
}
$value = strtolower(trim($element->getAttribute('aria-current')));
if (!in_array($value, self::$validValues, true)) {
$validList = implode(', ', self::$validValues);
return $this->createViolation(
$element,
"Invalid aria-current value \"{$value}\". Valid values are: {$validList}.",
"Set aria-current to one of the valid token values: page, step, location, date, time, true, or false."
);
}
return null;
}
}

Some files were not shown because too many files have changed in this diff Show More