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

This commit is contained in:
Enes Yakıştır
2026-11-21 09:48:29 +03:00
parent ef8ccb9f75
commit 5680882bee
114 changed files with 8875 additions and 325 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
+192 -152
View File
@@ -1,47 +1,53 @@
# YakNet Accessibility Console 3.3 (AI-Powered Static Analysis & WCAG 2.2 Linter)
# YakNet Accessibility Console 4.0
[![PHP Version](https://img.shields.io/badge/php-%5E8.2-blue.svg)](https://php.net)
[![PHPStan](https://img.shields.io/badge/PHPStan-Level%209-brightgreen.svg)](https://phpstan.org)
[![Tests](https://img.shields.io/badge/PHPUnit-230%20passed-success.svg)](https://phpunit.de)
[![Rules](https://img.shields.io/badge/WCAG%20Rules-130%20Active-purple.svg)](https://www.w3.org/WAI/standards-guidelines/wcag/)
[![Rules](https://img.shields.io/badge/WCAG%20%26%20ARIA%20Rules-175%20Active-purple.svg)](https://www.w3.org/WAI/standards-guidelines/wcag/)
[![Presets](https://img.shields.io/badge/Compliance%20Presets-11-teal.svg)](#-mevzuat-ve-sektörel-ön-ayarlar-presets)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![AI Powered](https://img.shields.io/badge/AI%20Self--Healing-Google%20Gemini-orange.svg)](https://ai.google.dev)
[![Open Source](https://img.shields.io/badge/Open%20Source-YakNet-orange.svg)](https://forum.yak.net.tr)
**YakNet Accessibility Console**, web projelerinizdeki erişilebilirlik (WCAG 2.1, 2.2 ve WAI-ARIA) ve HTML söz dizimi hatalarını statik olarak analiz eden, **130 benzersiz kural setiyle** denetleyen, kurumsal CI/CD kalite kapısı (Quality Gates) sunan ve **Yapay Zeka (Google Gemini AI) ile Çevrimdışı Deterministik Motor** desteğiyle kaynak kodunuzu otomatik tamir edebilen (Self-Healing) kurumsal düzeyde bir PHP statik analiz ve linter kütüphanesidir.
**YakNet Accessibility Console**, web uygulamalarındaki erişilebilirlik (WCAG 2.1, WCAG 2.2, WAI-ARIA 1.2, ARIA APG) ve HTML söz dizimi sorunlarını statik ve DOM tabanlı olarak analiz eden, **175 benzersiz kural**, **11 mevzuat/sektör uyumluluk profili**, **VPAT 2.5 (ACR) rapor üreticisi**, **politika yönetim motoru (Policy Engine)** ve **otomatik onarım (Offline & AI Self-Healing)** yetenekleri sunan açık kaynaklı bir PHP erişilebilirlik analiz platformudur.
PHPStan ve PHP-CS-Fixer esintili modern mimarisiyle; Laravel Blade (`.blade.php`), Twig (`.twig`), PHP (`.php`) ve standart HTML şablonlarınızı doğrudan tarar, baseline desteğiyle mevcut teknik borcu yönetir ve CI/CD pipeline süreçlerinize sıfır yapılandırmayla entegre olur.
**YakNet** tarafından açık kaynak topluluğu ve büyük ölçekli organizasyonların, kamu portallarının, üniversitelerin ve ürün ekiplerinin ortak standartlarla erişilebilir web yazılımları üretebilmesi için geliştirilmektedir.
Laravel Blade (`.blade.php`), Twig (`.twig`), **Vue SFC (`.vue`)**, **React JSX/TSX (`.jsx`, `.tsx`)**, PHP (`.php`) ve standart HTML şablonlarını doğrudan tarar; satır içi gizleme yönergelerini (`<!-- a11y-disable-next-line -->`), baseline yönetimini ve CI/CD kalite kapılarını sıfır ek kurulumla destekler.
---
## 🌟 Öne Çıkan Özellikler
- **🛡️ 130 Benzersiz WCAG 2.1 / 2.2 & WAI-ARIA Kuralı:** Algılanabilir (Perceivable), Çalıştırılabilir (Operable), Anlaşılabilir (Understandable) ve Sağlam (Robust) prensiplerine göre yapılandırılmış 5 kademeli kural havuzu. (Yeni: `LabelInName` WCAG 2.5.3, `RedundantEntry` WCAG 3.3.7, `TextSpacing` WCAG 1.4.12).
- **🏛️ Sektörel ve Mevzuat Ön Ayarları (Presets):** US Section 508, Avrupa Birliği EN 301 549 ve E-Ticaret (`--preset=section508|en301549|ecommerce`) profilleriyle hedeflenmiş standart denetimi.
- **🏷️ Dinamik SVG Rozet Üretimi (Badges):** Tarama tamamlandığında sağlık skoruna göre (yeşil/sarı/kırmızı) canlı SVG rozet (`--badge=public/a11y-badge.svg`) üretir.
- **📢 CI/CD Webhook Bildirimleri (Notifications):** Tarama sonuçlarını Slack ve Discord webhook kanallarına otomatik formatlanmış zengin mesajlarla iletir.
- **⚙️ Programatik Kural Denetleyicisi & İstatistikler:** `RuleController` ile DOM elementleri üzerinde doğrudan tekil kural yürütme ve `RuleExecutionStats` ile kural performans/yürütme süresi izleme.
- **⏱️ Gerçek Zamanlı İzleme Modu (`watch`):** Şablon dosyalarını (`.blade.php`, `.twig`, `.html`) arka planda izler, dosya kaydedildiğinde anında hızlı analiz yapıp konsolda canlı skor ve geri bildirim sunar.
- **🚦 CI/CD Kalite Kapısı Eşikleri (Quality Gates):** `--min-score=90`, `--max-warnings=5`, `--fail-on=error` seçenekleriyle pipeline süreçlerinde esnek kalite denetimi sağlar.
- **🔍 HTML & Şablon Söz Dizimi (Syntax/AST) Linter'ı:**
- Aynı etiket üzerinde yinelenen nitelikler (`Duplicate Attributes` - HTML5 3.2.4 ihlali)
- Kapanmamış veya çapraz kapanmış yapısal etiketler (`Mismatched / Unclosed Tags`)
- Void olmayan etiketlerde geçersiz self-closing kullanımı (`<div />`, `<span />`, `<p />`)
- Boşluksuz bitişik nitelik söz dizimi (`<a href="..."class="...">`)
- Kapanmamış HTML yorum blokları (`<!--`)
- **⚡ Tek Geçişli (Single-Pass) Yüksek Hızlı Kural Motoru:** DOM ağacını tek bir geçişte tarayarak büyük şablonlarda 5-10 kat daha hızlı analiz gerçekleştirir.
- **📝 1:1 Satır Eşlemeli Şablon Ön İşleyici (Template Preprocessor):** Blade direktiflerini (`@if`, `@foreach`, `@component`), Twig bloklarını (`{% %}`, `{{ }}`) ve PHP etiketlerini temizlerken satır sayılarını birebir korur.
- **🎯 Yüksek Hassasiyetli Satır & Sütun Bulucu (`PreciseElementLocator`):** Çok satırlı ve dinamik şablon bileşenlerinde ihlalin kaynak koddaki tam satır ve sütun numarasını saptar.
- **🤖 Yapay Zeka & Çevrimdışı Otomatik Onarım (Self-Healing):**
- **Çevrimdışı (Offline) Mod:** API anahtarı olmadan güvenli deterministik tamirler (`alt=""`, `aria-hidden="true"`, `rel="noopener noreferrer"`, `tabindex="0"`, `scope` temizliği vb.).
- **AI Destekli Mod:** Karmaşık şablon mantığı ve etiketler için Google Gemini AI ile akıllı tamir.
- **📊 Erişilebilirlik Analitiği & Uyumluluk Matrisi:** POUR prensipleri, WCAG A/AA/AAA başarı oranları ve KLOC başına hata yoğunluğu (Defect Density) istatistikleri.
- **🛡️ Baseline Desteği (`a11y-baseline.json`):** Mevcut hataları dondurarak CI/CD süreçlerinin yalnızca **yeni eklenen** hatalarda kırılmasını sağlar.
- **🔌 Zengin Çıktı & Rapor Formatları:**
- Konsol tablosu (`console`), JSON (`json`), GitHub Actions (`github`), GitLab SAST (`gitlab`)
- **OASIS SARIF 2.1.0 (`sarif`):** GitHub Code Scanning / Security Alerts ve VS Code SARIF uyumlu.
- **JUnit XML (`junit`):** Jenkins, GitLab CI, CircleCI, Bitbucket Pipelines uyumlu.
- **Çoklu Dışa Aktarım (`--report`):** HTML (`.html`), JSON (`.json`), SARIF (`.sarif`), JUnit (`.xml`), PDF (`.pdf`) ve Excel (`.xlsx`).
- **🏆 PHPStan Level 9 & %100 Tip Güvenliği:** Kod tabanı PHPStan en yüksek seviye (Level 9) ve 230 birim testi ile tam doğrulanmıştır.
- **🛡️ 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.
---
@@ -57,171 +63,204 @@ composer require --dev yaknet/accessibility-console
## 🚀 Komut Satırı (CLI) Kullanımı
### 1. Yapılandırma Dosyası Oluşturma (`init`)
Projenizin kök dizininde varsayılan bir `a11y.yaml` konfigürasyon dosyası oluşturur:
YakNet Accessibility Console **10 komut** sunar: `scan`, `fix`, `vpat`, `compare`, `rules`, `explain`, `presets`, `doctor`, `watch`, `init`.
### 1. Yapılandırma Oluşturma (`init`) ve Sistem Kontrolü (`doctor`)
```bash
# Kapsamlı varsayılan a11y.yaml dosyası oluşturur
bin/a11y init
# Ortam, 175 kural bütünlüğü ve entegrasyon durumunu doğrular
bin/a11y doctor
```
### 2. Projeyi veya Dizinleri Tarama (`scan`)
Yapılandırma dosyasındaki yollara göre tüm projeyi tarar:
### 2. Proje, Şablon veya Canlı URL Tarama (`scan`)
```bash
# a11y.yaml yapılandırmasına göre projeyi tara
bin/a11y scan
```
Belirli bir dizini veya şablon klasörünü hedef göstererek taramak için:
```bash
# Belirli bir dizini (Blade, Twig, Vue, JSX/TSX, HTML) tara
bin/a11y scan resources/views
bin/a11y scan templates/
```
Canlı bir web sitesini crawler desteğiyle taramak için:
```bash
bin/a11y scan https://siteniz.com --crawl
bin/a11y scan src/components
# Mevzuat / sektör ön ayarıyla tara ve VPAT 2.5 + SVG rozet üret
bin/a11y scan resources/views --preset=wcag22-aa --vpat=reports/vpat-2.5.md --badge=public/a11y.svg
# Performans profillemesi ve geçmiş kaydıyla tara
bin/a11y scan resources/views --profile --save-history=.a11y-history.json
# Canlı bir web sitesini crawler ve opsiyonel Headless Chrome ile tara
bin/a11y scan https://ornek.org --crawl --depth=3 --max-pages=25
```
### 3. CI/CD Kalite Kapısı Eşikleri (Quality Gates)
Pipeline süreçlerinde derlemenin kırılma şartlarını belirleyin:
### 3. VPAT 2.5 Uyumluluk Raporu Üretme (`vpat`)
```bash
# Sağlık skoru 90'ın altındaysa derlemeyi başarısız yap:
bin/a11y scan --min-score=90
# Markdown formatında VPAT 2.5 raporu üret
bin/a11y vpat resources/views --product="Açık Portal" --product-version="2.4.0" --output=VPAT-2.5.md
# En fazla 3 uyarıya izin ver:
bin/a11y scan --max-warnings=3
# Yalnızca kritik ve hata seviyesindeki ihlallerde kırıl (uyarıları göz ardı et):
bin/a11y scan --fail-on=error
# Bağımsız HTML veya JSON VPAT 2.5 raporu üret
bin/a11y vpat resources/views --format=html --output=reports/vpat.html
bin/a11y vpat resources/views --format=json --output=reports/vpat.json
```
### 4. Gerçek Zamanlı İzleme Modu (`watch`)
Geliştirme yaparken şablon dosyalarınızı izleyin ve dosya kaydedildiğinde anında otomatik re-scan çalıştırın:
### 4. Regresyon Karşılaştırması (`compare`)
PR veya sürüm öncesi iki tarama raporunu kıyaslayıp yeni eklenen ihlallerde derlemeyi durdurun:
```bash
bin/a11y watch resources/views
bin/a11y compare reports/before.json reports/after.json --fail-on-regression
```
### 5. Format ve Raporlama Seçenekleri
- **GitHub Code Scanning / SARIF 2.1.0 formatı:**
```bash
bin/a11y scan --format=sarif
```
- **JUnit XML formatı (Jenkins, GitLab CI):**
```bash
bin/a11y scan --format=junit
```
- **GitHub Actions bildirim formatı:**
```bash
bin/a11y scan --format=github
```
- **JSON formatında çıktı:**
```bash
bin/a11y scan --format=json
```
- **Çoklu Dışa Aktarım Formatları (`--report`):**
```bash
bin/a11y scan --report=rapor.html # İnteraktif HTML Dashboard
bin/a11y scan --report=rapor.pdf # PDF Sertifika ve Denetim Raporu
bin/a11y scan --report=rapor.xlsx # Microsoft Excel Çalışma Kitabı
bin/a11y scan --report=rapor.sarif # SARIF 2.1.0 Dosyası
bin/a11y scan --report=rapor.xml # JUnit XML Raporu
```
### 6. Mevzuat Ön Ayarları (`--preset`) ve Rozet Üretimi (`--badge`)
Mevzuat veya sektörel kurallara göre hedeflenmiş tarama yapın ve canlı SVG rozet oluşturun:
### 5. Kuralları Keşfetme (`rules`), Açıklama (`explain`) ve Ön Ayarlar (`presets`)
```bash
# US Section 508 federal uyumluluk profiliyle tara:
bin/a11y scan --preset=section508
# Avrupa Birliği EN 301 549 kamu web standardı profiliyle tara:
bin/a11y scan --preset=en301549
# E-Ticaret ödeme ve sepet akışları profiliyle tara:
bin/a11y scan --preset=ecommerce
# Tarama sonucunu SVG rozet olarak kaydet (README veya CI/CD artifact için):
bin/a11y scan --badge=public/badges/a11y.svg
```
### 7. Otomatik Düzeltme (`fix`)
Yapay zeka veya çevrimdışı yerel motor ile kaynak dosyalarınızı onarın:
```bash
# Gemini AI desteğiyle otomatik onarım:
bin/a11y fix
# Gemini API anahtarı olmadan tamamen çevrimdışı (offline) yerel motorla onarım:
bin/a11y fix --offline
# Dosyaları değiştirmeden yapılacak düzeltmeleri önizleme:
bin/a11y fix --offline --dry-run
```
### 8. Kuralları Listeleme ve Filtreleme (`rules`)
Kütüphanede tanımlı 130 kuralı listeleyin, arayın ve filtreleyin:
```bash
# Tüm kuralları listele:
# Tüm 175 kuralı listele
bin/a11y rules
# Kural adına veya açıklamasına göre ara:
bin/a11y rules --search=contrast
# POUR ilkesine, seviyeye veya çevrimdışı onarım desteğine göre filtrele
bin/a11y rules --principle=Operable --standard=AA
bin/a11y rules --healable
# Seviye ve standarda göre filtrele:
bin/a11y rules --standard=AA --level=3
# Belirli bir kuralın W3C rehberini ve kod örneklerini incele
bin/a11y explain WCAG_4_1_2_ARIA_TABLIST
# Tüm 11 mevzuat ve sektörel ön ayarı listele
bin/a11y presets
```
### 6. CI/CD Çıktı Formatları, Raporlar ve Bildirimler
```bash
bin/a11y scan --format=sarif --report=a11y.sarif
bin/a11y scan --format=checkstyle --report=a11y.checkstyle
bin/a11y scan --format=junit --report=a11y.xml
bin/a11y scan --report=rapor.html
bin/a11y scan --report=rapor.pdf
bin/a11y scan --report=rapor.xlsx
# Slack, Discord, Microsoft Teams veya genel webhook bildirimleri
bin/a11y scan --webhook-slack="$SLACK_WEBHOOK" --webhook-teams="$TEAMS_WEBHOOK"
```
### 7. Otomatik Onarım (`fix`) ve Canlı İzleme (`watch`)
```bash
# Çevrimdışı (API anahtarsız) deterministik onarım önizleme & uygulama
bin/a11y fix --offline --dry-run
bin/a11y fix --offline
# Gemini AI destekli onarım
bin/a11y fix
# Dosya değişikliklerini canlı izleme
bin/a11y watch resources/views
```
---
## ⚙️ Yapılandırma Dosyası (`a11y.yaml`)
## 🏛️ Mevzuat ve Sektörel Ön Ayarlar (Presets)
Projenizin ihtiyaçlarına göre `a11y.yaml` dosyasını özelleştirebilirsiniz:
| Ön Ayar (`--preset`) | Seviye | Kapsam |
| :--- | :---: | :--- |
| `wcag22-aa` | 4 | W3C WCAG 2.2 Level A & AA tam uyumluluk profili |
| `wcag22-aaa` | 5 | En katı W3C WCAG 2.2 Level AAA profili (tüm 175 kural) |
| `en301549` | 4 | Avrupa Birliği EN 301 549 kamu dijital erişilebilirlik standardı |
| `eaa2025` | 4 | European Accessibility Act (Direktif EU 2019/882) dijital hizmet profili |
| `section508` | 3 | ABD Revised Section 508 erişilebilirlik profili |
| `bitv2` | 5 | Almanya BITV 2.0 kamu erişilebilirlik standardı |
| `government` | 5 | Kamu portalları ve e-Devlet hizmetleri profili |
| `healthcare` | 5 | Sağlık ve hasta portalları profili (okunabilirlik ve hareket güvenliği odaklı) |
| `banking` | 4 | Dijital bankacılık ve finansal hizmetler profili |
| `education` | 4 | Üniversite, LMS ve akademik portallar (ADA Title II uyumlu) |
| `ecommerce` | 4 | E-Ticaret mağaza ve ödeme akışları profili |
---
## ⚙️ Yapılandırma (`a11y.yaml`) ve Politika Motoru
```yaml
# Tarama yapılacak dizin veya şablon yolları
paths:
- resources/views
- templates
- public/partials
- src/components
# Hariç tutulacak klasörler
exclude_paths:
- vendor
- node_modules
- storage
- tests/fixtures
- tests
# Kural Seviyesi (1: Kritik A -> 5: Kapsamlı AA/AAA)
level: 4
# Varsayılan çıktı formatı (console, json, github)
preset: wcag22-aa
format: console
# Baseline dosyası yolu
baseline: a11y-baseline.json
# Kural istisnaları ve özel kurallar
extensions:
- php
- html
- twig
- blade.php
- vue
- jsx
- tsx
# Organizasyon geneli yönetişim politikaları
policy:
min_score: 90
max_critical: 0
max_errors: 0
max_warnings: 10
required_standards:
- A
banned_rules:
- WCAG_1_1_1_ALT
- WCAG_2_3_1_FLASHING_CONTENT
severity_overrides:
WCAG_2_5_8_TARGET_SIZE: error
principle_limits:
Perceivable: 0
notifications:
slack_webhook: ""
discord_webhook: ""
teams_webhook: ""
webhook_url: ""
webhook_secret: ""
rules:
exclude:
- WCAG_1_3_1_FIELDSET # Belirli bir kuralı devre dışı bırak
- WCAG_1_3_1_FIELDSET
include:
- App\Rules\CustomBrandAccessibilityRule # Özel proje kuralı ekle
- App\Rules\CustomAccessibilityRule
```
---
## 📐 Kural Seviyeleri (Rule Levels)
## 🔇 Satır İçi Gizleme Yönergeleri (Inline Suppressions)
| Seviye | Adı | Kapsam | Örnek Kurallar |
| :--- | :--- | :--- | :--- |
| **Level 1** | Essential | Temel WCAG 2.1 A | `ImageAlt`, `ButtonName`, `HtmlHasLang`, `PageTitle` |
| **Level 2** | Standard | Standart WCAG 2.1/2.2 A & Söz Dizimi | `HtmlSyntaxValid`, `FormLabel`, `HeadingOrder`, `TrackValidation` |
| **Level 3** | Enhanced | Gelişmiş WAI-ARIA & Formlar | `DuplicateId`, `NestedInteractive`, `AriaCurrentValid`, `AccessibleAuth` |
| **Level 4** | Advanced | Kapsamlı WCAG 2.2 AA & UX | `TargetSizeMinimum`, `DraggingMovements`, `FocusNotObscured`, `ColorContrast` |
| **Level 5** | Strict | Çok Katı AAA & Best Practices | `FocusTrapping`, `ColorBlindnessContrast`, `NoFocusOutline` |
İstisnai durumlarda belirli satır veya bloklarda kuralı gerekçesiyle birlikte gizleyebilirsiniz; tüm gizlemeler denetim kaydına alınır:
```html
<!-- 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 -->
```
---
## 🔐 Yapay Zeka (AI) API Yapılandırması
## 🧩 PHP Programatik API
AI Self-Healing ve otomatik kod onarım özelliklerini kullanabilmek için projenizin kök dizinindeki `.env` dosyasına **Google Gemini API** anahtarınızı ekleyin:
```php
// 1. Hızlı tarama ve skor hesaplama
$violations = a11y_scan($html, level: 4);
$score = a11y_score($html, level: 4);
```env
GEMINI_API_KEY=AIzaSyA...your_api_key_here
// 2. Mevzuat ön ayarıyla tarama
$govViolations = a11y_scan_preset($html, 'government');
// 3. VPAT 2.5 raporu ve POUR uyumluluk matrisi üretme
$vpatMarkdown = a11y_vpat($html, format: 'markdown', productName: 'YakNet Portal');
$matrix = a11y_compliance_matrix($html, level: 5);
// 4. Çevrimdışı deterministik hızlı onarım
$fixedHtml = a11y_quick_fix($html);
```
---
@@ -240,14 +279,15 @@ vendor/bin/phpstan analyse -l 9 src/
## 🤝 Katkıda Bulunma
1. Bu depoyu forklayın (`fork`).
2. Yeni bir özellik dalı açın (`git checkout -b feature/harika-kural`).
3. Değişikliklerinizi commit edin (`git commit -m 'feat: Yeni WCAG kuralı eklendi'`).
4. Dalınıza push yapın (`git push origin feature/harika-kural`).
5. Bir **Pull Request** açın.
Bu proje açık kaynaklıdır ve her türlü katkıya açıktır:
1. Depoyu forklayın (`fork`).
2. Yeni bir özellik dalı açın (`git checkout -b feature/yeni-kural`).
3. Değişikliklerinizi ve testlerinizi ekleyin (`vendor/bin/phpunit` ve `vendor/bin/phpstan analyse -l 9 src/` ile doğrulayın).
4. Bir **Pull Request** açın.
---
## 📜 Lisans
Bu proje **YakNet Bilişim** tarafından geliştirilmiştir ve **MIT Lisansı** altında lisanslanmıştır. Detaylar için [LICENSE](LICENSE) dosyasına göz atabilirsiniz.
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.
+12 -2
View File
@@ -12,14 +12,19 @@ if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
use Symfony\Component\Console\Application;
use YakNet\AccessibilityConsole\Core\Container\ContainerFactory;
use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\CompareCommand;
use YakNet\AccessibilityConsole\Console\Command\DoctorCommand;
use YakNet\AccessibilityConsole\Console\Command\ExplainCommand;
use YakNet\AccessibilityConsole\Console\Command\FixCommand;
use YakNet\AccessibilityConsole\Console\Command\InitCommand;
use YakNet\AccessibilityConsole\Console\Command\PresetsCommand;
use YakNet\AccessibilityConsole\Console\Command\RulesCommand;
use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\VpatCommand;
use YakNet\AccessibilityConsole\Console\Command\WatchCommand;
$container = ContainerFactory::create();
$application = new Application('YakNet Accessibility Console', '3.3.0');
$application = new Application('YakNet Accessibility Console', '4.0.0');
// Add commands resolved via DI Container
$application->addCommand($container->get(ScanCommand::class));
@@ -27,5 +32,10 @@ $application->addCommand($container->get(FixCommand::class));
$application->addCommand($container->get(InitCommand::class));
$application->addCommand($container->get(RulesCommand::class));
$application->addCommand($container->get(WatchCommand::class));
$application->addCommand($container->get(VpatCommand::class));
$application->addCommand($container->get(CompareCommand::class));
$application->addCommand($container->get(DoctorCommand::class));
$application->addCommand($container->get(ExplainCommand::class));
$application->addCommand($container->get(PresetsCommand::class));
$application->run();
+11 -5
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.3.0",
"version": "4.0.0",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "YakNet Bilişim",
"name": "YakNet",
"email": "[email protected]",
"role": "Developer"
"role": "Organization"
}
],
"require": {
+3 -3
View File
@@ -18,10 +18,10 @@
<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 Engine</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">v3.2 Enterprise</span>
<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 İzleyici</p>
<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">
+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();
}
}
+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();
}
}
+5 -1
View File
@@ -26,7 +26,7 @@ class ComplianceMatrixGenerator
* levels: array<string, array{violations: int, percentage: float}>
* }
*/
public function generate(array $violations, int $totalActiveRules = 127): array
public function generate(array $violations, int $totalActiveRules = 175): array
{
$principles = [
'Perceivable' => ['violations' => 0, 'status' => 'Pass'],
@@ -47,6 +47,10 @@ class ComplianceMatrixGenerator
$principleNumber = 4;
if (preg_match('/WCAG_([1-4])_/', $v->ruleId, $m)) {
$principleNumber = (int)$m[1];
} elseif (in_array($v->ruleId, ['HeadingOrder', 'BannedSelectors', 'A11Y_VIEWPORT', 'WCAG_FONT_TAG_BANNED'], true)) {
$principleNumber = 1;
} elseif (in_array($v->ruleId, ['AccesskeyDuplicate', 'WCAG_LINK_TARGET_BLANK'], true)) {
$principleNumber = 2;
}
$pName = self::$principleMap[$principleNumber] ?? 'Robust';
$principles[$pName]['violations']++;
+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);
}
}
+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,
];
}
}
+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;
}
}
+2 -2
View File
@@ -151,7 +151,7 @@ class FixCommand extends Command
continue;
}
if (is_string($rawSuggestion) && $suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
if ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
$io->writeln("<fg=red>Skipped (AI could not generate a clean fix)</>");
continue;
}
@@ -278,7 +278,7 @@ class FixCommand extends Command
continue;
}
if (is_string($rawSuggestion) && $suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
if ($suggestion === $rawSuggestion && str_contains($suggestion, 'EXPLANATION:')) {
$io->writeln("<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;
}
}
+33 -5
View File
@@ -7,6 +7,7 @@ use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\SelfHealing\LocalHealer;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
use Symfony\Component\Console\Input\InputOption;
@@ -21,7 +22,9 @@ class RulesCommand extends Command
->addOption('search', 's', InputOption::VALUE_REQUIRED, 'Search rules by ID or description')
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Filter rules by maximum level (1-5)')
->addOption('standard', null, InputOption::VALUE_REQUIRED, 'Filter rules by standard (A, AA, AAA)')
->addOption('severity', null, InputOption::VALUE_REQUIRED, 'Filter rules by severity (error, warning, info)');
->addOption('severity', null, InputOption::VALUE_REQUIRED, 'Filter rules by severity (critical, error, warning, info)')
->addOption('principle', null, InputOption::VALUE_REQUIRED, 'Filter rules by POUR principle (Perceivable, Operable, Understandable, Robust)')
->addOption('healable', null, InputOption::VALUE_NONE, 'Show only rules with deterministic offline auto-fix support');
}
protected function execute(InputInterface $input, OutputInterface $output): int
@@ -33,6 +36,9 @@ class RulesCommand extends Command
$levelFilter = $input->getOption('level');
$standardFilter = $input->getOption('standard');
$severityFilter = $input->getOption('severity');
$principleFilter = $input->getOption('principle');
$healableOnly = (bool)$input->getOption('healable');
$healableIds = LocalHealer::getSupportedRuleIds();
$maxLevel = is_numeric($levelFilter) ? (int)$levelFilter : 9;
$rules = RuleLevels::getRulesForLevel($maxLevel);
@@ -42,9 +48,7 @@ class RulesCommand extends Command
$matchedCount = 0;
foreach ($rules as $rule) {
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
: (new \ReflectionClass($rule))->getShortName();
$ruleId = $rule->getId();
$description = method_exists($rule, 'getDescription') ? $rule->getDescription() : '';
$standard = method_exists($rule, 'getStandard') ? $rule->getStandard()->value : '';
@@ -72,6 +76,27 @@ class RulesCommand extends Command
continue;
}
}
// Principle filter
if (is_string($principleFilter) && $principleFilter !== '') {
$rulePrinciple = 'Robust';
if (preg_match('/WCAG_([1-4])_/', $ruleId, $m)) {
$rulePrinciple = match ((int)$m[1]) {
1 => 'Perceivable',
2 => 'Operable',
3 => 'Understandable',
default => 'Robust',
};
}
if (strcasecmp($rulePrinciple, $principleFilter) !== 0) {
continue;
}
}
// Healable filter
if ($healableOnly && !in_array($ruleId, $healableIds, true)) {
continue;
}
$table->addRow([
"<fg=cyan;options=bold>$ruleId</>",
@@ -86,7 +111,10 @@ class RulesCommand extends Command
$table->render();
$io->newLine();
if (is_string($searchQuery) || $levelFilter !== null || is_string($standardFilter) || is_string($severityFilter)) {
$hasFilter = is_string($searchQuery) || $levelFilter !== null || is_string($standardFilter)
|| is_string($severityFilter) || is_string($principleFilter) || $healableOnly;
if ($hasFilter) {
$io->note(sprintf("Showing %d matching rules (out of %d total rules).", $matchedCount, count(RuleLevels::getRulesForLevel(9))));
} else {
$io->note("Total rules available: " . count($rules));
+215 -15
View File
@@ -10,12 +10,24 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\AI\GeminiFixer;
use YakNet\AccessibilityConsole\Analytics\HistoryTracker;
use YakNet\AccessibilityConsole\Cache\ScanCache;
use YakNet\AccessibilityConsole\Compliance\VpatReportGenerator;
use YakNet\AccessibilityConsole\Core\Analyser;
use YakNet\AccessibilityConsole\Core\BaselineManager;
use YakNet\AccessibilityConsole\Core\Config;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Notifications\DiscordNotifier;
use YakNet\AccessibilityConsole\Notifications\GenericWebhookNotifier;
use YakNet\AccessibilityConsole\Notifications\MicrosoftTeamsNotifier;
use YakNet\AccessibilityConsole\Notifications\NotificationDispatcher;
use YakNet\AccessibilityConsole\Notifications\NotificationPayload;
use YakNet\AccessibilityConsole\Notifications\SlackNotifier;
use YakNet\AccessibilityConsole\Policy\PolicyEngine;
use YakNet\AccessibilityConsole\Rules\RuleExecutionStats;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
use YakNet\AccessibilityConsole\Reporting\CheckstyleFormatter;
use YakNet\AccessibilityConsole\Reporting\ConsoleFormatter;
use YakNet\AccessibilityConsole\Reporting\GithubFormatter;
use YakNet\AccessibilityConsole\Reporting\JsonFormatter;
@@ -42,8 +54,8 @@ class ScanCommand extends Command
->addArgument('target', InputArgument::OPTIONAL, 'The URL, file, or directory path to scan')
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to the configuration file (default: a11y.yaml)')
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-9)')
->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Use a pre-configured audit profile (section508, en301549, ecommerce)')
->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (console, json, github, xml, markdown, csv, gitlab, sarif, junit)')
->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Use a compliance preset (section508, en301549, eaa2025, bitv2, wcag22-aa, wcag22-aaa, government, healthcare, banking, education, ecommerce)')
->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (console, json, github, xml, markdown, csv, gitlab, sarif, junit, checkstyle)')
->addOption('min-score', null, InputOption::VALUE_REQUIRED, 'Minimum required accessibility health score (0-100) to pass the quality gate')
->addOption('max-warnings', null, InputOption::VALUE_REQUIRED, 'Maximum allowed warnings before failing the quality gate')
->addOption('fail-on', null, InputOption::VALUE_REQUIRED, 'Minimum severity to fail on (error, warning, info)')
@@ -51,7 +63,16 @@ class ScanCommand extends Command
->addOption('baseline', null, InputOption::VALUE_REQUIRED, 'Path to the baseline file')
->addOption('no-progress', null, InputOption::VALUE_NONE, 'Disable progress bar')
->addOption('ai', null, InputOption::VALUE_NONE, 'Enable AI-powered fix suggestions')
->addOption('report', null, InputOption::VALUE_REQUIRED, 'Save report to file (html, json, sarif, xml, junit, pdf, xlsx)')
->addOption('report', null, InputOption::VALUE_REQUIRED, 'Save report to file (html, json, sarif, xml, junit, checkstyle, pdf, xlsx)')
->addOption('vpat', null, InputOption::VALUE_REQUIRED, 'Export a VPAT 2.5 Conformance Report to file (.md, .html, or .json)')
->addOption('save-history', null, InputOption::VALUE_REQUIRED, 'Append scan snapshot to a JSON history file for trend tracking')
->addOption('cache', null, InputOption::VALUE_REQUIRED, 'Path to incremental content-hash cache file (e.g. .a11y-cache.json)')
->addOption('clear-cache', null, InputOption::VALUE_NONE, 'Clear the incremental scan cache before scanning')
->addOption('profile', null, InputOption::VALUE_NONE, 'Display rule execution timing profile (top slowest rules)')
->addOption('webhook-slack', null, InputOption::VALUE_REQUIRED, 'Send scan summary to a Slack Incoming Webhook URL')
->addOption('webhook-discord', null, InputOption::VALUE_REQUIRED, 'Send scan summary to a Discord Webhook URL')
->addOption('webhook-teams', null, InputOption::VALUE_REQUIRED, 'Send scan summary to a Microsoft Teams Webhook URL')
->addOption('webhook-url', null, InputOption::VALUE_REQUIRED, 'Send JSON payload to a generic webhook URL')
->addOption('badge', null, InputOption::VALUE_REQUIRED, 'Save SVG accessibility health badge to file (e.g. a11y-badge.svg)')
->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping (URL scans only)')
->addOption('crawl', null, InputOption::VALUE_NONE, 'Crawl internal links recursively (URL scans only)')
@@ -74,14 +95,15 @@ class ScanCommand extends Command
$level = is_numeric($levelOption) ? (int)$levelOption : $config->getLevel();
$presetOption = $input->getOption('preset');
$presetName = (is_string($presetOption) && $presetOption !== '') ? $presetOption : $config->getPreset();
$activePreset = null;
if (is_string($presetOption) && $presetOption !== '') {
if (is_string($presetName) && $presetName !== '') {
$presetRegistry = new PresetRegistry();
$activePreset = $presetRegistry->get($presetOption);
$activePreset = $presetRegistry->get($presetName);
if ($activePreset !== null) {
$level = $activePreset->getLevel();
} else {
$io->warning("Preset '{$presetOption}' not found. Using default rules.");
$io->warning("Preset '{$presetName}' not found. Using default rules.");
}
}
@@ -120,30 +142,53 @@ class ScanCommand extends Command
// Setup Analyser
$scanner = new Scanner();
$enableProfile = (bool)$input->getOption('profile');
$executionStats = $enableProfile ? new RuleExecutionStats() : null;
if ($executionStats !== null) {
$scanner->getEngine()->setStats($executionStats);
}
$rules = RuleLevels::getRulesForLevel($level);
// Filter rules based on config
// Filter rules based on config and active preset
$rulesConfig = $config->getRulesConfig();
$excludedIds = $rulesConfig['exclude'];
if ($activePreset !== null) {
$excludedIds = array_values(array_unique(array_merge($excludedIds, $activePreset->getExcludedRules())));
}
$activeRules = [];
foreach ($rules as $rule) {
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
: (new \ReflectionClass($rule))->getShortName();
$ruleId = $rule->getId();
if (in_array($ruleId, $rulesConfig['exclude'], true)) {
if (in_array($ruleId, $excludedIds, true)) {
continue;
}
$activeRules[$ruleId] = $rule;
}
// Ensure preset-included priority rules are active even if they belong to a higher scan level
if ($activePreset !== null && !empty($activePreset->getIncludedRules())) {
$allRulesById = [];
foreach (RuleLevels::getRulesForLevel(9) as $candidateRule) {
$cid = $candidateRule->getId();
$allRulesById[$cid] = $candidateRule;
}
foreach ($activePreset->getIncludedRules() as $priorityRuleId) {
if (!isset($activeRules[$priorityRuleId]) && isset($allRulesById[$priorityRuleId]) && !in_array($priorityRuleId, $excludedIds, true)) {
$activeRules[$priorityRuleId] = $allRulesById[$priorityRuleId];
}
}
}
foreach ($rulesConfig['include'] as $customRuleClass) {
if (class_exists($customRuleClass)) {
try {
$reflection = new \ReflectionClass($customRuleClass);
if ($reflection->isInstantiable()) {
$rule = $reflection->newInstance();
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
$ruleId = method_exists($rule, 'getId')
? $rule->getId()
: $reflection->getShortName();
$activeRules[$ruleId] = $rule;
}
@@ -161,7 +206,20 @@ class ScanCommand extends Command
$baselineManager->load(getcwd() . '/' . $baselinePath);
}
$analyser = new Analyser($config, $scanner, $baselineManager);
// Setup Incremental Scan Cache (if --cache is passed)
$scanCache = null;
$cachePathOption = $input->getOption('cache');
if (is_string($cachePathOption) && $cachePathOption !== '') {
$rulesSig = hash('sha256', implode('|', array_keys($activeRules)));
$scanCache = new ScanCache($cachePathOption, $rulesSig);
if ($input->getOption('clear-cache')) {
$scanCache->clear();
} else {
$scanCache->load();
}
}
$analyser = new Analyser($config, $scanner, $baselineManager, null, null, null, $scanCache);
// Progress bar setup
$progressBar = null;
@@ -229,6 +287,10 @@ class ScanCommand extends Command
}
}
// Apply governance policy severity overrides before formatting & scoring
$policyEngine = new PolicyEngine($config->getPolicyConfig());
$policyEngine->applySeverityOverrides($violations);
// Select formatter
$formatter = new ConsoleFormatter();
if ($format === 'json') {
@@ -247,12 +309,15 @@ class ScanCommand extends Command
$formatter = new SarifFormatter();
} elseif ($format === 'junit') {
$formatter = new JunitFormatter();
} elseif ($format === 'checkstyle') {
$formatter = new CheckstyleFormatter();
}
$exitCode = $formatter->format($violations, $baselinedCount, $io);
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
$score = $metrics['score'];
$suppressedLog = $analyser->getSuppressedAuditLog();
if ($format === 'console') {
$io->section("Accessibility Ratings");
@@ -261,10 +326,34 @@ class ScanCommand extends Command
$io->writeln(sprintf(" - Screen Reader / Visual Impact: <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();
}
// Quality Gate evaluation
// Execution profiling summary (--profile)
if ($executionStats !== null && $format === 'console') {
$slowest = $executionStats->getSlowestRules(10);
if (!empty($slowest)) {
$io->section('Rule Execution Profile (Top 10 Slowest)');
$profileTable = new \Symfony\Component\Console\Helper\Table($output);
$profileTable->setHeaders(['Rule ID', 'Invocations', 'Total (ms)', 'Avg (ms)', 'Violations']);
foreach ($slowest as $rId => $stat) {
$profileTable->addRow([
$rId,
(string)$stat['invocations'],
sprintf('%.3f', $stat['total_time_ms']),
sprintf('%.4f', $stat['avg_time_ms']),
(string)$stat['violations'],
]);
}
$profileTable->render();
$io->newLine();
}
}
// Quality Gate & Policy Engine evaluation
$minScoreOption = $input->getOption('min-score');
$maxWarningsOption = $input->getOption('max-warnings');
$failOnOption = $input->getOption('fail-on');
@@ -283,6 +372,14 @@ class ScanCommand extends Command
/** @var string[] $gateFailures */
$gateFailures = [];
if ($policyEngine->hasPolicies()) {
$policyResult = $policyEngine->evaluate($violations);
if (!$policyResult->passed) {
$qualityGateFailed = true;
$gateFailures = array_merge($gateFailures, $policyResult->failures);
}
}
if ($minScoreOption !== null && is_numeric($minScoreOption)) {
$minScore = (int)$minScoreOption;
if ($score < $minScore) {
@@ -320,6 +417,32 @@ class ScanCommand extends Command
$this->exportReport($reportPath, $violations, 'Static Analysis', $io);
}
// Export VPAT 2.5 report if --vpat is specified
$vpatPath = $input->getOption('vpat');
if (is_string($vpatPath) && $vpatPath !== '') {
$vpatGenerator = new VpatReportGenerator();
$vpatExt = strtolower(pathinfo($vpatPath, PATHINFO_EXTENSION));
$vpatContent = match ($vpatExt) {
'html', 'htm' => $vpatGenerator->renderHtml($violations, basename((string)getcwd()) ?: 'Web Application'),
'json' => $vpatGenerator->renderJson($violations, basename((string)getcwd()) ?: 'Web Application'),
default => $vpatGenerator->renderMarkdown($violations, basename((string)getcwd()) ?: 'Web Application'),
};
file_put_contents($vpatPath, $vpatContent);
$io->success("VPAT 2.5 Conformance Report saved to: $vpatPath");
}
// Save history snapshot if --save-history is specified
$historyPath = $input->getOption('save-history');
if (is_string($historyPath) && $historyPath !== '') {
$tracker = new HistoryTracker();
$tracker->record($violations, $historyPath, implode(', ', $paths), $activePreset?->getName());
$trend = $tracker->computeTrend($tracker->load($historyPath));
if ($format === 'console') {
$deltaStr = $trend['score_delta'] > 0 ? '+' . $trend['score_delta'] : (string)$trend['score_delta'];
$io->note(sprintf('History saved (%d total runs, trend: %s, delta: %s).', $trend['runs'], $trend['trend'], $deltaStr));
}
}
// Export SVG badge if --badge is specified
$badgePath = $input->getOption('badge');
if (is_string($badgePath) && $badgePath !== '') {
@@ -327,6 +450,9 @@ class ScanCommand extends Command
$io->success("SVG Badge saved to: $badgePath");
}
// Dispatch webhook notifications (CLI flags or a11y.yaml notifications block)
$this->dispatchNotifications($input, $config, implode(', ', $paths), $score, $violations, $errorCount, $warningCount);
return $exitCode;
}
@@ -561,6 +687,9 @@ class ScanCommand extends Command
} elseif ($extension === 'sarif') {
$sarifFormatter = new SarifFormatter();
file_put_contents($reportPath, $sarifFormatter->render($violations));
} elseif ($extension === 'checkstyle') {
$checkstyleFormatter = new CheckstyleFormatter();
file_put_contents($reportPath, $checkstyleFormatter->render($violations));
} elseif ($extension === 'xml' || $extension === 'junit') {
$junitFormatter = new JunitFormatter();
file_put_contents($reportPath, $junitFormatter->render($violations));
@@ -594,5 +723,76 @@ class ScanCommand extends Command
$io->success("Report saved to: $reportPath");
}
/**
* Dispatch configured webhook notifications (Slack, Discord, Microsoft Teams, generic JSON webhook).
*
* @param \YakNet\AccessibilityConsole\Core\Violation[] $violations
*/
private function dispatchNotifications(
InputInterface $input,
Config $config,
string $target,
int $score,
array $violations,
int $errorCount,
int $warningCount
): void {
$notifConfig = $config->getNotificationsConfig();
$dispatcher = new NotificationDispatcher();
$slackUrl = $input->getOption('webhook-slack');
if (!is_string($slackUrl) || $slackUrl === '') {
$slackUrl = is_string($notifConfig['slack_webhook'] ?? null) ? $notifConfig['slack_webhook'] : '';
}
if ($slackUrl !== '') {
$dispatcher->addNotifier('slack', new SlackNotifier($slackUrl));
}
$discordUrl = $input->getOption('webhook-discord');
if (!is_string($discordUrl) || $discordUrl === '') {
$discordUrl = is_string($notifConfig['discord_webhook'] ?? null) ? $notifConfig['discord_webhook'] : '';
}
if ($discordUrl !== '') {
$dispatcher->addNotifier('discord', new DiscordNotifier($discordUrl));
}
$teamsUrl = $input->getOption('webhook-teams');
if (!is_string($teamsUrl) || $teamsUrl === '') {
$teamsUrl = is_string($notifConfig['teams_webhook'] ?? null) ? $notifConfig['teams_webhook'] : '';
}
if ($teamsUrl !== '') {
$dispatcher->addNotifier('teams', new MicrosoftTeamsNotifier($teamsUrl));
}
$genericUrl = $input->getOption('webhook-url');
if (!is_string($genericUrl) || $genericUrl === '') {
$genericUrl = is_string($notifConfig['webhook_url'] ?? null) ? $notifConfig['webhook_url'] : '';
}
$secret = is_string($notifConfig['webhook_secret'] ?? null) ? $notifConfig['webhook_secret'] : null;
if ($genericUrl !== '') {
$dispatcher->addNotifier('webhook', new GenericWebhookNotifier($genericUrl, $secret));
}
if (!$dispatcher->hasNotifiers()) {
return;
}
$topViolations = array_map(
static fn($v): array => $v->toArray(),
array_slice($violations, 0, 5)
);
$payload = new NotificationPayload(
target: $target,
healthScore: $score,
totalViolations: count($violations),
errorCount: $errorCount,
warningCount: $warningCount,
topViolations: $topViolations
);
$dispatcher->dispatch($payload);
}
}
+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;
}
}
+75 -26
View File
@@ -5,7 +5,9 @@ namespace YakNet\AccessibilityConsole\Core;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
use YakNet\AccessibilityConsole\Cache\ScanCache;
use YakNet\AccessibilityConsole\Core\Locator\PreciseElementLocator;
use YakNet\AccessibilityConsole\Core\Suppression\InlineSuppressionParser;
use YakNet\AccessibilityConsole\Parser\TemplatePreprocessor;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
@@ -16,20 +18,29 @@ class Analyser
private BaselineManager $baselineManager;
private TemplatePreprocessor $templatePreprocessor;
private PreciseElementLocator $elementLocator;
private InlineSuppressionParser $suppressionParser;
private ?ScanCache $cache;
private string $projectRoot;
/** @var array<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
?PreciseElementLocator $elementLocator = null,
?InlineSuppressionParser $suppressionParser = null,
?ScanCache $cache = null
) {
$this->config = $config ?? new Config();
$this->scanner = $scanner ?? $this->setupScanner();
$this->baselineManager = $baselineManager ?? new BaselineManager();
$this->templatePreprocessor = $templatePreprocessor ?? new TemplatePreprocessor();
$this->elementLocator = $elementLocator ?? new PreciseElementLocator();
$this->suppressionParser = $suppressionParser ?? new InlineSuppressionParser();
$this->cache = $cache;
$cwd = getcwd();
$this->projectRoot = $cwd ? str_replace('\\', '/', realpath($cwd) ?: $cwd) : '.';
@@ -50,9 +61,7 @@ class Analyser
$activeRules = [];
foreach ($rules as $rule) {
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
: (new \ReflectionClass($rule))->getShortName();
$ruleId = $rule->getId();
if (in_array($ruleId, $rulesConfig['exclude'], true)) {
continue;
@@ -67,8 +76,8 @@ class Analyser
$reflection = new \ReflectionClass($customRuleClass);
if ($reflection->isInstantiable()) {
$rule = $reflection->newInstance();
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
$ruleId = method_exists($rule, 'getId')
? $rule->getId()
: $reflection->getShortName();
$activeRules[$ruleId] = $rule;
}
@@ -113,6 +122,7 @@ class Analyser
$violations = [];
$baselinedCount = 0;
$this->suppressedAuditLog = [];
foreach ($filesToScan as $index => $file) {
if ($onProgress) {
@@ -124,30 +134,57 @@ class Analyser
continue;
}
// Preprocess templates (Blade, Twig, PHP) into scan-ready HTML preserving line numbers
$scanContent = $this->templatePreprocessor->preprocess($rawContent, $file);
// Scan file content
try {
$fileViolations = $this->scanner->scan($scanContent);
} catch (\Throwable $e) {
// Skip if parsing failed dramatically
continue;
$relativeFile = $this->makePathRelative($file);
// Parse inline suppression directives (<!-- 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);
}
$relativeFile = $this->makePathRelative($file);
foreach ($fileViolations as $violation) {
// Find line and column number using high-precision locator
if (!isset($violation->location['line']) || $violation->location['line'] <= 1) {
$location = $this->elementLocator->locate($rawContent, $violation->htmlSnippet);
$violation->location = [
$lineNum = $violation->location['line'] ?? 1;
// Check inline suppression directives
$suppressionReason = $this->suppressionParser->getSuppressionReason($suppressions, $violation->ruleId, $lineNum);
if ($suppressionReason !== null) {
$this->suppressedAuditLog[] = [
'file' => $relativeFile,
'line' => $location['line'],
'column' => $location['column'],
'line' => $lineNum,
'ruleId' => $violation->ruleId,
'reason' => $suppressionReason,
];
} else {
$violation->location['file'] = $relativeFile;
continue;
}
// Check if ignored in baseline
@@ -158,6 +195,8 @@ class Analyser
}
}
}
$this->cache?->save();
return [
'violations' => $violations,
@@ -165,6 +204,16 @@ class Analyser
];
}
/**
* Audit trail of violations suppressed via inline comments during the latest analysis run.
*
* @return array<int, array{file: string, line: int, ruleId: string, reason: string}>
*/
public function getSuppressedAuditLog(): array
{
return $this->suppressedAuditLog;
}
public function getBaselineManager(): BaselineManager
{
return $this->baselineManager;
@@ -211,7 +260,7 @@ class Analyser
$iterator = new RecursiveIteratorIterator($filter, RecursiveIteratorIterator::SELF_FIRST);
$extensions = ['php', 'html', 'twig', 'blade.php'];
$extensions = $this->config->getExtensions();
foreach ($iterator as $file) {
/** @var SplFileInfo $file */
+50
View File
@@ -127,4 +127,54 @@ class Config
$key = $this->get('gemini_api_key') ?? $_ENV['GEMINI_API_KEY'] ?? getenv('GEMINI_API_KEY') ?: null;
return is_string($key) ? $key : null;
}
public function getPreset(): ?string
{
$preset = $this->get('preset');
return is_string($preset) && $preset !== '' ? $preset : null;
}
/**
* Governance policy configuration block from a11y.yaml.
*
* @return array<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'];
}
}
+21 -1
View File
@@ -7,10 +7,15 @@ use Psr\Container\ContainerInterface;
use YakNet\AccessibilityConsole\Core\Config;
use YakNet\AccessibilityConsole\Core\Analyser;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\CompareCommand;
use YakNet\AccessibilityConsole\Console\Command\DoctorCommand;
use YakNet\AccessibilityConsole\Console\Command\ExplainCommand;
use YakNet\AccessibilityConsole\Console\Command\FixCommand;
use YakNet\AccessibilityConsole\Console\Command\InitCommand;
use YakNet\AccessibilityConsole\Console\Command\PresetsCommand;
use YakNet\AccessibilityConsole\Console\Command\RulesCommand;
use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\VpatCommand;
use YakNet\AccessibilityConsole\Console\Command\WatchCommand;
class ContainerFactory
@@ -55,6 +60,21 @@ class ContainerFactory
WatchCommand::class => function () {
return new WatchCommand();
},
VpatCommand::class => function () {
return new VpatCommand();
},
CompareCommand::class => function () {
return new CompareCommand();
},
DoctorCommand::class => function () {
return new DoctorCommand();
},
ExplainCommand::class => function () {
return new ExplainCommand();
},
PresetsCommand::class => function () {
return new PresetsCommand();
},
]);
return $builder->build();
+23
View File
@@ -5,6 +5,7 @@ namespace YakNet\AccessibilityConsole\Core;
use DOMDocument;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Rules\RuleExecutionStats;
use YakNet\AccessibilityConsole\Rules\RuleInterface;
class RuleEngine
@@ -12,6 +13,18 @@ class RuleEngine
/** @var array<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;
@@ -47,7 +60,12 @@ class RuleEngine
// 1. Run Document-level rules
foreach ($docRules as $rule) {
$start = $this->stats !== null ? hrtime(true) : 0;
$violations = $rule->check($doc);
if ($this->stats !== null) {
$elapsedMs = (hrtime(true) - $start) / 1_000_000;
$this->stats->record($rule->getId(), $elapsedMs, !empty($violations));
}
$allViolations = array_merge($allViolations, $violations);
}
@@ -63,7 +81,12 @@ class RuleEngine
}
foreach ($elementRules as $rule) {
$start = $this->stats !== null ? hrtime(true) : 0;
$violation = $rule->check($element);
if ($this->stats !== null) {
$elapsedMs = (hrtime(true) - $start) / 1_000_000;
$this->stats->record($rule->getId(), $elapsedMs, $violation !== null);
}
if ($violation !== null) {
$allViolations[] = $violation;
}
+174
View File
@@ -136,8 +136,182 @@ class LocalHealer
return "EXPLANATION: Injected default lang=\"tr\" to HTML element.\nFIX: " . $fixed;
}
break;
case 'WCAG_3_2_2_BUTTON_TYPE':
case 'ButtonTypeExplicit':
if (preg_match('/<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];
}
}
@@ -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;
}
}
}
+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;
}
}
+13 -1
View File
@@ -7,15 +7,21 @@ 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
?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();
}
/**
@@ -35,6 +41,12 @@ class TemplatePreprocessor
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);
}
+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 [];
}
}
+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 [];
}
}
+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 [];
}
}
+8
View File
@@ -14,6 +14,14 @@ class PresetRegistry
$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
+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 [];
}
}
+116 -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(
@@ -281,6 +281,106 @@ class WcagDatabase
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
@@ -291,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');
}
}
+323 -41
View File
@@ -6,11 +6,16 @@ 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 an Excel (.xlsx) workbook.
* Export WCAG audit results as a multi-tab Excel (.xlsx) workbook.
*
* @param array<string, mixed> $scanResult
* @param string $targetUrl
@@ -22,65 +27,342 @@ class ExcelReportExporter
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 = $spreadsheet->getActiveSheet();
$sheet->setTitle('Erişilebilirlik Raporu');
// Headers
$sheet->setCellValue('A1', 'YakNet Accessibility Console - WCAG 2.1 Audit Export');
$sheet->mergeCells('A1:F1');
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14);
$sheet->getStyle('A1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
// -------------------------------------------------------------
// SHEET 1: ÖZET VE DENETİM KARNESİ (Executive Summary)
// -------------------------------------------------------------
$sheetSummary = $spreadsheet->getActiveSheet();
$sheetSummary->setTitle('Denetim Özeti & Karne');
$sheetSummary->setShowGridLines(true);
$sheet->setCellValue('A3', 'Hedef URL / Dizin:');
$sheet->setCellValue('B3', $targetUrl);
$sheet->setCellValue('A4', 'WCAG Skoru:');
$sheet->setCellValue('B4', $score . ' / 100');
$sheet->setCellValue('A5', 'İhlal Sayısı:');
$sheet->setCellValue('B5', count($violations));
// 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
$row = 7;
$headers = ['#', 'Kural ID', 'Standart', 'Ciddiyet', 'İhlal Açıklaması', 'Kod Snippet'];
$cols = ['A', 'B', 'C', 'D', 'E', 'F'];
foreach ($headers as $i => $h) {
$col = $cols[$i];
$sheet->setCellValue("{$col}{$row}", $h);
$sheet->getStyle("{$col}{$row}")->getFont()->setBold(true);
$sheet->getStyle("{$col}{$row}")->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setRGB('1E293B');
$sheet->getStyle("{$col}{$row}")->getFont()->getColor()->setRGB('FFFFFF');
$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);
// Table Rows
// Populate Table Rows
$vRow = 2;
foreach ($violations as $idx => $v) {
/** @var array<string, mixed> $v */
$r = $row + 1 + intval($idx);
$ruleId = is_string($v['ruleId'] ?? null) ? $v['ruleId'] : '';
$standard = is_string($v['standard'] ?? null) ? $v['standard'] : 'WCAG 2.1';
$severity = is_string($v['severity'] ?? null) ? $v['severity'] : 'WARNING';
$desc = is_string($v['description'] ?? null) ? $v['description'] : '';
$snippet = is_string($v['htmlSnippet'] ?? null) ? $v['htmlSnippet'] : '';
$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 : '';
$sheet->setCellValue("A{$r}", intval($idx) + 1);
$sheet->setCellValue("B{$r}", $ruleId);
$sheet->setCellValue("C{$r}", $standard);
$sheet->setCellValue("D{$r}", $severity);
$sheet->setCellValue("E{$r}", $desc);
$sheet->setCellValue("F{$r}", $snippet);
$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++;
}
// Auto-fit columns
foreach ($cols as $col) {
$sheet->getColumnDimension($col)->setAutoSize(true);
// 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');
+270 -51
View File
@@ -4,13 +4,15 @@ namespace YakNet\AccessibilityConsole\Reporting;
use Dompdf\Dompdf;
use Dompdf\Options;
use YakNet\AccessibilityConsole\Analytics\ComplianceMatrixGenerator;
use YakNet\AccessibilityConsole\Core\Violation;
class PdfReportGenerator
{
/**
* Generate a PDF Accessibility Certificate & Audit Report.
* Generate a detailed PDF Accessibility Audit & Conformance Report.
*
* @param array<string, mixed> $scanResult Scan result metrics and violations array
* @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
*/
@@ -28,32 +30,150 @@ class PdfReportGenerator
/** @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');
$dateStr = date('d.m.Y H:i:s');
$reportId = 'YAK-A11Y-' . date('Ymd') . '-' . strtoupper(substr(md5($targetUrl . date('Ymd')), 0, 6));
$scoreColor = $score >= 80 ? '#10b981' : ($score >= 50 ? '#f59e0b' : '#ef4444');
$statusText = $score >= 80 ? 'WCAG 2.1 AA Uyumlu (Pass)' : ($score >= 50 ? 'İyileştirme Gerekli (Warning)' : 'Kritik İhlaller (Fail)');
// 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 = '';
$slicedViolations = array_slice($violations, 0, 25);
foreach ($slicedViolations as $idx => $v) {
/** @var array<string, mixed> $v */
$num = $idx + 1;
$ruleIdVal = is_string($v['ruleId'] ?? null) ? $v['ruleId'] : '';
$descVal = is_string($v['description'] ?? null) ? $v['description'] : '';
$snippetVal = is_string($v['htmlSnippet'] ?? null) ? $v['htmlSnippet'] : '';
$suggestionVal = is_string($v['suggestion'] ?? null) ? $v['suggestion'] : '';
$ruleId = htmlspecialchars($ruleIdVal);
$desc = htmlspecialchars($descVal);
$snippet = htmlspecialchars($snippetVal);
$suggestion = htmlspecialchars($suggestionVal);
$violationsHtml .= "
<div style='margin-bottom:12px; padding:10px; border-left:4px solid #ef4444; background:#f8fafc;'>
<div style='font-weight:bold; color:#0f172a; font-size:12px;'>#{$num} [{$ruleId}] {$desc}</div>
<div style='font-family:monospace; font-size:10px; color:#e11d48; margin:4px 0; background:#f1f5f9; padding:4px;'>{$snippet}</div>
<div style='font-size:11px; color:#475569;'><b>Öneri:</b> {$suggestion}</div>
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 = "
@@ -61,50 +181,149 @@ class PdfReportGenerator
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>WCAG 2.1 Erişilebilirlik Sertifikası ve Raporu</title>
<title>YakNet Erişilebilirlik Denetim Raporu</title>
<style>
* { font-family: 'DejaVu Sans', sans-serif; }
body { font-family: 'DejaVu Sans', sans-serif; color: #1e293b; line-height: 1.5; font-size: 11px; margin: 0; padding: 20px; }
.header { text-align: center; border-bottom: 2px solid #38bdf8; padding-bottom: 15px; margin-bottom: 20px; }
.title { font-size: 18px; font-weight: bold; color: #0f172a; }
.subtitle { font-size: 12px; color: #64748b; margin-top: 4px; }
.badge { display: inline-block; padding: 6px 16px; border-radius: 12px; color: #fff; font-weight: bold; font-size: 13px; background: {$scoreColor}; }
.grid { margin-bottom: 20px; }
.card { background: #f8fafc; border: 1px solid #e2e8f0; padding: 12px; border-radius: 6px; margin-bottom: 10px; }
.footer { text-align: center; border-top: 1px solid #e2e8f0; padding-top: 15px; font-size: 10px; color: #94a3b8; margin-top: 30px; }
@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>
<div class='header'>
<div class='title'>♿ YakNet Accessibility Console</div>
<div class='subtitle'>WCAG 2.1 AA Erişilebilirlik Uyumluluk Raporu</div>
<!-- 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>
<div class='card' style='text-align:center;'>
<div style='font-size:11px; color:#64748b; text-transform:uppercase;'>Erişilebilirlik Sağlık Skoru</div>
<div style='font-size:32px; font-weight:bold; color:{$scoreColor}; margin:6px 0;'>{$score} / 100</div>
<div class='badge'>{$statusText}</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>
<div class='card'>
<div><b>Hedef URL / Dizin:</b> " . htmlspecialchars($targetUrl) . "</div>
<div><b>Tarama Tarihi:</b> {$dateStr}</div>
<div><b>Tespit Edilen İhlal Sayısı:</b> {$violationsCount} Hata</div>
<div><b>Raporu Üreten Motor:</b> YakNet AI & Accessibility Engine v3.3</div>
</div>
<!-- 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>
<h3 style='color:#0f172a; border-bottom:1px solid #cbd5e1; padding-bottom:6px;'>📋 Erişilebilirlik İhlalleri ve Çözüm Detayları</h3>
<!-- Detaylı İhlal Listesi -->
<div class='section-header'>📋 Tespit Edilen Erişilebilirlik Bulguları ve Çözüm Planı ({$violationsCount} Kayıt)</div>
{$violationsHtml}
<div class='footer'>
© {$dateStr} YakNet Bilişim — Türkiye'nin Yerli & Milli Erişilebilirlik Platformu (yak.net.tr)
<!-- 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);
+1 -1
View File
@@ -124,7 +124,7 @@ class SarifFormatter implements FormatterInterface
'driver' => [
'name' => 'YakNet Accessibility Console',
'informationUri' => 'https://forum.yak.net.tr',
'semanticVersion' => '3.3.0',
'semanticVersion' => '4.0.0',
'rules' => array_values($rulesMap),
],
],
+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;
}
}
+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;
}
}
+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;
}
}
+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;
}
}
+83
View File
@@ -0,0 +1,83 @@
<?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 AriaDeprecatedRoles extends AbstractRule
{
/** @var array<string, string> */
private const DEPRECATED_ROLES = [
'directory' => 'Use role="list" or native <ul>/<ol> instead of deprecated role="directory".',
];
/** @var string[] */
private const ABSTRACT_ROLES = [
'command', 'composite', 'input', 'landmark', 'range', 'roletype',
'section', 'sectionhead', 'select', 'structure', 'widget', 'window',
];
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_DEPRECATED_ROLE';
}
public function getDescription(): string
{
return 'Deprecated WAI-ARIA 1.2 roles (e.g. directory) and abstract ARIA ontology roles must not be used in markup.';
}
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('role')) {
return null;
}
$roles = preg_split('/\s+/', strtolower(trim($element->getAttribute('role'))));
if (!is_array($roles)) {
return null;
}
foreach ($roles as $role) {
if ($role === '') {
continue;
}
if (isset(self::DEPRECATED_ROLES[$role])) {
return $this->createViolation(
$element,
sprintf('ARIA role="%s" is deprecated in WAI-ARIA 1.2.', $role),
self::DEPRECATED_ROLES[$role]
);
}
if (in_array($role, self::ABSTRACT_ROLES, true)) {
return $this->createViolation(
$element,
sprintf('ARIA role="%s" is an abstract taxonomy role and must never be used directly by authors.', $role),
'Replace the abstract role with a concrete WAI-ARIA role or native semantic HTML element.'
);
}
}
return null;
}
}
+58
View File
@@ -0,0 +1,58 @@
<?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 AriaLivePoliteMisuse extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_3_ARIA_LIVE_ASSERTIVE';
}
public function getDescription(): string
{
return 'Avoid applying aria-live="assertive" on major page landmarks (<main>, <nav>, <header>, <footer>, <article>, <form>) as it aggressively interrupts screen readers.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower(trim($element->getAttribute('aria-live'))) !== 'assertive') {
return null;
}
$tag = strtolower($element->tagName);
$landmarkTags = ['body', 'main', 'nav', 'header', 'footer', 'article', 'aside', 'form', 'table'];
if (in_array($tag, $landmarkTags, true)) {
return $this->createViolation(
$element,
sprintf('Landmark/container <%s> uses aria-live="assertive", which interrupts ongoing screen reader speech whenever any descendant updates.', $tag),
'Reserve aria-live="assertive" strictly for urgent error/alert banners, and use aria-live="polite" on dedicated small status containers.'
);
}
return null;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?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 AriaMenuPattern extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_MENU';
}
public function getDescription(): string
{
return 'Elements with role="menu" or role="menubar" must contain valid menuitem roles and avoid mixing bare links without menuitem semantics.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
$role = strtolower(trim($element->getAttribute('role')));
if (!in_array($role, ['menu', 'menubar'], true)) {
return null;
}
$doc = $element->ownerDocument;
if ($doc === null) {
return null;
}
$xpath = new DOMXPath($doc);
$menuItems = $xpath->query('.//*[@role="menuitem" or @role="menuitemcheckbox" or @role="menuitemradio"]', $element);
if ($menuItems !== false && $menuItems->length === 0) {
return $this->createViolation(
$element,
sprintf('Container with role="%s" does not contain any role="menuitem", "menuitemcheckbox", or "menuitemradio" descendants.', $role),
'For site navigation links, use <nav><ul><li><a> instead of role="menu". For application menus, assign role="menuitem" to each action.'
);
}
return null;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?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 AriaModalBackdrop extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_MODAL';
}
public function getDescription(): string
{
return 'Custom modal dialog containers (role="dialog" or role="alertdialog") must declare aria-modal="true" to isolate screen reader navigation.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
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 === 'dialog') {
return null; // Native <dialog> handles modal state via showModal()
}
$role = strtolower(trim($element->getAttribute('role')));
if (!in_array($role, ['dialog', 'alertdialog'], true)) {
return null;
}
if (!$element->hasAttribute('aria-modal')) {
return $this->createViolation(
$element,
sprintf('Custom element with role="%s" is missing aria-modal="true" (or "false" for non-modal dialogs).', $role),
'Add aria-modal="true" on modal dialogs so assistive technologies constrain virtual cursor navigation inside the dialog.'
);
}
return null;
}
}
+89
View File
@@ -0,0 +1,89 @@
<?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 AriaOwnsValidTarget extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_OWNS';
}
public function getDescription(): string
{
return 'The aria-owns attribute must reference existing element IDs in the document and must not reference its own element ID.';
}
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-owns')) {
return null;
}
$owns = trim($element->getAttribute('aria-owns'));
if ($owns === '' || preg_match('/\{\{|\{%|<\?php/', $owns)) {
return null;
}
$doc = $element->ownerDocument;
if ($doc === null) {
return null;
}
$selfId = trim($element->getAttribute('id'));
$xpath = new DOMXPath($doc);
$ids = preg_split('/\s+/', $owns);
if (!is_array($ids)) {
return null;
}
foreach ($ids as $targetId) {
if ($targetId === '') {
continue;
}
if ($selfId !== '' && $targetId === $selfId) {
return $this->createViolation(
$element,
sprintf('Element creates an aria-owns self-reference cycle pointing to its own id="%s".', $selfId),
'Remove the self-referencing ID from aria-owns.'
);
}
if (preg_match('/^[a-zA-Z0-9_\-:.]+$/', $targetId)) {
$found = $xpath->query('//*[@id="' . $targetId . '"]');
if ($found !== false && $found->length === 0) {
return $this->createViolation(
$element,
sprintf('Attribute aria-owns references non-existent element ID "%s".', $targetId),
sprintf('Ensure an element with id="%s" exists in the DOM or update aria-owns.', $targetId)
);
}
}
}
return null;
}
}
+5
View File
@@ -76,6 +76,11 @@ class AriaRole extends AbstractRule
return $violations;
}
public function getDescription(): string
{
return 'ARIA role values must be valid WAI-ARIA roles and aria-controls targets must exist in the document.';
}
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 3; }
+74
View File
@@ -0,0 +1,74 @@
<?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 AriaSliderAttributes extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_SLIDER';
}
public function getDescription(): string
{
return 'Custom elements with role="slider" must provide aria-valuenow, aria-valuemin, aria-valuemax, and an accessible name.';
}
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'))) !== 'slider') {
return null;
}
if (strtolower($element->tagName) === 'input' && strtolower($element->getAttribute('type')) === 'range') {
return null;
}
$missing = [];
foreach (['aria-valuenow', 'aria-valuemin', 'aria-valuemax'] as $attr) {
if (!$element->hasAttribute($attr) || !is_numeric(trim($element->getAttribute($attr)))) {
$missing[] = $attr;
}
}
$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')) !== '');
if (!$hasName) {
$missing[] = 'accessible name (aria-label or aria-labelledby)';
}
if (!empty($missing)) {
return $this->createViolation(
$element,
'Custom slider (role="slider") is missing required attributes: ' . implode(', ', $missing) . '.',
'Specify numeric aria-valuemin, aria-valuemax, aria-valuenow, tabindex="0", and an aria-label, or use native <input type="range">.'
);
}
return null;
}
}
+74
View File
@@ -0,0 +1,74 @@
<?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 AriaSwitchState extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_SWITCH';
}
public function getDescription(): string
{
return 'Elements with role="switch" must declare aria-checked ("true" or "false") 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'))) !== 'switch') {
return null;
}
$tag = strtolower($element->tagName);
$isNativeCheckbox = $tag === 'input' && strtolower($element->getAttribute('type')) === 'checkbox';
if (!$isNativeCheckbox) {
$checkedVal = strtolower(trim($element->getAttribute('aria-checked')));
if (!in_array($checkedVal, ['true', 'false'], true)) {
return $this->createViolation(
$element,
'Element with role="switch" must specify aria-checked="true" or aria-checked="false" (note: "mixed" is invalid for switches).',
'Add aria-checked="false" (or "true") and toggle its value programmatically when activated.'
);
}
}
$hasName = trim($element->textContent) !== ''
|| ($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')) !== '');
if (!$hasName && !$isNativeCheckbox) {
return $this->createViolation(
$element,
'Element with role="switch" is missing an accessible name.',
'Add visible label text, aria-label, or aria-labelledby to identify what the switch controls.'
);
}
return null;
}
}
+91
View File
@@ -0,0 +1,91 @@
<?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 AriaTablistPattern extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_TABLIST';
}
public function getDescription(): string
{
return 'WAI-ARIA Tabs (tablist/tab/tabpanel) must follow the APG pattern with aria-selected, aria-controls, and aria-labelledby.';
}
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
{
$role = strtolower(trim($element->getAttribute('role')));
if ($role === 'tab') {
if (!$element->hasAttribute('aria-selected')) {
return $this->createViolation(
$element,
'Element with role="tab" is missing required aria-selected ("true" or "false") attribute.',
'Add aria-selected="true" for the active tab and aria-selected="false" for inactive tabs.'
);
}
if (!$element->hasAttribute('aria-controls') || trim($element->getAttribute('aria-controls')) === '') {
return $this->createViolation(
$element,
'Element with role="tab" should declare aria-controls referencing its associated role="tabpanel" element.',
'Add aria-controls="<panel-id>" pointing to the corresponding tabpanel.'
);
}
}
if ($role === 'tabpanel') {
$hasLabel = ($element->hasAttribute('aria-labelledby') && trim($element->getAttribute('aria-labelledby')) !== '')
|| ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '');
if (!$hasLabel) {
return $this->createViolation(
$element,
'Element with role="tabpanel" is missing an accessible name (aria-labelledby referencing its tab, or aria-label).',
'Add aria-labelledby="<tab-id>" to associate the tabpanel with its controlling tab.'
);
}
}
if ($role === 'tablist') {
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new DOMXPath($doc);
$tabs = $xpath->query('.//*[@role="tab"]', $element);
if ($tabs !== false && $tabs->length === 0) {
return $this->createViolation(
$element,
'Element with role="tablist" does not contain any child elements with role="tab".',
'Add interactive elements with role="tab" inside the tablist container.'
);
}
}
}
return null;
}
}
+74
View File
@@ -0,0 +1,74 @@
<?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 AriaTreePattern extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_TREE';
}
public function getDescription(): string
{
return 'WAI-ARIA Tree widgets (role="tree") must have an accessible name and expandable treeitems must specify aria-expanded.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
$role = strtolower(trim($element->getAttribute('role')));
if ($role === 'tree') {
$hasName = ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '')
|| ($element->hasAttribute('aria-labelledby') && trim($element->getAttribute('aria-labelledby')) !== '');
if (!$hasName) {
return $this->createViolation(
$element,
'Element with role="tree" is missing an accessible name (aria-label or aria-labelledby).',
'Add aria-label="File Explorer" or aria-labelledby referencing a visible heading.'
);
}
return null;
}
if ($role === 'treeitem') {
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new DOMXPath($doc);
$nestedGroup = $xpath->query('./*[@role="group"] | ./ul | ./ol', $element);
if ($nestedGroup !== false && $nestedGroup->length > 0 && !$element->hasAttribute('aria-expanded')) {
return $this->createViolation(
$element,
'Parent element with role="treeitem" contains nested child items without an aria-expanded attribute.',
'Add aria-expanded="true" or aria-expanded="false" to expandable treeitem nodes.'
);
}
}
}
return null;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?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 ArticleAccessibleHeading extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_ARTICLE_HEADING';
}
public function getDescription(): string
{
return '<article> elements should contain a heading (h1-h6 or role="heading") or provide an aria-label / aria-labelledby.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'article') {
return null;
}
$hasLabel = ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '')
|| ($element->hasAttribute('aria-labelledby') && trim($element->getAttribute('aria-labelledby')) !== '');
if ($hasLabel) {
return null;
}
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new DOMXPath($doc);
$headings = $xpath->query('.//h1 | .//h2 | .//h3 | .//h4 | .//h5 | .//h6 | .//*[@role="heading"]', $element);
if ($headings !== false && $headings->length > 0) {
return null;
}
}
return $this->createViolation(
$element,
'<article> element has no heading (h1-h6) and no aria-label/aria-labelledby to identify its topic.',
'Include a descriptive heading (e.g., <h2>) inside the <article> or add an aria-label attribute.'
);
}
}
+5
View File
@@ -43,6 +43,11 @@ class BannedSelectors extends AbstractRule
return $violations;
}
public function getDescription(): string
{
return 'Obsolete presentational HTML elements and attributes (center, blink, marquee, font, align, bgcolor) must not be used.';
}
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 2; }
+64
View File
@@ -0,0 +1,64 @@
<?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 BlockquoteCiteValid extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_BLOCKQUOTE_MISUSE';
}
public function getDescription(): string
{
return '<blockquote> elements must not have an empty cite attribute and should only be used for actual quotations, not visual indentation.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'blockquote') {
return null;
}
if ($element->hasAttribute('cite') && trim($element->getAttribute('cite')) === '') {
return $this->createViolation(
$element,
'<blockquote> element has an empty cite="" attribute.',
'Provide a valid source URL in the cite attribute or remove the empty attribute.'
);
}
$text = trim($element->textContent);
if ($text === '') {
return $this->createViolation(
$element,
'<blockquote> element contains no readable quotation text and appears to be used for layout spacing.',
'Remove empty <blockquote> elements and use CSS margin/padding for indentation.'
);
}
return null;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?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 ButtonTypeExplicit extends AbstractRule
{
public function getId(): string
{
return 'WCAG_3_2_2_BUTTON_TYPE';
}
public function getDescription(): string
{
return '<button> elements inside a <form> should explicitly declare type="submit", type="button", or type="reset" to prevent unexpected submissions (WCAG 3.2.2).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'button') {
return null;
}
if ($element->hasAttribute('type')) {
$type = strtolower(trim($element->getAttribute('type')));
if (in_array($type, ['submit', 'button', 'reset'], true)) {
return null;
}
}
// Only flag buttons located inside a <form>
$insideForm = false;
$parent = $element->parentNode;
while ($parent instanceof DOMElement) {
if (strtolower($parent->tagName) === 'form') {
$insideForm = true;
break;
}
$parent = $parent->parentNode;
}
if (!$insideForm) {
return null;
}
return $this->createViolation(
$element,
'<button> inside a <form> omits an explicit type attribute and defaults to type="submit", risking unintended form submission (WCAG 3.2.2).',
'Explicitly add type="button" for non-submitting actions or type="submit" for form submission.'
);
}
}
+81
View File
@@ -0,0 +1,81 @@
<?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 CharacterKeyShortcuts extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_1_4_CHAR_KEY_SHORTCUTS';
}
public function getDescription(): string
{
return 'Keyboard shortcuts defined via aria-keyshortcuts or data-hotkey must use a modifier key (Control, Alt, Meta) to avoid speech-input conflicts (WCAG 2.1.4).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
$attrs = ['aria-keyshortcuts', 'data-hotkey', 'data-shortcut'];
foreach ($attrs as $attr) {
if (!$element->hasAttribute($attr)) {
continue;
}
$value = trim($element->getAttribute($attr));
if ($value === '') {
continue;
}
// Multiple shortcuts can be space-separated
$shortcuts = preg_split('/\s+/', $value);
if (!is_array($shortcuts)) {
continue;
}
foreach ($shortcuts as $shortcut) {
// Single printable character without modifier (e.g. "k", "/", "?", "j", "Shift+a" is also printable)
$clean = trim($shortcut);
if ($clean === '') {
continue;
}
$hasNonPrintableModifier = (bool)preg_match('/^(?:Control|Ctrl|Alt|Meta|Command|Cmd|AltGraph)\+/i', $clean);
$isSingleChar = mb_strlen($clean) === 1 && preg_match('/^[a-zA-Z0-9\p{P}\p{S}]$/u', $clean);
$isShiftOnlyChar = (bool)preg_match('/^Shift\+[^\s+]{1}$/i', $clean);
if (!$hasNonPrintableModifier && ($isSingleChar || $isShiftOnlyChar)) {
return $this->createViolation(
$element,
sprintf('Attribute %s="%s" defines a single-character keyboard shortcut without a non-printable modifier (Control/Alt/Meta), violating WCAG 2.1.4.', $attr, $clean),
sprintf('Require a modifier key (e.g., %s="Alt+%s") or provide a mechanism to remap or disable the shortcut.', $attr, strtoupper($clean))
);
}
}
}
return null;
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMDocument;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Core\AbstractRule as DocumentAbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class CheckboxGroupFieldset extends DocumentAbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_CHECKBOX_GROUP';
}
public function getDescription(): string
{
return 'Multiple checkboxes sharing the same group name should be grouped inside a <fieldset> with a <legend> or an element with role="group".';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMDocument $doc): array
{
$xpath = new DOMXPath($doc);
$checkboxes = $xpath->query('//input[@type="checkbox" and @name]');
if ($checkboxes === false || $checkboxes->length < 2) {
return [];
}
/** @var array<string, DOMElement[]> $groups */
$groups = [];
foreach ($checkboxes as $cb) {
if (!$cb instanceof DOMElement) {
continue;
}
$name = trim($cb->getAttribute('name'));
if ($name === '') {
continue;
}
$groups[$name][] = $cb;
}
$violations = [];
foreach ($groups as $name => $elements) {
if (count($elements) < 2) {
continue;
}
$first = $elements[0];
$isGrouped = false;
$parent = $first->parentNode;
while ($parent instanceof DOMElement) {
$pTag = strtolower($parent->tagName);
$pRole = strtolower(trim($parent->getAttribute('role')));
if ($pTag === 'fieldset' || $pRole === 'group') {
$isGrouped = true;
break;
}
$parent = $parent->parentNode;
}
if (!$isGrouped) {
$violations[] = $this->createViolation(
sprintf('Checkbox group "%s" (%d checkboxes) is not wrapped in a <fieldset><legend> or role="group" container.', $name, count($elements)),
$first,
'Wrap related checkboxes inside a <fieldset> with a descriptive <legend> (or a container with role="group" and aria-labelledby).'
);
}
}
return $violations;
}
}
+133
View File
@@ -0,0 +1,133 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use Spatie\Color\Rgb;
use YakNet\AccessibilityConsole\Color\Contrast\ContrastRatioCalculator;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class ColorContrastAAA extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_4_6_CONTRAST_AAA';
}
public function getDescription(): string
{
return 'Enhanced contrast (WCAG AAA) requires at least 7:1 contrast ratio for normal text and 4.5:1 for large text (WCAG 1.4.6).';
}
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
{
$style = $element->getAttribute('style');
if ($style === '') {
return null;
}
$fg = $this->extractHex($style, 'color');
$bg = $this->extractHex($style, 'background-color') ?? $this->extractHex($style, 'background');
if ($fg === null || $bg === null) {
return null;
}
$fgRgb = $this->hexToRgb($fg);
$bgRgb = $this->hexToRgb($bg);
if ($fgRgb === null || $bgRgb === null) {
return null;
}
$ratio = ContrastRatioCalculator::calculate($fgRgb, $bgRgb);
$isLarge = $this->isLargeText($style);
$minRatio = $isLarge ? 4.5 : 7.0;
if ($ratio < $minRatio) {
return $this->createViolation(
$element,
sprintf('Contrast ratio %.2f:1 does not meet WCAG AAA enhanced threshold of %.1f:1 (WCAG 1.4.6).', $ratio, $minRatio),
sprintf('Increase contrast between foreground (%s) and background (%s) to at least %.1f:1.', $fg, $bg, $minRatio)
);
}
return null;
}
private function extractHex(string $style, string $property): ?string
{
if (!preg_match('/(?:^|;)\s*' . preg_quote($property, '/') . '\s*:\s*([^;]+)/i', $style, $m)) {
return null;
}
$val = trim($m[1]);
if (preg_match('/#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b/', $val, $hex)) {
return '#' . $hex[1];
}
if (preg_match('/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i', $val, $rgb)) {
return sprintf('#%02x%02x%02x', min(255, (int)$rgb[1]), min(255, (int)$rgb[2]), min(255, (int)$rgb[3]));
}
$named = [
'black' => '#000000',
'white' => '#ffffff',
'gray' => '#808080',
'grey' => '#808080',
'silver' => '#c0c0c0',
'red' => '#ff0000',
'blue' => '#0000ff',
'green' => '#008000',
'yellow' => '#ffff00',
'navy' => '#000080',
];
$lower = strtolower($val);
return $named[$lower] ?? null;
}
private function hexToRgb(string $hex): ?Rgb
{
$hex = ltrim($hex, '#');
if (strlen($hex) === 3) {
$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
}
if (strlen($hex) !== 6) {
return null;
}
return new Rgb(
(int)hexdec(substr($hex, 0, 2)),
(int)hexdec(substr($hex, 2, 2)),
(int)hexdec(substr($hex, 4, 2))
);
}
private function isLargeText(string $style): bool
{
if (!preg_match('/font-size\s*:\s*([0-9.]+)(px|pt|rem|em)/i', $style, $m)) {
return false;
}
$val = (float)$m[1];
$unit = strtolower($m[2]);
$isBold = (bool)preg_match('/font-weight\s*:\s*(?:bold|[7-9]00)/i', $style);
if ($isBold) {
return ($unit === 'px' && $val >= 18.66) || ($unit === 'pt' && $val >= 14) || (($unit === 'rem' || $unit === 'em') && $val >= 1.2);
}
return ($unit === 'px' && $val >= 24) || ($unit === 'pt' && $val >= 18) || (($unit === 'rem' || $unit === 'em') && $val >= 1.5);
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMDocument;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Core\AbstractRule as DocumentAbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class ConsistentHelp extends DocumentAbstractRule
{
public function getId(): string
{
return 'WCAG_3_2_6_CONSISTENT_HELP';
}
public function getDescription(): string
{
return 'Interactive full-page documents with forms should provide an accessible help, contact, or support mechanism (WCAG 2.2 SC 3.2.6).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::INFO;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMDocument $doc): array
{
$xpath = new DOMXPath($doc);
// Only evaluate full pages that include a <body>, a <header> or <footer>, and a <form>
$bodies = $xpath->query('//body');
$forms = $xpath->query('//form');
$landmarks = $xpath->query('//header | //footer | //nav');
if ($bodies === false || $bodies->length === 0
|| $forms === false || $forms->length === 0
|| $landmarks === false || $landmarks->length === 0) {
return [];
}
$helpKeywords = [
'help', 'support', 'contact', 'faq', 'assist', 'chat', 'customer service',
'yardım', 'destek', 'iletişim', 'sss', 'canlı destek', 'müşteri hizmetleri',
];
$linksAndButtons = $xpath->query('//a | //button');
if ($linksAndButtons !== false) {
foreach ($linksAndButtons as $el) {
if (!$el instanceof DOMElement) {
continue;
}
$text = mb_strtolower(trim($el->textContent . ' ' . $el->getAttribute('aria-label') . ' ' . $el->getAttribute('title') . ' ' . $el->getAttribute('href')));
if (str_starts_with($el->getAttribute('href'), 'mailto:') || str_starts_with($el->getAttribute('href'), 'tel:')) {
return [];
}
foreach ($helpKeywords as $kw) {
if (str_contains($text, $kw)) {
return [];
}
}
}
}
$body = $bodies->item(0);
if ($body instanceof DOMElement) {
return [
$this->createViolation(
'Page contains interactive forms and navigation landmarks but no detectable help, support, or contact link (WCAG 2.2 SC 3.2.6 Consistent Help).',
$body,
'Provide a consistent help or contact mechanism (e.g., <a href="/help">Help</a> or <a href="/contact">Contact Support</a>) in the header or footer.'
),
];
}
return [];
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMDocument;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Core\AbstractRule as DocumentAbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class DocumentHasH1 extends DocumentAbstractRule
{
public function getId(): string
{
return 'WCAG_2_4_6_DOCUMENT_H1';
}
public function getDescription(): string
{
return 'Full HTML pages with a <main> landmark or headings should include an <h1> primary heading (WCAG 2.4.6).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMDocument $doc): array
{
$xpath = new DOMXPath($doc);
// Only evaluate full documents that have a <main> landmark (avoids false positives on small partial snippets)
$mains = $xpath->query('//main | //*[@role="main"]');
if ($mains === false || $mains->length === 0) {
return [];
}
$h1s = $xpath->query('//h1 | //*[@role="heading" and @aria-level="1"]');
if ($h1s !== false && $h1s->length > 0) {
return [];
}
$main = $mains->item(0);
if ($main instanceof DOMElement) {
return [
$this->createViolation(
'Document contains a <main> landmark but lacks a primary <h1> heading for screen reader orientation (WCAG 2.4.6).',
$main,
'Add a single descriptive <h1> heading inside <main> representing the primary topic of the page.'
),
];
}
return [];
}
}
+68
View File
@@ -0,0 +1,68 @@
<?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 FlashingContentBanned extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_3_1_FLASHING_CONTENT';
}
public function getDescription(): string
{
return 'Content must not flash more than three times per second (> 3Hz), which can trigger photosensitive seizures (WCAG 2.3.1).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::CRITICAL;
}
public function getLevel(): int
{
return 2;
}
public function check(DOMElement $element): ?Violation
{
$tag = strtolower($element->tagName);
$cssText = ($tag === 'style') ? $element->textContent : $element->getAttribute('style');
if (trim($cssText) === '') {
return null;
}
// Check infinite rapid animations faster than 0.33s (330ms) => > 3 flashes/sec
if (preg_match('/animation(?:-duration)?\s*:\s*[^;]*\b(0?\.\d+s|\d+ms)\b[^;]*infinite/i', $cssText, $m)
|| (preg_match('/animation-iteration-count\s*:\s*infinite/i', $cssText)
&& preg_match('/animation-duration\s*:\s*(0?\.\d+s|\d+ms)/i', $cssText, $m))) {
$rawDuration = strtolower($m[1]);
$ms = str_ends_with($rawDuration, 'ms')
? (float)substr($rawDuration, 0, -2)
: ((float)substr($rawDuration, 0, -1) * 1000.0);
if ($ms > 0.0 && $ms < 333.0) {
return $this->createViolation(
$element,
sprintf('Infinite CSS animation with duration %s exceeds 3 cycles/second, posing a photosensitive seizure hazard (WCAG 2.3.1).', $rawDuration),
'Increase animation duration to at least 0.5s (500ms) or avoid rapid flashing/strobing animations.'
);
}
}
return null;
}
}
+77
View File
@@ -0,0 +1,77 @@
<?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 FocusAppearance extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_4_13_FOCUS_APPEARANCE';
}
public function getDescription(): string
{
return 'Focus indicators must have sufficient thickness (at least 2px) and visual clarity (WCAG 2.2 SC 2.4.13).';
}
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
{
$tag = strtolower($element->tagName);
if ($tag === 'style') {
$css = $element->textContent;
if (preg_match('/:focus(?:-visible)?\s*\{[^}]*\boutline(?:-width)?\s*:\s*(?:0(?:\.?\d+)?(?:px|em|rem)?|1px|0\.5px|thin)\b/i', $css)) {
return $this->createViolation(
$element,
'CSS :focus rule defines an outline thinner than 2px, failing WCAG 2.2 Focus Appearance (SC 2.4.13).',
'Use at least a 2px solid high-contrast focus indicator (e.g., outline: 2px solid #005fcc; outline-offset: 2px;).'
);
}
return null;
}
$style = $element->getAttribute('style');
if ($style === '') {
return null;
}
$isInteractive = in_array($tag, ['a', 'button', 'input', 'select', 'textarea', 'summary'], true)
|| ($element->hasAttribute('tabindex') && (int)$element->getAttribute('tabindex') >= 0);
if (!$isInteractive) {
return null;
}
if (preg_match('/outline(?:-width)?\s*:\s*(?:1px|0\.5px|thin)\b/i', $style)) {
return $this->createViolation(
$element,
'Interactive element defines an outline thinner than 2px, reducing keyboard focus visibility (WCAG 2.2 SC 2.4.13).',
'Increase the focus outline thickness to at least 2px with a 3:1 contrast ratio against adjacent colors.'
);
}
return null;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?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 FontSizeMinimum extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_4_4_FONT_SIZE_MIN';
}
public function getDescription(): string
{
return 'Inline text font sizes should not be smaller than 11px (or 0.7rem) to maintain readability for low-vision users (WCAG 1.4.4).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
$style = $element->getAttribute('style');
if ($style === '' || trim($element->textContent) === '') {
return null;
}
if (preg_match('/(?:^|;)\s*font-size\s*:\s*([0-9.]+)(px|pt|rem|em)\b/i', $style, $m)) {
$value = (float)$m[1];
$unit = strtolower($m[2]);
$tooSmall = ($unit === 'px' && $value > 0 && $value < 11.0)
|| ($unit === 'pt' && $value > 0 && $value < 8.5)
|| (($unit === 'rem' || $unit === 'em') && $value > 0 && $value < 0.7);
if ($tooSmall) {
return $this->createViolation(
$element,
sprintf('Element sets an excessively small inline font-size of %s%s, impeding readability for low-vision users.', $m[1], $unit),
'Use relative units (rem/em) with a readable base size (at least 14px-16px / 0.875rem-1rem for body copy).'
);
}
}
return null;
}
}
+63
View File
@@ -0,0 +1,63 @@
<?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 FormErrorSummary extends AbstractRule
{
public function getId(): string
{
return 'WCAG_3_3_1_FORM_ERROR_SUMMARY';
}
public function getDescription(): string
{
return 'Form fields marked with aria-invalid="true" must programmatically reference an error description via aria-errormessage or aria-describedby (WCAG 3.3.1).';
}
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
{
$tag = strtolower($element->tagName);
if (!in_array($tag, ['input', 'select', 'textarea'], true)) {
return null;
}
if (strtolower(trim($element->getAttribute('aria-invalid'))) !== 'true') {
return null;
}
$hasErrorRef = ($element->hasAttribute('aria-errormessage') && trim($element->getAttribute('aria-errormessage')) !== '')
|| ($element->hasAttribute('aria-describedby') && trim($element->getAttribute('aria-describedby')) !== '');
if (!$hasErrorRef) {
return $this->createViolation(
$element,
'Form control has aria-invalid="true" without referencing an error message via aria-describedby or aria-errormessage (WCAG 3.3.1 Error Identification).',
'Link the field to its visible error message using aria-describedby="field-error-id" or aria-errormessage="field-error-id".'
);
}
return null;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?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 HeaderMainNestedInvalid extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_LANDMARK_NESTING';
}
public function getDescription(): string
{
return 'The <main> landmark must not be nested inside <article>, <aside>, <footer>, <header>, or <nav> elements.';
}
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
{
$tag = strtolower($element->tagName);
$role = strtolower(trim($element->getAttribute('role')));
if ($tag !== 'main' && $role !== 'main') {
return null;
}
$forbiddenAncestors = ['article', 'aside', 'footer', 'header', 'nav'];
$parent = $element->parentNode;
while ($parent instanceof DOMElement) {
$parentTag = strtolower($parent->tagName);
if (in_array($parentTag, $forbiddenAncestors, true)) {
return $this->createViolation(
$element,
sprintf('The <main> landmark is improperly nested inside a <%s> element, violating HTML5 landmark rules.', $parentTag),
'Move <main> to be a top-level landmark directly inside <body> (or inside a generic <div> wrapper).'
);
}
$parent = $parent->parentNode;
}
return null;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?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 HeadingLengthConcise extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_4_6_HEADING_LENGTH';
}
public function getDescription(): string
{
return 'Headings (h1-h6) should be concise (under 160 characters) rather than wrapping full paragraphs (WCAG 2.4.6).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
$tag = strtolower($element->tagName);
if (!in_array($tag, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'], true)) {
return null;
}
$text = trim((string)preg_replace('/\s+/', ' ', $element->textContent));
$length = mb_strlen($text);
if ($length > 160) {
return $this->createViolation(
$element,
sprintf('Heading <%s> is excessively long (%d characters; recommended <= 160), making screen reader navigation difficult (WCAG 2.4.6).', $tag, $length),
'Shorten the heading to a concise summary and move explanatory text into a <p> element below it.'
);
}
return null;
}
}
+104
View File
@@ -0,0 +1,104 @@
<?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 HoverFocusContentDismissible extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_4_13_CONTENT_ON_HOVER';
}
public function getDescription(): string
{
return 'Tooltip elements (role="tooltip" or data-tooltip) must be programmatically linked via aria-describedby and keyboard accessible (WCAG 1.4.13).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
$role = strtolower(trim($element->getAttribute('role')));
$tag = strtolower($element->tagName);
// Case 1: role="tooltip" without an id or without any trigger referencing it
if ($role === 'tooltip') {
$id = trim($element->getAttribute('id'));
if ($id === '') {
return $this->createViolation(
$element,
'Element with role="tooltip" is missing an id attribute and cannot be referenced by aria-describedby (WCAG 1.4.13).',
'Add a unique id to the tooltip element and link the trigger control with aria-describedby="<tooltip-id>".'
);
}
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new DOMXPath($doc);
$triggers = $xpath->query('//*[@aria-describedby]');
$isReferenced = false;
if ($triggers !== false) {
foreach ($triggers as $trigger) {
if ($trigger instanceof DOMElement) {
$refs = preg_split('/\s+/', trim($trigger->getAttribute('aria-describedby')));
if (is_array($refs) && in_array($id, $refs, true)) {
$isReferenced = true;
break;
}
}
}
}
if (!$isReferenced) {
return $this->createViolation(
$element,
sprintf('Tooltip with id="%s" is not referenced by any element via aria-describedby (WCAG 1.4.13).', $id),
sprintf('Add aria-describedby="%s" to the focusable trigger element controlling this tooltip.', $id)
);
}
}
return null;
}
// Case 2: Non-focusable element with data-tooltip / data-bs-toggle="tooltip"
$hasDataTooltip = $element->hasAttribute('data-tooltip')
|| strtolower($element->getAttribute('data-bs-toggle')) === 'tooltip'
|| strtolower($element->getAttribute('data-toggle')) === 'tooltip';
if ($hasDataTooltip) {
$nativelyFocusable = in_array($tag, ['a', 'button', 'input', 'select', 'textarea', 'summary'], true);
$hasTabindex = $element->hasAttribute('tabindex') && (int)$element->getAttribute('tabindex') >= 0;
if (!$nativelyFocusable && !$hasTabindex) {
return $this->createViolation(
$element,
sprintf('Non-focusable <%s> element triggers a hover tooltip without keyboard focus support (WCAG 1.4.13).', $tag),
'Use a native <button> or add tabindex="0" and Escape-key dismissal so keyboard users can access and dismiss the tooltip.'
);
}
}
return null;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?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 IframeSandboxAccessibility extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_IFRAME_TABINDEX';
}
public function getDescription(): string
{
return 'Visible <iframe> elements must not set tabindex="-1", which blocks keyboard users from tabbing into embedded content.';
}
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($element->tagName) !== 'iframe') {
return null;
}
if (strtolower(trim($element->getAttribute('aria-hidden'))) === 'true' || $element->hasAttribute('hidden')) {
return null;
}
if ($element->hasAttribute('tabindex') && (int)$element->getAttribute('tabindex') < 0) {
return $this->createViolation(
$element,
'Visible <iframe> has negative tabindex="-1", preventing keyboard-only users from reaching interactive controls inside the frame.',
'Remove tabindex="-1" from the <iframe>, or hide decorative frames with aria-hidden="true".'
);
}
return null;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?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 InputTypeValidation extends AbstractRule
{
public function getId(): string
{
return 'WCAG_3_3_2_INPUT_TYPE_SEMANTIC';
}
public function getDescription(): string
{
return 'Use semantic HTML5 input types (email, tel, url, search) instead of generic type="text" to assist mobile keyboards and assistive technologies.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::INFO;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'input') {
return null;
}
$type = strtolower(trim($element->getAttribute('type')));
if ($type !== '' && $type !== 'text') {
return null;
}
$identifier = strtolower($element->getAttribute('name') . ' ' . $element->getAttribute('id'));
if (trim($identifier) === '') {
return null;
}
$mappings = [
'email' => '/\b(e?mail|eposta|e_posta)\b/',
'tel' => '/\b(phone|tel|telephone|mobile|gsm|telefon|cep)\b/',
'url' => '/\b(website|homepage|url|web_site)\b/',
];
foreach ($mappings as $expectedType => $pattern) {
if (preg_match($pattern, $identifier)) {
return $this->createViolation(
$element,
sprintf('Input appears to collect "%s" data but uses generic type="text" instead of type="%s".', $expectedType, $expectedType),
sprintf('Change type="text" to type="%s" to expose native validation and optimized virtual keyboards.', $expectedType)
);
}
}
return null;
}
}
+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 JustifiedTextBanned extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_4_8_TEXT_JUSTIFY';
}
public function getDescription(): string
{
return 'Avoid full text justification (text-align: justify) on prose blocks, which creates uneven word spacing for readers with dyslexia (WCAG 1.4.8).';
}
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
{
$style = $element->getAttribute('style');
if ($style === '') {
return null;
}
if (preg_match('/(?:^|;)\s*text-align\s*:\s*justify\b/i', $style)) {
return $this->createViolation(
$element,
'Element uses text-align: justify, which creates irregular spacing ("rivers of white") impeding cognitive and dyslexic readability (WCAG 1.4.8).',
'Use text-align: start (or left/right matching text direction) instead of text-align: justify.'
);
}
return null;
}
}
+95
View File
@@ -0,0 +1,95 @@
<?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 LinkDownloadContext extends AbstractRule
{
/** @var array<string, string> */
private const DOCUMENT_EXTENSIONS = [
'pdf' => 'PDF',
'doc' => 'DOC',
'docx' => 'DOCX',
'xls' => 'XLS',
'xlsx' => 'XLSX',
'ppt' => 'PPT',
'pptx' => 'PPTX',
'zip' => 'ZIP',
'rar' => 'RAR',
'csv' => 'CSV',
];
public function getId(): string
{
return 'WCAG_2_4_4_LINK_DOWNLOAD_CONTEXT';
}
public function getDescription(): string
{
return 'Links to downloadable non-HTML documents (.pdf, .docx, .xlsx, .zip) should indicate the file format in the link text or aria-label.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::INFO;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'a' || !$element->hasAttribute('href')) {
return null;
}
$href = trim($element->getAttribute('href'));
$path = parse_url($href, PHP_URL_PATH);
if (!is_string($path) || $path === '') {
return null;
}
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if (!isset(self::DOCUMENT_EXTENSIONS[$ext])) {
return null;
}
$accessibleText = mb_strtolower(trim(
$element->textContent . ' ' . $element->getAttribute('aria-label') . ' ' . $element->getAttribute('title')
));
$labelFormat = self::DOCUMENT_EXTENSIONS[$ext];
$baseFormat = strtolower($ext);
$altFormats = match ($ext) {
'docx' => ['docx', 'doc', 'word'],
'xlsx' => ['xlsx', 'xls', 'excel'],
'pptx' => ['pptx', 'ppt', 'powerpoint'],
default => [$baseFormat],
};
foreach ($altFormats as $token) {
if (str_contains($accessibleText, $token)) {
return null;
}
}
return $this->createViolation(
$element,
sprintf('Link downloads a %s file ("%s") without mentioning the file format in its accessible name.', $labelFormat, basename($path)),
sprintf('Include the file format in the link text or aria-label (e.g., "Annual Report (%s)").', $labelFormat)
);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?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 MotionAnimationReduced extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_3_3_REDUCED_MOTION';
}
public function getDescription(): string
{
return 'Stylesheets defining CSS animations or keyframes should respect the prefers-reduced-motion media query (WCAG 2.3.3).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AAA;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'style') {
return null;
}
$css = $element->textContent;
if (trim($css) === '') {
return null;
}
$hasAnimation = (bool)preg_match('/@keyframes\b|\banimation(?:-name)?\s*:\s*(?!none\b)/i', $css);
$hasReducedMotion = (bool)preg_match('/prefers-reduced-motion/i', $css);
if ($hasAnimation && !$hasReducedMotion) {
return $this->createViolation(
$element,
'Stylesheet defines CSS animations without a @media (prefers-reduced-motion: reduce) fallback (WCAG 2.3.3).',
'Add @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } }.'
);
}
return null;
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Rules;
use DOMDocument;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Core\AbstractRule as DocumentAbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class NavAccessibleName extends DocumentAbstractRule
{
public function getId(): string
{
return 'WCAG_2_4_1_NAV_LABEL';
}
public function getDescription(): string
{
return 'When multiple navigation landmarks (<nav> or role="navigation") exist on a page, each must have a unique aria-label or aria-labelledby.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMDocument $doc): array
{
$xpath = new DOMXPath($doc);
$navs = $xpath->query('//nav | //*[@role="navigation"]');
if ($navs === false || $navs->length <= 1) {
return [];
}
$violations = [];
$seenLabels = [];
foreach ($navs as $nav) {
if (!$nav instanceof DOMElement) {
continue;
}
$label = trim($nav->getAttribute('aria-label'));
$labelledBy = trim($nav->getAttribute('aria-labelledby'));
if ($label === '' && $labelledBy === '') {
$violations[] = $this->createViolation(
'Page contains multiple navigation landmarks, but this <nav> is missing an aria-label or aria-labelledby to distinguish it.',
$nav,
'Add a unique aria-label (e.g., aria-label="Main Navigation", aria-label="Footer Links", aria-label="Pagination").'
);
continue;
}
$key = strtolower($label !== '' ? $label : 'id:' . $labelledBy);
if (isset($seenLabels[$key])) {
$violations[] = $this->createViolation(
sprintf('Multiple navigation landmarks share the duplicate accessible name "%s".', $label !== '' ? $label : $labelledBy),
$nav,
'Provide a distinct aria-label for each navigation landmark on the page.'
);
} else {
$seenLabels[$key] = true;
}
}
return $violations;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?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 OrientationLockBanned extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_4_ORIENTATION_LOCK';
}
public function getDescription(): string
{
return 'CSS must not lock display orientation by hiding content or rotating the viewport in portrait/landscape media queries (WCAG 1.3.4).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'style') {
return null;
}
$css = $element->textContent;
if (!preg_match('/@media[^{]*orientation\s*:\s*(?:portrait|landscape)[^{]*\{/i', $css)) {
return null;
}
// Check if orientation query hides body/main/app or applies 90deg/-90deg rotation lock
if (preg_match('/@media[^{]*orientation\s*:\s*(?:portrait|landscape)[^{]*\{[\s\S]*?(?:(?:body|main|#app|\.app)\s*\{[^}]*(?:display\s*:\s*none|visibility\s*:\s*hidden)|transform\s*:\s*rotate\(\s*-?90deg\s*\))/i', $css)) {
return $this->createViolation(
$element,
'Stylesheet appears to restrict page display to a single screen orientation (WCAG 1.3.4 Orientation).',
'Remove orientation locks and use responsive CSS layouts that adapt seamlessly to both portrait and landscape orientations.'
);
}
return null;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?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 OutputForValid extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_OUTPUT_FOR';
}
public function getDescription(): string
{
return '<output> elements with a "for" attribute must reference existing element IDs in the document.';
}
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($element->tagName) !== 'output' || !$element->hasAttribute('for')) {
return null;
}
$forAttr = trim($element->getAttribute('for'));
if ($forAttr === '' || preg_match('/\{\{|\{%|<\?php/', $forAttr)) {
return null;
}
$doc = $element->ownerDocument;
if ($doc === null) {
return null;
}
$xpath = new DOMXPath($doc);
$ids = preg_split('/\s+/', $forAttr);
if (!is_array($ids)) {
return null;
}
foreach ($ids as $targetId) {
if ($targetId === '' || !preg_match('/^[a-zA-Z0-9_\-:.]+$/', $targetId)) {
continue;
}
$nodes = $xpath->query('//*[@id="' . $targetId . '"]');
if ($nodes !== false && $nodes->length === 0) {
return $this->createViolation(
$element,
sprintf('<output> attribute for="%s" references a non-existent element ID "%s".', $forAttr, $targetId),
sprintf('Ensure an input or control with id="%s" exists in the document.', $targetId)
);
}
}
return null;
}
}
+77
View File
@@ -0,0 +1,77 @@
<?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 PointerCancellation extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_5_2_POINTER_CANCELLATION';
}
public function getDescription(): string
{
return 'Interactive controls should trigger actions on pointer up-events (onclick/onmouseup) rather than down-events (onmousedown/ontouchstart/onpointerdown) (WCAG 2.5.2).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
$downEvents = ['onmousedown', 'ontouchstart', 'onpointerdown'];
$hasDownEvent = null;
foreach ($downEvents as $evt) {
if ($element->hasAttribute($evt) && trim($element->getAttribute($evt)) !== '') {
$hasDownEvent = $evt;
break;
}
}
if ($hasDownEvent === null) {
return null;
}
// If element also has up/click event or is explicitly draggable/slider/canvas, down-event may be legitimate
$tag = strtolower($element->tagName);
$role = strtolower($element->getAttribute('role'));
if ($tag === 'canvas' || $role === 'slider' || $element->getAttribute('draggable') === 'true') {
return null;
}
$hasUpEvent = $element->hasAttribute('onclick')
|| $element->hasAttribute('onmouseup')
|| $element->hasAttribute('ontouchend')
|| $element->hasAttribute('onpointerup');
if (!$hasUpEvent) {
return $this->createViolation(
$element,
sprintf('Element executes an action on "%s" down-event without an up-event or click handler, preventing pointer cancellation (WCAG 2.5.2).', $hasDownEvent),
'Bind interactive actions to onclick / onmouseup / onpointerup so users can abort accidental pointer activation.'
);
}
return null;
}
}
+1 -2
View File
@@ -22,8 +22,7 @@ class RuleController
{
$allRules = $rules ?? RuleLevels::getRulesForLevel(9);
foreach ($allRules as $rule) {
$id = ($rule instanceof RuleInterface) ? $rule->getId() : (new \ReflectionClass($rule))->getShortName();
$this->rulesRegistry[$id] = $rule;
$this->rulesRegistry[$rule->getId()] = $rule;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?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 SectionAccessibleName extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_SECTION_NAME';
}
public function getDescription(): string
{
return 'Elements with role="region" must have an accessible name (aria-label or aria-labelledby) to be exposed as a landmark.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower(trim($element->getAttribute('role'))) !== 'region') {
return null;
}
$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')) !== '');
if (!$hasName) {
return $this->createViolation(
$element,
'Element with role="region" is missing an accessible name (aria-label or aria-labelledby) and will not function effectively as a landmark.',
'Add aria-label="<Region Purpose>" or aria-labelledby="<heading-id>" to the region landmark.'
);
}
return null;
}
}
+64
View File
@@ -0,0 +1,64 @@
<?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 SelectOptionNotEmpty extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_OPTION_EMPTY';
}
public function getDescription(): string
{
return '<option> elements inside <select> must have non-empty text or a label attribute.';
}
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) !== 'option') {
return null;
}
// Skip <option> inside <datalist> where value attribute acts as label
$parent = $element->parentNode;
if ($parent instanceof DOMElement && strtolower($parent->tagName) === 'datalist') {
return null;
}
$text = trim($element->textContent);
$label = trim($element->getAttribute('label'));
if ($text === '' && $label === '') {
return $this->createViolation(
$element,
'<option> element has no visible text content and no label attribute.',
'Provide descriptive text inside <option>...</option> (e.g., <option value="">Select an option</option>).'
);
}
return null;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?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 SvgFocusableIeEdge extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_1_1_SVG_FOCUSABLE';
}
public function getDescription(): string
{
return 'Decorative SVGs (aria-hidden="true") must include focusable="false" and must not contain focusable links or controls.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'svg') {
return null;
}
if (strtolower(trim($element->getAttribute('aria-hidden'))) !== 'true') {
return null;
}
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new DOMXPath($doc);
$focusableChildren = $xpath->query('.//a[@href] | .//*[@tabindex and @tabindex != "-1"]', $element);
if ($focusableChildren !== false && $focusableChildren->length > 0) {
return $this->createViolation(
$element,
'Decorative <svg aria-hidden="true"> contains focusable child elements, creating invisible keyboard tab stops.',
'Remove interactive links/tabindex from decorative SVGs or remove aria-hidden="true" and provide an accessible name.'
);
}
}
if (strtolower(trim($element->getAttribute('focusable'))) !== 'false') {
return $this->createViolation(
$element,
'Decorative <svg aria-hidden="true"> is missing focusable="false", which may allow stray keyboard focus in legacy browsers and assistive tech.',
'Add focusable="false" alongside aria-hidden="true" on decorative <svg> elements.'
);
}
return null;
}
}
+67
View File
@@ -0,0 +1,67 @@
<?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 TargetSpacingMinimum extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_5_8_TARGET_SPACING';
}
public function getDescription(): string
{
return 'Interactive controls must not use negative margins that cause overlapping tap targets below WCAG 2.2 spacing thresholds (WCAG 2.5.8).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::AA;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
$tag = strtolower($element->tagName);
$role = strtolower($element->getAttribute('role'));
$isInteractive = in_array($tag, ['a', 'button', 'input', 'select'], true)
|| in_array($role, ['button', 'link', 'tab', 'menuitem', 'checkbox', 'radio'], true);
if (!$isInteractive) {
return null;
}
$style = $element->getAttribute('style');
if ($style === '') {
return null;
}
// Detect negative margins on interactive targets (e.g., margin: -4px or margin-left: -10px)
if (preg_match('/margin(?:-(?:top|right|bottom|left))?\s*:\s*[^;]*-\d+(?:\.\d+)?(?:px|rem|em)/i', $style)) {
return $this->createViolation(
$element,
'Interactive element uses negative inline margin which can cause pointer target overlap (WCAG 2.2 SC 2.5.8).',
'Avoid negative margins on interactive controls and ensure at least 24x24px target size or adequate spacing between adjacent controls.'
);
}
return null;
}
}
+84
View File
@@ -0,0 +1,84 @@
<?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 TextareaAccessibleName extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_TEXTAREA_LABEL';
}
public function getDescription(): string
{
return '<textarea> elements must have an accessible name via an associated <label>, aria-label, aria-labelledby, or title.';
}
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) !== 'textarea') {
return null;
}
if (strtolower(trim($element->getAttribute('aria-hidden'))) === 'true' || $element->hasAttribute('hidden')) {
return null;
}
$hasDirectName = ($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')) !== '');
if ($hasDirectName) {
return null;
}
// Check wrapping <label>
$parent = $element->parentNode;
while ($parent instanceof DOMElement) {
if (strtolower($parent->tagName) === 'label') {
return null;
}
$parent = $parent->parentNode;
}
// Check explicit <label for="id">
$id = trim($element->getAttribute('id'));
$doc = $element->ownerDocument;
if ($id !== '' && $doc !== null && preg_match('/^[a-zA-Z0-9_\-:.]+$/', $id)) {
$xpath = new DOMXPath($doc);
$labels = $xpath->query('//label[@for="' . $id . '"]');
if ($labels !== false && $labels->length > 0) {
return null;
}
}
return $this->createViolation(
$element,
'<textarea> element does not have an associated <label>, aria-label, aria-labelledby, or title.',
'Associate a <label for="message">Message</label> with the <textarea id="message"> element.'
);
}
}
+71
View File
@@ -0,0 +1,71 @@
<?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 TimeDatetimeValid extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_TIME_DATETIME';
}
public function getDescription(): string
{
return '<time> elements specifying a datetime attribute must use valid machine-readable ISO-8601 date, time, or duration syntax.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'time' || !$element->hasAttribute('datetime')) {
return null;
}
$dt = trim($element->getAttribute('datetime'));
if ($dt === '' || preg_match('/\{\{|\{%|<\?php/', $dt)) {
return null;
}
// Valid HTML5 <time datetime="..."> formats:
// YYYY, YYYY-MM, YYYY-MM-DD, MM-DD, HH:MM(:SS(.sss))?, YYYY-MM-DD[T ]HH:MM(:SS)?(Z|±HH:MM)?, YYYY-Www, P... duration
$pattern = '/^('
. '\d{4}(?:-\d{2}(?:-\d{2})?)?(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?'
. '|\d{2}-\d{2}'
. '|\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?'
. '|\d{4}-W\d{2}'
. '|P(?:\d+[YMWD])*(?:T(?:\d+[HMS])+)?'
. '|[+-]\d{2}:?\d{2}|Z'
. ')$/';
if (!preg_match($pattern, $dt)) {
return $this->createViolation(
$element,
sprintf('<time> element has invalid machine-readable datetime="%s".', $dt),
'Use a valid ISO-8601 value in datetime (e.g., datetime="2026-11-21" or datetime="2026-11-21T14:30:00Z").'
);
}
return null;
}
}
+83
View File
@@ -0,0 +1,83 @@
<?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 TimeoutWarning extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_2_1_TIMEOUT_WARNING';
}
public function getDescription(): string
{
return 'Session timeout or countdown containers must expose role="timer" and provide a mechanism to extend or pause the time limit (WCAG 2.2.1).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
$hasTimeoutAttr = $element->hasAttribute('data-timeout')
|| $element->hasAttribute('data-session-timeout')
|| $element->hasAttribute('data-countdown');
$idAndClass = strtolower($element->getAttribute('id') . ' ' . $element->getAttribute('class'));
$looksLikeTimeout = $hasTimeoutAttr
|| (bool)preg_match('/\b(session-timeout|timeout-modal|countdown-timer|inactivity-warning)\b/', $idAndClass);
if (!$looksLikeTimeout) {
return null;
}
$role = strtolower($element->getAttribute('role'));
$hasLive = $element->hasAttribute('aria-live') || in_array($role, ['timer', 'alert', 'alertdialog', 'status'], true);
if (!$hasLive) {
return $this->createViolation(
$element,
'Timeout or countdown container is missing role="timer" or an aria-live announcement region (WCAG 2.2.1 Timing Adjustable).',
'Add role="timer" aria-live="polite" and ensure a button allows users to extend, pause, or turn off the time limit.'
);
}
// Check for extend/pause/continue button inside timeout modal/container
if (in_array($role, ['dialog', 'alertdialog'], true) || str_contains($idAndClass, 'timeout')) {
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new DOMXPath($doc);
$buttons = $xpath->query('.//button | .//a[@href] | .//input[@type="button"]', $element);
if ($buttons !== false && $buttons->length === 0) {
return $this->createViolation(
$element,
'Timeout warning container provides no interactive control to extend or pause the session time limit (WCAG 2.2.1).',
'Add a focusable <button type="button">Extend Session</button> inside the timeout container.'
);
}
}
}
return null;
}
}
+190
View File
@@ -0,0 +1,190 @@
<?php
declare(strict_types=1);
namespace YakNet\AccessibilityConsole\Testing;
use PHPUnit\Framework\Assert;
use YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Presets\PresetRegistry;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
/**
* Drop-in PHPUnit trait providing expressive accessibility assertions for
* Laravel, Symfony, and standard PHP test suites.
*/
trait AccessibilityAssertions
{
/**
* Assert that the given HTML string has zero ERROR/CRITICAL accessibility violations
* (and optionally zero or bounded WARNING violations).
*/
protected function assertHtmlAccessible(
string $html,
int $level = 4,
?int $maxWarnings = null,
string $message = ''
): void {
$violations = $this->runAccessibilityScan($html, $level);
$errors = [];
$warnings = [];
foreach ($violations as $v) {
if ($v->severity === Severity::CRITICAL || $v->severity === Severity::ERROR) {
$errors[] = $v;
} elseif ($v->severity === Severity::WARNING) {
$warnings[] = $v;
}
}
Assert::assertEmpty(
$errors,
($message !== '' ? $message . "\n" : '') . sprintf(
"Expected HTML to have 0 critical/error accessibility violations (Level %d), found %d:\n%s",
$level,
count($errors),
$this->formatViolationList($errors)
)
);
if ($maxWarnings !== null) {
Assert::assertLessThanOrEqual(
$maxWarnings,
count($warnings),
($message !== '' ? $message . "\n" : '') . sprintf(
"Expected at most %d accessibility warning(s), found %d:\n%s",
$maxWarnings,
count($warnings),
$this->formatViolationList($warnings)
)
);
}
}
/**
* Assert that the HTML meets or exceeds a minimum accessibility health score (0-100).
*/
protected function assertAccessibilityScoreAtLeast(
string $html,
int $minScore,
int $level = 4,
string $message = ''
): void {
$violations = $this->runAccessibilityScan($html, $level);
$metrics = AccessibilityScoreCalculator::calculate($violations);
$actual = $metrics['score'];
Assert::assertGreaterThanOrEqual(
$minScore,
$actual,
($message !== '' ? $message . ' ' : '') . sprintf(
"Accessibility score %d/100 is below expected minimum %d/100 (%d violations).\n%s",
$actual,
$minScore,
count($violations),
$this->formatViolationList($violations)
)
);
}
/**
* Assert that HTML has zero critical/error violations under a named compliance preset.
*/
protected function assertMeetsAccessibilityPreset(
string $html,
string $presetName = 'wcag22-aa',
string $message = ''
): void {
$registry = new PresetRegistry();
$preset = $registry->get($presetName);
Assert::assertNotNull($preset, "Unknown accessibility preset '{$presetName}'.");
$scanner = new Scanner();
$excluded = $preset->getExcludedRules();
$active = [];
foreach (RuleLevels::getRulesForLevel($preset->getLevel()) as $rule) {
$id = $rule->getId();
if (!in_array($id, $excluded, true)) {
$active[$id] = $rule;
}
}
foreach (RuleLevels::getRulesForLevel(9) as $rule) {
$id = $rule->getId();
if (in_array($id, $preset->getIncludedRules(), true) && !in_array($id, $excluded, true)) {
$active[$id] = $rule;
}
}
foreach ($active as $rule) {
$scanner->addRule($rule);
}
$violations = $scanner->scan($html);
$severe = array_values(array_filter(
$violations,
static fn(Violation $v): bool => $v->severity === Severity::CRITICAL || $v->severity === Severity::ERROR
));
Assert::assertEmpty(
$severe,
($message !== '' ? $message . "\n" : '') . sprintf(
"HTML failed compliance preset '%s' with %d severe violation(s):\n%s",
$presetName,
count($severe),
$this->formatViolationList($severe)
)
);
}
/**
* Assert that a specific accessibility rule ID is not violated in the HTML.
*/
protected function assertNoAccessibilityRuleViolation(
string $html,
string $ruleId,
string $message = ''
): void {
$violations = $this->runAccessibilityScan($html, 5);
$matched = array_values(array_filter(
$violations,
static fn(Violation $v): bool => $v->ruleId === $ruleId
));
Assert::assertEmpty(
$matched,
($message !== '' ? $message . "\n" : '') . sprintf(
"Expected no violation of rule '%s', found %d:\n%s",
$ruleId,
count($matched),
$this->formatViolationList($matched)
)
);
}
/**
* @return Violation[]
*/
private function runAccessibilityScan(string $html, int $level): array
{
$scanner = new Scanner();
foreach (RuleLevels::getRulesForLevel($level) as $rule) {
$scanner->addRule($rule);
}
return $scanner->scan($html);
}
/**
* @param Violation[] $violations
*/
private function formatViolationList(array $violations): string
{
$lines = [];
foreach (array_slice($violations, 0, 10) as $v) {
$lines[] = sprintf(' - [%s] (%s) %s', $v->ruleId, strtoupper($v->severity->value), $v->message);
}
return implode("\n", $lines);
}
}

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