Compare commits

..
8 Commits
133 changed files with 7476 additions and 374 deletions
+162 -53
View File
@@ -1,40 +1,61 @@
# YakNet Accessibility Console 2.9 (AI-Powered Static Analysis)
# YakNet Accessibility Console 3.3 (AI-Powered Static Analysis & WCAG 2.2 Linter)
[![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/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![AI Powered](https://img.shields.io/badge/AI-Powered-purple.svg)](https://gemini.google.com)
[![AI Powered](https://img.shields.io/badge/AI%20Self--Healing-Google%20Gemini-orange.svg)](https://ai.google.dev)
**YakNet Accessibility Console**, web projelerinizdeki erişilebilirlik (WCAG 2.1) hatalarını sadece tespit etmekle kalmayan, aynı zamanda **Yapay Zeka (AI)** desteğiyle bu hataları otomatik olarak düzeltebilen (Self-Healing) profesyonel bir PHP static analysis kütüphanesidir.
**YakNet Accessibility Console**, web 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.
PHPStan ve PHP-CS-Fixer esintili yapısıyla, yerel görünüm şablonlarınızı (`.blade.php`, `.twig`, `.html`, `.php`) doğrudan tarayabilir, baseline desteğiyle mevcut hataları yok sayabilir ve CI/CD süreçlerinize tam entegre çalışabilir.
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.
---
## 🌟 Öne Çıkan Özellikler
- **🤖 AI Self-Healing:** Tespit edilen WCAG hataları için Google Gemini AI üzerinden akıllı çözüm önerileri alır ve kaynak kodunuzu (Blade, Twig, PHP, HTML) otomatik olarak tamir eder.
- **⚡ PHPStan Tarzı Analiz:** Tüm projeyi veya belirli dizinleri komut satırından tarayarak hataları tam dosya yolu ve satır numarası ile listeler.
- **🛡️ Baseline Desteği:** `a11y-baseline.json` oluşturarak mevcut erişilebilirlik hatalarını yok sayabilir, CI/CD pipeline'ınızın sadece yeni hatalarda kırılmasını sağlayabilirsiniz.
- **⚙️ YAML Konfigürasyonu:** `a11y.yaml` dosyası üzerinden tarama yollarını, hariç tutulacak klasörleri, kural seviyelerini ve özel kural setlerini yapılandırabilirsiniz.
- **🔌 Çoklu Çıktı Formatları:**
- `console`: Renkli ve düzenli terminal tablosu.
- `json`: Makine tarafından okunabilir JSON çıktısı.
- `github`: GitHub Actions PR süreçlerinde doğrudan inline hata göstermek için workflow formatı.
- **📊 Görsel Raporlama:** Sonuçları modern bir HTML Dashboard raporu olarak dışarı aktarın.
- **🛡️ 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.
---
## 📦 Kurulum
Composer ile projenize dahil edin:
Composer ile projenize geliştirme bağımlılığı olarak ekleyin:
```bash
composer require yaknet/accessibility-console
composer require --dev yaknet/accessibility-console
```
---
## 🚀 CLI Kullanımı
## 🚀 Komut Satırı (CLI) Kullanımı
### 1. Yapılandırma Dosyası Oluşturma (`init`)
Projenizin kök dizininde varsayılan bir `a11y.yaml` konfigürasyon dosyası oluşturur:
@@ -42,71 +63,129 @@ Projenizin kök dizininde varsayılan bir `a11y.yaml` konfigürasyon dosyası ol
bin/a11y init
```
### 2. Projeyi Tarama (`scan` / `analyse`)
`a11y.yaml` dosyasındaki kurallara ve dizinlere göre tüm projeyi tarar:
### 2. Projeyi veya Dizinleri Tarama (`scan`)
Yapılandırma dosyasındaki yollara göre tüm projeyi tarar:
```bash
bin/a11y scan
```
Belirli bir dizini veya dosyayı hedef göstermek için:
Belirli bir dizini veya şablon klasörünü hedef göstererek taramak için:
```bash
bin/a11y scan resources/views
bin/a11y scan templates/
```
URL veya tek bir yerel HTML dosyasını taramak için (crawler desteğiyle):
Canlı bir web sitesini crawler desteğiyle taramak için:
```bash
bin/a11y scan https://test-siteniz.com --crawl
bin/a11y scan https://siteniz.com --crawl
```
### 3. Baseline Yönetimi
Projeye ait mevcut tüm hataları `a11y-baseline.json` dosyasına kaydederek sonraki taramalarda yok sayılmasını sağlar:
### 3. CI/CD Kalite Kapısı Eşikleri (Quality Gates)
Pipeline süreçlerinde derlemenin kırılma şartlarını belirleyin:
```bash
bin/a11y scan --generate-baseline
# Sağlık skoru 90'ın altındaysa derlemeyi başarısız yap:
bin/a11y scan --min-score=90
# 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
```
### 4. Format ve Raporlama Seçenekleri
Hataları GitHub Actions formatında yazdırmak için:
### 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:
```bash
bin/a11y scan --format=github
```
HTML Raporu kaydetmek için:
```bash
bin/a11y scan --report=report.html
bin/a11y watch resources/views
```
### 5. AI Destekli Otomatik Düzeltme (`fix`)
Tespit edilen tüm hataları yapay zekaya analiz ettirip dosyalarınızı otomatik olarak tamir ettirin:
### 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:
```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
```
Sadece neyin değişeceğini görmek için (`--dry-run`):
```bash
bin/a11y fix --dry-run
# 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
```
### 6. Kuralları Listeleme (`rules`)
Mevcut tüm WCAG kurallarını seviyeleri ve açıklamalarıyla birlikte listeler:
### 8. Kuralları Listeleme ve Filtreleme (`rules`)
Kütüphanede tanımlı 130 kuralı listeleyin, arayın ve filtreleyin:
```bash
# Tüm kuralları listele:
bin/a11y rules
# Kural adına veya açıklamasına göre ara:
bin/a11y rules --search=contrast
# Seviye ve standarda göre filtrele:
bin/a11y rules --standard=AA --level=3
```
---
## ⚙️ Yapılandırma (`a11y.yaml`)
## ⚙️ Yapılandırma Dosyası (`a11y.yaml`)
Projenizi özelleştirmek için `a11y.yaml` dosyasını kullanabilirsiniz:
Projenizin ihtiyaçlarına göre `a11y.yaml` dosyasını özelleştirebilirsiniz:
```yaml
# Tarama yapılacak dizin veya dosyalar
# Tarama yapılacak dizin veya şablon yolları
paths:
- resources/views
- public/templates
- templates
- public/partials
# Hariç tutulacak dizinler
# Hariç tutulacak klasörler
exclude_paths:
- vendor
- node_modules
- storage
- tests/fixtures
# WCAG seviyesi (1-9, varsayılan 4)
# Kural Seviyesi (1: Kritik A -> 5: Kapsamlı AA/AAA)
level: 4
# Varsayılan çıktı formatı (console, json, github)
@@ -115,30 +194,60 @@ format: console
# Baseline dosyası yolu
baseline: a11y-baseline.json
# Kural özelleştirmeleri
# Kural istisnaları ve özel kurallar
rules:
exclude:
- WCAG_1_3_1_FIELDSET # Bu kuralı çalıştırma
- WCAG_1_3_1_FIELDSET # Belirli bir kuralı devre dışı bırak
include:
- App\Rules\CustomAccessibilityRule # Özel kural ekle
- App\Rules\CustomBrandAccessibilityRule # Özel proje kuralı ekle
```
---
## 🔐 Yapay Zeka API Anahtarı
## 📐 Kural Seviyeleri (Rule Levels)
AI düzeltme ve öneri özelliklerini kullanabilmek için projenizin kök dizininde bir `.env` dosyası oluşturup **Google Gemini API** anahtarınızı eklemeniz gerekir:
| 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` |
---
## 🔐 Yapay Zeka (AI) API Yapılandırması
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:
```env
GEMINI_API_KEY=AIzaSyA...your_key_here
GEMINI_API_KEY=AIzaSyA...your_api_key_here
```
---
## 🧪 Geliştirme ve Test
```bash
# Tüm PHPUnit testlerini çalıştır
vendor/bin/phpunit
# PHPStan Level 9 statik tip analizini çalıştır
vendor/bin/phpstan analyse -l 9 src/
```
---
## 🤝 Katkıda Bulunma
Bu proje açık kaynaklıdır ve katkılarınıza açıktır. Lütfen hata bildirimleri için `Issue` açmaktan veya yeni özellikler için `Pull Request` göndermekten çekinmeyin.
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.
---
## 📜 Lisans
Bu yazılım **YakNet Bilişim** tarafından geliştirilmiştir ve **MIT Lisansı** altında lisanslanmıştır. Detaylar için [LICENSE](LICENSE) dosyasına göz atabilirsiniz.
Bu proje **YakNet 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.
+3 -1
View File
@@ -16,14 +16,16 @@ use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\FixCommand;
use YakNet\AccessibilityConsole\Console\Command\InitCommand;
use YakNet\AccessibilityConsole\Console\Command\RulesCommand;
use YakNet\AccessibilityConsole\Console\Command\WatchCommand;
$container = ContainerFactory::create();
$application = new Application('YakNet Accessibility Console', '3.2.0');
$application = new Application('YakNet Accessibility Console', '3.3.0');
// Add commands resolved via DI Container
$application->addCommand($container->get(ScanCommand::class));
$application->addCommand($container->get(FixCommand::class));
$application->addCommand($container->get(InitCommand::class));
$application->addCommand($container->get(RulesCommand::class));
$application->addCommand($container->get(WatchCommand::class));
$application->run();
+11 -11
View File
@@ -12,7 +12,7 @@
"yaknet"
],
"homepage": "https://forum.yak.net.tr",
"version": "3.2.0",
"version": "3.3.0",
"type": "library",
"license": "MIT",
"authors": [
@@ -27,23 +27,23 @@
"ext-dom": "*",
"ext-libxml": "*",
"ext-mbstring": "*",
"symfony/console": "^6.4|^7.0|^8.0",
"symfony/yaml": "^6.4|^7.0|^8.0",
"symfony/console": "^6.4 || ^7.0 || ^8.0",
"symfony/yaml": "^6.4 || ^7.0 || ^8.0",
"monolog/monolog": "^3.0",
"vlucas/phpdotenv": "^5.6",
"google-gemini-php/client": "^1.0|^2.0",
"google-gemini-php/client": "^1.0 || ^2.0",
"guzzlehttp/guzzle": "^7.8",
"masterminds/html5": "^2.8",
"sabberworm/php-css-parser": "^9.4",
"sabberworm/php-css-parser": "^8.4 || ^9.0",
"chrome-php/chrome": "^1.15",
"sebastian/diff": "^5.1 || ^6.0 || ^7.0 || ^8.0 || ^9.0",
"php-di/php-di": "^7.1",
"symfony/css-selector": "^8.1",
"symfony/dom-crawler": "^8.1",
"spatie/color": "^1.5",
"intervention/image": "^3.0",
"dompdf/dompdf": "^3.0",
"phpoffice/phpspreadsheet": "^2.0 || ^3.0"
"symfony/css-selector": "^6.4 || ^7.0 || ^8.0",
"symfony/dom-crawler": "^6.4 || ^7.0 || ^8.0",
"spatie/color": "^1.5 || ^2.0",
"intervention/image": "^2.7 || ^3.0",
"dompdf/dompdf": "^2.0 || ^3.0",
"phpoffice/phpspreadsheet": "^1.28 || ^2.0 || ^3.0"
},
"require-dev": {
"phpunit/phpunit": "^10.5",
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace YakNet\AccessibilityConsole\Analytics;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
class AccessibilityTelemetry
{
/**
* Compute violation density, error distribution, and priority impact metrics.
*
* @param Violation[] $violations
* @param int $totalLinesOfCode
* @return array{
* total_violations: int,
* error_count: int,
* warning_count: int,
* defect_density_per_kloc: float,
* critical_blockers_ratio: float
* }
*/
public function computeMetrics(array $violations, int $totalLinesOfCode = 1000): array
{
$errorCount = 0;
$warningCount = 0;
foreach ($violations as $v) {
if ($v->severity === Severity::ERROR) {
$errorCount++;
} else {
$warningCount++;
}
}
$totalViolations = count($violations);
$kloc = max(1.0, $totalLinesOfCode / 1000.0);
$defectDensity = round($totalViolations / $kloc, 2);
$criticalRatio = ($totalViolations > 0) ? round(($errorCount / $totalViolations) * 100, 1) : 0.0;
return [
'total_violations' => $totalViolations,
'error_count' => $errorCount,
'warning_count' => $warningCount,
'defect_density_per_kloc' => $defectDensity,
'critical_blockers_ratio' => $criticalRatio,
];
}
}
@@ -0,0 +1,77 @@
<?php
namespace YakNet\AccessibilityConsole\Analytics;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class ComplianceMatrixGenerator
{
/** @var array<int|string, string> */
private static array $principleMap = [
1 => 'Perceivable',
2 => 'Operable',
3 => 'Understandable',
4 => 'Robust',
];
/**
* Generate WCAG 2.1 & 2.2 Compliance Matrix from a list of violations and total rules tested.
*
* @param Violation[] $violations
* @param int $totalActiveRules
* @return array{
* overall_compliance_percentage: float,
* principles: array<string, array{violations: int, status: string}>,
* levels: array<string, array{violations: int, percentage: float}>
* }
*/
public function generate(array $violations, int $totalActiveRules = 127): array
{
$principles = [
'Perceivable' => ['violations' => 0, 'status' => 'Pass'],
'Operable' => ['violations' => 0, 'status' => 'Pass'],
'Understandable' => ['violations' => 0, 'status' => 'Pass'],
'Robust' => ['violations' => 0, 'status' => 'Pass'],
];
/** @var array<string, array{violations: int, percentage: float}> $levelCounts */
$levelCounts = [
'A' => ['violations' => 0, 'percentage' => 100.0],
'AA' => ['violations' => 0, 'percentage' => 100.0],
'AAA' => ['violations' => 0, 'percentage' => 100.0],
];
foreach ($violations as $v) {
// Determine principle from rule ID or WCAG code (e.g. WCAG_1_... => Perceivable)
$principleNumber = 4;
if (preg_match('/WCAG_([1-4])_/', $v->ruleId, $m)) {
$principleNumber = (int)$m[1];
}
$pName = self::$principleMap[$principleNumber] ?? 'Robust';
$principles[$pName]['violations']++;
$principles[$pName]['status'] = 'Needs Review';
// Level breakdown
$stdVal = $v->standard->value;
if (array_key_exists($stdVal, $levelCounts)) {
$levelCounts[$stdVal]['violations']++;
}
}
$totalViolations = count($violations);
$overallScore = ($totalActiveRules > 0)
? max(0.0, min(100.0, round((1.0 - ($totalViolations / ($totalActiveRules * 2))) * 100, 1)))
: 100.0;
foreach ($levelCounts as $lvl => &$data) {
$data['percentage'] = max(0.0, min(100.0, round((1.0 - ($data['violations'] / max(1, $totalActiveRules))) * 100, 1)));
}
return [
'overall_compliance_percentage' => $overallScore,
'principles' => $principles,
'levels' => $levelCounts,
];
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace YakNet\AccessibilityConsole\Analytics;
class ReportSummaryModel
{
/**
* @param array<string, int> $violationCountsBySeverity
* @param array<string, int> $violationCountsByStandard
* @param array<string, int> $violationCountsByPrinciple
* @param array<string, mixed> $complianceScores
*/
public function __construct(
public readonly int $totalViolations,
public readonly int $totalFilesScanned,
public readonly int $baselinedCount,
public readonly int $healthScore,
public readonly array $violationCountsBySeverity,
public readonly array $violationCountsByStandard,
public readonly array $violationCountsByPrinciple,
public readonly array $complianceScores,
public readonly float $scanDurationSeconds = 0.0
) {}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'totalViolations' => $this->totalViolations,
'totalFilesScanned' => $this->totalFilesScanned,
'baselinedCount' => $this->baselinedCount,
'healthScore' => $this->healthScore,
'bySeverity' => $this->violationCountsBySeverity,
'byStandard' => $this->violationCountsByStandard,
'byPrinciple' => $this->violationCountsByPrinciple,
'complianceScores' => $this->complianceScores,
'duration' => $this->scanDurationSeconds,
];
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace YakNet\AccessibilityConsole\Badges;
class BadgeGenerator
{
/**
* Generate an SVG badge representing the Accessibility Health Score.
*
* @param int $score 0-100
* @param BadgeOptions|null $options
* @return string Raw SVG markup
*/
public static function generateScoreBadge(int $score, ?BadgeOptions $options = null): string
{
$opts = $options ?? new BadgeOptions();
$color = $opts->rightColor ?? ($score >= 90 ? '#10b981' : ($score >= 70 ? '#f59e0b' : '#ef4444'));
$label = $opts->label;
$value = "{$score}/100";
return self::renderBadge($label, $value, $color, $opts);
}
/**
* Generate an SVG badge representing WCAG compliance status.
*
* @param string $standard E.g. 'WCAG 2.1 AA'
* @param bool $compliant
* @param BadgeOptions|null $options
* @return string Raw SVG markup
*/
public static function generateComplianceBadge(string $standard = 'WCAG 2.1 AA', bool $compliant = true, ?BadgeOptions $options = null): string
{
$opts = $options ?? new BadgeOptions();
$color = $opts->rightColor ?? ($compliant ? '#10b981' : '#ef4444');
$value = $compliant ? 'passed' : 'failed';
return self::renderBadge($standard, $value, $color, $opts);
}
/**
* Generate an SVG badge for total violations count.
*
* @param int $violationsCount
* @param BadgeOptions|null $options
* @return string Raw SVG markup
*/
public static function generateViolationsBadge(int $violationsCount, ?BadgeOptions $options = null): string
{
$opts = $options ?? new BadgeOptions();
$color = $opts->rightColor ?? ($violationsCount === 0 ? '#10b981' : ($violationsCount < 5 ? '#f59e0b' : '#ef4444'));
$value = $violationsCount === 0 ? '0 issues' : "{$violationsCount} issues";
$label = $opts->label !== 'accessibility' ? $opts->label : 'a11y issues';
return self::renderBadge($label, $value, $color, $opts);
}
/**
* Render a standard flat shield SVG badge.
*/
private static function renderBadge(string $label, string $value, string $rightColor, ?BadgeOptions $options = null): string
{
$opts = $options ?? new BadgeOptions();
$charWidth = 7;
$padding = 12;
$leftWidth = (int)(mb_strlen($label) * $charWidth + $padding);
$rightWidth = (int)(mb_strlen($value) * $charWidth + $padding);
$totalWidth = $leftWidth + $rightWidth;
$height = 20;
$leftCenter = (int)($leftWidth / 2);
$rightCenter = (int)($leftWidth + ($rightWidth / 2));
$escLabel = htmlspecialchars($label);
$escValue = htmlspecialchars($value);
$borderRadius = $opts->borderRadius;
$leftColor = $opts->leftColor;
$fontFamily = htmlspecialchars($opts->fontFamily);
$fontSize = $opts->fontSize;
return <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" width="{$totalWidth}" height="{$height}" role="img" aria-label="{$escLabel}: {$escValue}">
<title>{$escLabel}: {$escValue}</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r">
<rect width="{$totalWidth}" height="{$height}" rx="{$borderRadius}" fill="#fff"/>
</clipPath>
<g clip-path="url(#r)">
<rect width="{$leftWidth}" height="{$height}" fill="{$leftColor}"/>
<rect x="{$leftWidth}" width="{$rightWidth}" height="{$height}" fill="{$rightColor}"/>
<rect width="{$totalWidth}" height="{$height}" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="{$fontFamily}" text-rendering="geometricPrecision" font-size="{$fontSize}">
<text aria-hidden="true" x="{$leftCenter}" y="15" fill="#010101" fill-opacity=".3">{$escLabel}</text>
<text x="{$leftCenter}" y="14">{$escLabel}</text>
<text aria-hidden="true" x="{$rightCenter}" y="15" fill="#010101" fill-opacity=".3">{$escValue}</text>
<text x="{$rightCenter}" y="14">{$escValue}</text>
</g>
</svg>
SVG;
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace YakNet\AccessibilityConsole\Badges;
/**
* Options DTO for customizing SVG badge generation.
*/
class BadgeOptions
{
/**
* @param string $label Default left container text label
* @param string $leftColor Hex color code for left container background
* @param string|null $rightColor Optional hex color override for right container background
* @param int $borderRadius Corner radius for SVG clipPath
* @param string $fontFamily Font family CSS rule for badge typography
* @param int $fontSize Font size in pixels
*/
public function __construct(
public readonly string $label = 'accessibility',
public readonly string $leftColor = '#1f2937',
public readonly ?string $rightColor = null,
public readonly int $borderRadius = 3,
public readonly string $fontFamily = 'Verdana,Geneva,DejaVu Sans,sans-serif',
public readonly int $fontSize = 11,
) {
}
}
+21 -13
View File
@@ -26,6 +26,7 @@ class FixCommand extends Command
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to the configuration file (default: a11y.yaml)')
->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping (URL scans only)')
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Show what would be fixed without modifying files')
->addOption('offline', null, InputOption::VALUE_NONE, 'Perform deterministic offline rule-based fixes without calling AI')
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-9)')
->addOption('js', null, InputOption::VALUE_NONE, 'Enable JavaScript rendering using Headless Chrome (URL scans only)');
}
@@ -39,10 +40,11 @@ class FixCommand extends Command
$configPath = is_string($configPathOption) ? $configPathOption : getcwd() . '/a11y.yaml';
$config = Config::fromYaml($configPath);
$offline = (bool)$input->getOption('offline');
$apiKey = $config->getGeminiApiKey();
if (!$apiKey) {
$io->error("GEMINI_API_KEY not found in .env or environment variables. AI fixing requires an API key.");
return Command::FAILURE;
if (!$offline && !$apiKey) {
$io->note("GEMINI_API_KEY not found in .env or environment variables. Running in offline rule-based healing mode (--offline).");
$offline = true;
}
$levelOption = $input->getOption('level');
@@ -53,11 +55,11 @@ class FixCommand extends Command
// If target is a URL, run the legacy URL fixing logic
if ($isUrl) {
return $this->executeUrlFix($target, $level, $apiKey, $input, $output, $io);
return $this->executeUrlFix($target, $level, $apiKey, $input, $output, $io, $offline);
}
// --- LOCAL FILE / DIRECTORY SELF-HEALING ENGINE ---
$io->title("AI Self-Healing Mode - Directory Static Analysis");
$io->title($offline ? "Offline Rule-Based Self-Healing Mode" : "AI Self-Healing Mode - Directory Static Analysis");
$io->writeln("<fg=gray>Configuration loaded from:</> <fg=cyan>$configPath</>");
$dryRun = (bool)$input->getOption('dry-run');
@@ -87,9 +89,9 @@ class FixCommand extends Command
return Command::SUCCESS;
}
$io->note(sprintf("Found %d violations. Starting AI analysis and healing...", count($violations)));
$io->note(sprintf("Found %d violations. Starting %s analysis and healing...", count($violations), $offline ? 'offline rule-based' : 'AI'));
$fixer = new AiFixerManager($apiKey);
$fixer = !$offline ? new AiFixerManager($apiKey) : null;
$diffGenerator = new \YakNet\AccessibilityConsole\Core\Diff\VisualDiffGenerator();
$fixedCount = 0;
@@ -129,9 +131,12 @@ class FixCommand extends Command
if ($rawSuggestion !== null) {
$isLocalFix = true;
} else {
} elseif ($fixer !== null) {
// Fallback to AI Suggestion
$rawSuggestion = $fixer->suggestFix($violation);
} else {
$io->writeln("<fg=yellow>Skipped (Rule requires AI or manual intervention)</>");
continue;
}
$suggestion = $rawSuggestion;
@@ -189,7 +194,7 @@ class FixCommand extends Command
/**
* Legacy URL scan and fix logic
*/
private function executeUrlFix(string $target, int $level, string $apiKey, InputInterface $input, OutputInterface $output, SymfonyStyle $io): int
private function executeUrlFix(string $target, int $level, ?string $apiKey, InputInterface $input, OutputInterface $output, SymfonyStyle $io, bool $offline = false): int
{
$projectPathOption = $input->getOption('project-path');
$projectPath = is_string($projectPathOption) ? $projectPathOption : getcwd();
@@ -199,7 +204,7 @@ class FixCommand extends Command
$dryRun = (bool)$input->getOption('dry-run');
$useJs = (bool)$input->getOption('js');
$io->title("AI Self-Healing Mode - Fixing URL: $target");
$io->title($offline ? "Offline Rule-Based Mode - Fixing URL: $target" : "AI Self-Healing Mode - Fixing URL: $target");
// Fetch HTML
if ($useJs) {
@@ -231,9 +236,9 @@ class FixCommand extends Command
return Command::SUCCESS;
}
$io->note("Found " . count($violations) . " violations. Starting AI analysis...");
$io->note(sprintf("Found %d violations. Starting %s analysis...", count($violations), $offline ? 'offline' : 'AI'));
$fixer = new AiFixerManager($apiKey);
$fixer = (!$offline && is_string($apiKey) && $apiKey !== '') ? new AiFixerManager($apiKey) : null;
$diffGenerator = new \YakNet\AccessibilityConsole\Core\Diff\VisualDiffGenerator();
$locator = new SourceLocator($projectPath);
$fixedCount = 0;
@@ -254,8 +259,11 @@ class FixCommand extends Command
if ($rawSuggestion !== null) {
$isLocalFix = true;
} else {
} elseif ($fixer !== null) {
$rawSuggestion = $fixer->suggestFix($violation);
} else {
$io->writeln("<fg=yellow>Skipped (Rule requires AI or manual intervention)</>");
continue;
}
$suggestion = $rawSuggestion;
+45 -3
View File
@@ -9,13 +9,19 @@ use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
use Symfony\Component\Console\Input\InputOption;
class RulesCommand extends Command
{
protected function configure(): void
{
$this
->setName('rules')
->setDescription('List all available accessibility scanning rules');
->setDescription('List all available accessibility scanning rules')
->addOption('search', 's', InputOption::VALUE_REQUIRED, 'Search rules by ID or description')
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Filter rules by maximum level (1-5)')
->addOption('standard', null, InputOption::VALUE_REQUIRED, 'Filter rules by standard (A, AA, AAA)')
->addOption('severity', null, InputOption::VALUE_REQUIRED, 'Filter rules by severity (error, warning, info)');
}
protected function execute(InputInterface $input, OutputInterface $output): int
@@ -23,10 +29,18 @@ class RulesCommand extends Command
$io = new SymfonyStyle($input, $output);
$io->title("Accessibility Console - Available Rules");
$searchQuery = $input->getOption('search');
$levelFilter = $input->getOption('level');
$standardFilter = $input->getOption('standard');
$severityFilter = $input->getOption('severity');
$maxLevel = is_numeric($levelFilter) ? (int)$levelFilter : 9;
$rules = RuleLevels::getRulesForLevel($maxLevel);
$table = new Table($output);
$table->setHeaders(['Rule ID', 'Standard', 'Severity', 'Level', 'Description']);
$rules = RuleLevels::getRulesForLevel(9);
$matchedCount = 0;
foreach ($rules as $rule) {
$ruleId = ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface)
? $rule->getId()
@@ -36,6 +50,28 @@ class RulesCommand extends Command
$standard = method_exists($rule, 'getStandard') ? $rule->getStandard()->value : '';
$severity = method_exists($rule, 'getSeverity') ? $rule->getSeverity()->value : '';
$level = method_exists($rule, 'getLevel') ? $rule->getLevel() : 4;
// Search filter
if (is_string($searchQuery) && $searchQuery !== '') {
$query = strtolower($searchQuery);
if (!str_contains(strtolower($ruleId), $query) && !str_contains(strtolower($description), $query)) {
continue;
}
}
// Standard filter
if (is_string($standardFilter) && $standardFilter !== '') {
if (strcasecmp($standard, $standardFilter) !== 0) {
continue;
}
}
// Severity filter
if (is_string($severityFilter) && $severityFilter !== '') {
if (strcasecmp($severity, $severityFilter) !== 0) {
continue;
}
}
$table->addRow([
"<fg=cyan;options=bold>$ruleId</>",
@@ -44,11 +80,17 @@ class RulesCommand extends Command
$level,
$description
]);
$matchedCount++;
}
$table->render();
$io->newLine();
$io->note("Total rules available: " . count($rules));
if (is_string($searchQuery) || $levelFilter !== null || is_string($standardFilter) || is_string($severityFilter)) {
$io->note(sprintf("Showing %d matching rules (out of %d total rules).", $matchedCount, count(RuleLevels::getRulesForLevel(9))));
} else {
$io->note("Total rules available: " . count($rules));
}
return Command::SUCCESS;
}
+174 -33
View File
@@ -14,6 +14,7 @@ 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\Rules\RuleLevels;
use YakNet\AccessibilityConsole\Reporting\ConsoleFormatter;
use YakNet\AccessibilityConsole\Reporting\GithubFormatter;
@@ -22,6 +23,12 @@ use YakNet\AccessibilityConsole\Reporting\XmlFormatter;
use YakNet\AccessibilityConsole\Reporting\MarkdownFormatter;
use YakNet\AccessibilityConsole\Reporting\CsvFormatter;
use YakNet\AccessibilityConsole\Reporting\GitLabCodeQualityFormatter;
use YakNet\AccessibilityConsole\Reporting\SarifFormatter;
use YakNet\AccessibilityConsole\Reporting\JunitFormatter;
use YakNet\AccessibilityConsole\Reporting\PdfReportGenerator;
use YakNet\AccessibilityConsole\Reporting\ExcelReportExporter;
use YakNet\AccessibilityConsole\Badges\BadgeGenerator;
use YakNet\AccessibilityConsole\Presets\PresetRegistry;
use YakNet\AccessibilityConsole\Source\SourceLocator;
class ScanCommand extends Command
@@ -35,12 +42,17 @@ class ScanCommand extends Command
->addArgument('target', InputArgument::OPTIONAL, 'The URL, file, or directory path to scan')
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to the configuration file (default: a11y.yaml)')
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-9)')
->addOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format (console, json, github)')
->addOption('preset', 'p', InputOption::VALUE_REQUIRED, 'Use a 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('min-score', null, InputOption::VALUE_REQUIRED, 'Minimum required accessibility health score (0-100) to pass the quality gate')
->addOption('max-warnings', null, InputOption::VALUE_REQUIRED, 'Maximum allowed warnings before failing the quality gate')
->addOption('fail-on', null, InputOption::VALUE_REQUIRED, 'Minimum severity to fail on (error, warning, info)')
->addOption('generate-baseline', null, InputOption::VALUE_NONE, 'Generate a baseline file containing all current violations')
->addOption('baseline', null, InputOption::VALUE_REQUIRED, 'Path to the baseline file')
->addOption('no-progress', null, InputOption::VALUE_NONE, 'Disable progress bar')
->addOption('ai', null, InputOption::VALUE_NONE, 'Enable AI-powered fix suggestions')
->addOption('report', null, InputOption::VALUE_REQUIRED, 'Save report to file (html or json)')
->addOption('report', null, InputOption::VALUE_REQUIRED, 'Save report to file (html, json, sarif, xml, junit, pdf, xlsx)')
->addOption('badge', null, InputOption::VALUE_REQUIRED, 'Save SVG accessibility health badge to file (e.g. a11y-badge.svg)')
->addOption('project-path', null, InputOption::VALUE_REQUIRED, 'Base path for source mapping (URL scans only)')
->addOption('crawl', null, InputOption::VALUE_NONE, 'Crawl internal links recursively (URL scans only)')
->addOption('depth', null, InputOption::VALUE_REQUIRED, 'Maximum crawling depth (URL scans only)', '3')
@@ -61,6 +73,18 @@ class ScanCommand extends Command
$levelOption = $input->getOption('level');
$level = is_numeric($levelOption) ? (int)$levelOption : $config->getLevel();
$presetOption = $input->getOption('preset');
$activePreset = null;
if (is_string($presetOption) && $presetOption !== '') {
$presetRegistry = new PresetRegistry();
$activePreset = $presetRegistry->get($presetOption);
if ($activePreset !== null) {
$level = $activePreset->getLevel();
} else {
$io->warning("Preset '{$presetOption}' not found. Using default rules.");
}
}
$formatOption = $input->getOption('format');
$format = is_string($formatOption) ? $formatOption : $config->getFormat();
@@ -79,9 +103,14 @@ class ScanCommand extends Command
}
// --- LOCAL DIRECTORY / FILE STATIC ANALYSIS ENGINE ---
$io->title("Accessibility Console - Static Analysis");
$io->writeln("<fg=gray>Configuration loaded from:</> <fg=cyan>$configPath</>");
$io->writeln("<fg=gray>Rule Level:</> <fg=yellow>$level</>");
if ($format === 'console') {
$io->title("Accessibility Console - Static Analysis");
$io->writeln("<fg=gray>Configuration loaded from:</> <fg=cyan>$configPath</>");
$io->writeln("<fg=gray>Rule Level:</> <fg=yellow>$level</>");
if ($activePreset !== null) {
$io->writeln("<fg=gray>Compliance Preset:</> <fg=magenta>" . $activePreset->getName() . " (" . $activePreset->getDescription() . ")</>");
}
}
// Resolve paths to scan
$paths = $config->getPaths();
@@ -214,38 +243,88 @@ class ScanCommand extends Command
$formatter = new CsvFormatter();
} elseif ($format === 'gitlab') {
$formatter = new GitLabCodeQualityFormatter();
} elseif ($format === 'sarif') {
$formatter = new SarifFormatter();
} elseif ($format === 'junit') {
$formatter = new JunitFormatter();
}
$exitCode = $formatter->format($violations, $baselinedCount, $io);
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
$score = $metrics['score'];
if ($format === 'console') {
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
$io->section("Accessibility Ratings");
$color = $metrics['score'] >= 90 ? 'green' : ($metrics['score'] >= 70 ? 'yellow' : 'red');
$io->writeln(sprintf("Health Score: <fg=%s>%d/100</>", $color, $metrics['score']));
$color = $score >= 90 ? 'green' : ($score >= 70 ? 'yellow' : 'red');
$io->writeln(sprintf("Health Score: <fg=%s>%d/100</>", $color, $score));
$io->writeln(sprintf(" - Screen Reader / Visual Impact: <fg=cyan>%d%%</>", $metrics['visualImpact']));
$io->writeln(sprintf(" - Keyboard / Motor Impact: <fg=cyan>%d%%</>", $metrics['motorImpact']));
$io->writeln(sprintf(" - Cognitive / Distraction Impact: <fg=cyan>%d%%</>", $metrics['cognitiveImpact']));
$io->newLine();
}
// Quality Gate evaluation
$minScoreOption = $input->getOption('min-score');
$maxWarningsOption = $input->getOption('max-warnings');
$failOnOption = $input->getOption('fail-on');
$errorCount = 0;
$warningCount = 0;
foreach ($violations as $v) {
if ($v->severity === Severity::CRITICAL || $v->severity === Severity::ERROR) {
$errorCount++;
} elseif ($v->severity === Severity::WARNING) {
$warningCount++;
}
}
$qualityGateFailed = false;
/** @var string[] $gateFailures */
$gateFailures = [];
if ($minScoreOption !== null && is_numeric($minScoreOption)) {
$minScore = (int)$minScoreOption;
if ($score < $minScore) {
$qualityGateFailed = true;
$gateFailures[] = sprintf("Accessibility score (%d/100) is lower than the minimum required threshold of %d/100.", $score, $minScore);
}
}
if ($maxWarningsOption !== null && is_numeric($maxWarningsOption)) {
$maxWarnings = (int)$maxWarningsOption;
if ($warningCount > $maxWarnings) {
$qualityGateFailed = true;
$gateFailures[] = sprintf("Warning count (%d) exceeds the maximum allowed limit of %d.", $warningCount, $maxWarnings);
}
}
if (is_string($failOnOption)) {
$failOn = strtolower($failOnOption);
if ($failOn === 'error') {
$exitCode = ($errorCount > 0) ? Command::FAILURE : Command::SUCCESS;
} elseif ($failOn === 'warning') {
$exitCode = ($errorCount > 0 || $warningCount > 0) ? Command::FAILURE : Command::SUCCESS;
}
}
if ($qualityGateFailed) {
$io->newLine();
$io->error("CI/CD Quality Gate Failed:\n- " . implode("\n- ", $gateFailures));
$exitCode = Command::FAILURE;
}
// Export report if --report is specified
$reportPath = $input->getOption('report');
if (is_string($reportPath) && $reportPath !== '') {
$extension = pathinfo($reportPath, PATHINFO_EXTENSION);
if ($extension === 'json') {
$serialized = [];
foreach ($violations as $v) {
$serialized[] = $v->toArray();
}
file_put_contents($reportPath, json_encode($serialized, JSON_PRETTY_PRINT));
} else {
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
// Map violations into page format
$mappedViolations = ['Static Analysis' => $violations];
file_put_contents($reportPath, $reporter->render($mappedViolations, 'Static Analysis'));
}
$io->success("Report saved to: $reportPath");
$this->exportReport($reportPath, $violations, 'Static Analysis', $io);
}
// Export SVG badge if --badge is specified
$badgePath = $input->getOption('badge');
if (is_string($badgePath) && $badgePath !== '') {
file_put_contents($badgePath, BadgeGenerator::generateScoreBadge($score));
$io->success("SVG Badge saved to: $badgePath");
}
return $exitCode;
@@ -438,20 +517,82 @@ class ScanCommand extends Command
$reportPath = $input->getOption('report');
if (is_string($reportPath) && $reportPath !== '') {
$extension = pathinfo($reportPath, PATHINFO_EXTENSION);
if ($extension === 'json') {
$serialized = [];
foreach ($results as $url => $violations) {
$serialized[$url] = array_map(fn($v) => $v->toArray(), $violations);
}
file_put_contents($reportPath, json_encode($serialized, JSON_PRETTY_PRINT));
} else {
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
file_put_contents($reportPath, $reporter->render($results, $target));
$allViolations = [];
foreach ($results as $urlViolations) {
$allViolations = array_merge($allViolations, $urlViolations);
}
$io->success("Report saved to: $reportPath");
$this->exportReport($reportPath, $allViolations, $target, $io, $results);
}
return Command::FAILURE;
}
/**
* Export violations to various file formats (HTML, JSON, SARIF, XML/JUnit, PDF, Excel).
*
* @param string $reportPath
* @param \YakNet\AccessibilityConsole\Core\Violation[] $violations
* @param string $targetName
* @param SymfonyStyle $io
* @param array<string, \YakNet\AccessibilityConsole\Core\Violation[]>|null $pageResults
*/
private function exportReport(
string $reportPath,
array $violations,
string $targetName,
SymfonyStyle $io,
?array $pageResults = null
): void {
$extension = strtolower(pathinfo($reportPath, PATHINFO_EXTENSION));
if ($extension === 'json') {
if ($pageResults !== null) {
$serialized = [];
foreach ($pageResults as $url => $pageViolations) {
$serialized[$url] = array_map(fn($v) => $v->toArray(), $pageViolations);
}
} else {
$serialized = [];
foreach ($violations as $v) {
$serialized[] = $v->toArray();
}
}
file_put_contents($reportPath, (string)json_encode($serialized, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
} elseif ($extension === 'sarif') {
$sarifFormatter = new SarifFormatter();
file_put_contents($reportPath, $sarifFormatter->render($violations));
} elseif ($extension === 'xml' || $extension === 'junit') {
$junitFormatter = new JunitFormatter();
file_put_contents($reportPath, $junitFormatter->render($violations));
} elseif ($extension === 'pdf') {
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
$serialized = [];
foreach ($violations as $v) {
$serialized[] = $v->toArray();
}
$scanResult = [
'score' => $metrics['score'],
'violations' => $serialized,
];
file_put_contents($reportPath, PdfReportGenerator::generatePdf($scanResult, $targetName));
} elseif ($extension === 'xlsx' || $extension === 'xls') {
$metrics = \YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator::calculate($violations);
$serialized = [];
foreach ($violations as $v) {
$serialized[] = $v->toArray();
}
$scanResult = [
'score' => $metrics['score'],
'violations' => $serialized,
];
file_put_contents($reportPath, ExcelReportExporter::exportExcel($scanResult, $targetName));
} else {
$reporter = new \YakNet\AccessibilityConsole\Reporting\HtmlDashboardReporter();
$mapped = $pageResults ?? [$targetName => $violations];
file_put_contents($reportPath, $reporter->render($mapped, $targetName));
}
$io->success("Report saved to: $reportPath");
}
}
+217
View File
@@ -0,0 +1,217 @@
<?php
namespace YakNet\AccessibilityConsole\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\Analyser;
use YakNet\AccessibilityConsole\Core\BaselineManager;
use YakNet\AccessibilityConsole\Core\Config;
use YakNet\AccessibilityConsole\Core\Metrics\AccessibilityScoreCalculator;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Reporting\ConsoleFormatter;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
class WatchCommand extends Command
{
protected function configure(): void
{
$this
->setName('watch')
->setDescription('Continuously watch templates and files for changes and automatically re-scan')
->addArgument('target', InputArgument::OPTIONAL, 'The file or directory path to watch (defaults to config paths)')
->addOption('config', 'c', InputOption::VALUE_REQUIRED, 'Path to configuration file (default: a11y.yaml)')
->addOption('level', 'l', InputOption::VALUE_REQUIRED, 'Accessibility scan level (1-5)')
->addOption('interval', 'i', InputOption::VALUE_REQUIRED, 'Watch poll interval in seconds', '1')
->addOption('max-iterations', null, InputOption::VALUE_REQUIRED, 'Max loop iterations (used for testing/debugging)');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$configPathOption = $input->getOption('config');
$configPath = is_string($configPathOption) ? $configPathOption : getcwd() . '/a11y.yaml';
$config = Config::fromYaml($configPath);
$levelOption = $input->getOption('level');
$level = is_numeric($levelOption) ? (int)$levelOption : $config->getLevel();
$target = $input->getArgument('target');
$paths = $config->getPaths();
if (is_string($target) && $target !== '') {
$paths = [$target];
}
$intervalOption = $input->getOption('interval');
$interval = is_numeric($intervalOption) ? (int)$intervalOption : 1;
if ($interval < 1) {
$interval = 1;
}
$maxIterationsOption = $input->getOption('max-iterations');
$maxIterations = is_numeric($maxIterationsOption) ? (int)$maxIterationsOption : null;
$io->title("Accessibility Console - Real-Time Watch Mode");
$io->writeln("<fg=gray>Watching paths:</> <fg=cyan>" . implode(', ', $paths) . "</>");
$io->writeln("<fg=gray>Rule Level:</> <fg=yellow>$level</>");
$io->writeln("<fg=gray>Poll Interval:</> <fg=yellow>{$interval}s</>");
$io->note("Press Ctrl+C to stop watching.");
// Build Scanner
$scanner = new Scanner();
$rules = RuleLevels::getRulesForLevel($level);
foreach ($rules as $rule) {
$scanner->addRule($rule);
}
$analyser = new Analyser($config, $scanner, new BaselineManager());
// Perform initial scan
$io->section("Initial Scan");
$this->runScanAndPrint($analyser, $paths, $io);
// Map existing files to their last modified timestamp
$fileMtimes = $this->collectFileMtimes($paths, $config->getExcludePaths());
$iteration = 0;
while (true) {
if ($maxIterations !== null && $iteration >= $maxIterations) {
break;
}
$iteration++;
sleep($interval);
$currentMtimes = $this->collectFileMtimes($paths, $config->getExcludePaths());
$changedFiles = $this->detectChangedFiles($fileMtimes, $currentMtimes);
if (!empty($changedFiles)) {
$fileMtimes = $currentMtimes;
$timestamp = date('H:i:s');
$io->newLine();
$io->writeln(sprintf(
"<fg=yellow>[%s]</> Change detected in <fg=cyan>%s</>. Re-scanning...",
$timestamp,
basename($changedFiles[0]) . (count($changedFiles) > 1 ? ' (+' . (count($changedFiles) - 1) . ' more)' : '')
));
// Re-scan changed files or paths
$this->runScanAndPrint($analyser, $changedFiles, $io);
}
}
return Command::SUCCESS;
}
/**
* @param Analyser $analyser
* @param string[] $paths
* @param SymfonyStyle $io
*/
private function runScanAndPrint(Analyser $analyser, array $paths, SymfonyStyle $io): void
{
$start = microtime(true);
$result = $analyser->analyse($paths);
$elapsed = round(microtime(true) - $start, 3);
$violations = $result['violations'];
$formatter = new ConsoleFormatter();
$formatter->format($violations, $result['baselinedCount'], $io);
$metrics = AccessibilityScoreCalculator::calculate($violations);
$score = $metrics['score'];
$color = $score >= 90 ? 'green' : ($score >= 70 ? 'yellow' : 'red');
$io->writeln(sprintf(
"Health Score: <fg=%s;options=bold>%d/100</> | Scan time: <fg=gray>%ss</>",
$color,
$score,
$elapsed
));
}
/**
* @param string[] $paths
* @param string[] $excludePaths
* @return array<string, int>
*/
public function collectFileMtimes(array $paths, array $excludePaths): array
{
$mtimes = [];
$extensions = ['php', 'html', 'twig', 'blade.php'];
foreach ($paths as $path) {
if (is_file($path)) {
$mtimes[$path] = (int)filemtime($path);
continue;
}
if (!is_dir($path)) {
continue;
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS)
);
/** @var \SplFileInfo $file */
foreach ($iterator as $file) {
if (!$file->isFile()) {
continue;
}
$filename = $file->getFilename();
$ext = $file->getExtension();
$isMatching = in_array($ext, ['php', 'html', 'twig'], true) || str_ends_with($filename, '.blade.php');
if (!$isMatching) {
continue;
}
$filePath = (string)$file->getRealPath();
$excluded = false;
foreach ($excludePaths as $ex) {
if (str_contains(str_replace('\\', '/', $filePath), '/' . trim($ex, '/') . '/')) {
$excluded = true;
break;
}
}
if (!$excluded) {
$mtimes[$filePath] = (int)$file->getMTime();
}
}
}
return $mtimes;
}
/**
* @param array<string, int> $oldMtimes
* @param array<string, int> $newMtimes
* @return string[]
*/
public function detectChangedFiles(array $oldMtimes, array $newMtimes): array
{
$changed = [];
foreach ($newMtimes as $file => $mtime) {
if (!isset($oldMtimes[$file]) || $oldMtimes[$file] !== $mtime) {
$changed[] = $file;
}
}
foreach ($oldMtimes as $file => $mtime) {
if (!isset($newMtimes[$file])) {
$changed[] = $file;
}
}
return array_values(array_unique($changed));
}
}
+14 -3
View File
@@ -24,7 +24,17 @@ abstract class AbstractRule
return 4;
}
protected function createViolation(string $message, \DOMElement $element): Violation
public function getId(): string
{
return (new \ReflectionClass($this))->getShortName();
}
public function getDescription(): string
{
return '';
}
protected function createViolation(string $message, \DOMElement $element, ?string $suggestion = null): Violation
{
$doc = $element->ownerDocument;
$html = '';
@@ -36,11 +46,12 @@ abstract class AbstractRule
}
return new Violation(
ruleId: (new \ReflectionClass($this))->getShortName(),
ruleId: $this->getId(),
message: $message,
severity: $this->getSeverity(),
standard: $this->getStandard(),
htmlSnippet: $html
htmlSnippet: $html,
fixSuggestion: $suggestion
);
}
}
+30 -79
View File
@@ -5,6 +5,8 @@ namespace YakNet\AccessibilityConsole\Core;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
use YakNet\AccessibilityConsole\Core\Locator\PreciseElementLocator;
use YakNet\AccessibilityConsole\Parser\TemplatePreprocessor;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
class Analyser
@@ -12,13 +14,22 @@ class Analyser
private Config $config;
private Scanner $scanner;
private BaselineManager $baselineManager;
private TemplatePreprocessor $templatePreprocessor;
private PreciseElementLocator $elementLocator;
private string $projectRoot;
public function __construct(?Config $config = null, ?Scanner $scanner = null, ?BaselineManager $baselineManager = null)
{
public function __construct(
?Config $config = null,
?Scanner $scanner = null,
?BaselineManager $baselineManager = null,
?TemplatePreprocessor $templatePreprocessor = null,
?PreciseElementLocator $elementLocator = 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();
$cwd = getcwd();
$this->projectRoot = $cwd ? str_replace('\\', '/', realpath($cwd) ?: $cwd) : '.';
@@ -108,14 +119,17 @@ class Analyser
$onProgress($file, $index + 1, $totalFiles);
}
$content = @file_get_contents($file);
if ($content === false || trim($content) === '') {
$rawContent = @file_get_contents($file);
if ($rawContent === false || trim($rawContent) === '') {
continue;
}
// 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($content);
$fileViolations = $this->scanner->scan($scanContent);
} catch (\Throwable $e) {
// Skip if parsing failed dramatically
continue;
@@ -124,14 +138,17 @@ class Analyser
$relativeFile = $this->makePathRelative($file);
foreach ($fileViolations as $violation) {
// Find line number using line-by-line helper
$line = $this->locateLineInContent($content, $violation->htmlSnippet);
// Store location in violation
$violation->location = [
'file' => $relativeFile,
'line' => $line
];
// 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 = [
'file' => $relativeFile,
'line' => $location['line'],
'column' => $location['column'],
];
} else {
$violation->location['file'] = $relativeFile;
}
// Check if ignored in baseline
if ($this->baselineManager->isIgnored($relativeFile, $violation->ruleId, $violation->htmlSnippet)) {
@@ -221,70 +238,4 @@ class Analyser
return $files;
}
private function locateLineInContent(string $content, string $snippet): int
{
$replaced = preg_replace('/\s+/', ' ', $snippet);
$cleanSnippet = is_string($replaced) ? trim($replaced) : '';
if ($cleanSnippet === '') {
return 1;
}
$searchSnippet = mb_strlen($cleanSnippet) > 150 ? mb_substr($cleanSnippet, 0, 150) : $cleanSnippet;
$lines = explode("\n", $content);
// 1. Exact match pass
foreach ($lines as $index => $line) {
$replacedLine = preg_replace('/\s+/', ' ', $line);
$cleanLine = is_string($replacedLine) ? trim($replacedLine) : '';
if (str_contains($cleanLine, $searchSnippet)) {
return $index + 1;
}
}
// 2. Parse snippet to find tag and attributes for fuzzy match pass
preg_match('/<([a-zA-Z0-9]+)/', $snippet, $matches);
$tagName = $matches[1] ?? null;
if (!$tagName) {
return 1;
}
preg_match_all('/([a-zA-Z0-9-]+)=["\']([^"\']*)["\']/', $snippet, $attrMatches, PREG_SET_ORDER);
$attributes = [];
foreach ($attrMatches as $match) {
$attributes[$match[1]] = $match[2];
}
$bestLine = 1;
$maxScore = 0;
foreach ($lines as $index => $line) {
$replacedLine = preg_replace('/\s+/', ' ', $line);
$cleanLine = is_string($replacedLine) ? trim($replacedLine) : '';
if (!str_contains(strtolower($cleanLine), '<' . strtolower($tagName))) {
continue;
}
$score = 1.0;
if (in_array(strtolower($tagName), ['html', 'head', 'body', 'title'], true)) {
$score += 1.0;
}
foreach ($attributes as $name => $value) {
if (str_contains($cleanLine, "$name=\"$value\"") || str_contains($cleanLine, "$name='$value'")) {
$score += 2.0;
} elseif (str_contains($cleanLine, $name . '=')) {
$score += 0.5;
}
}
if ($score > $maxScore) {
$maxScore = $score;
$bestLine = $index + 1;
}
}
return $bestLine;
}
}
+4
View File
@@ -11,6 +11,7 @@ use YakNet\AccessibilityConsole\Console\Command\ScanCommand;
use YakNet\AccessibilityConsole\Console\Command\FixCommand;
use YakNet\AccessibilityConsole\Console\Command\InitCommand;
use YakNet\AccessibilityConsole\Console\Command\RulesCommand;
use YakNet\AccessibilityConsole\Console\Command\WatchCommand;
class ContainerFactory
{
@@ -51,6 +52,9 @@ class ContainerFactory
RulesCommand::class => function () {
return new RulesCommand();
},
WatchCommand::class => function () {
return new WatchCommand();
},
]);
return $builder->build();
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace YakNet\AccessibilityConsole\Core\Locator;
class PreciseElementLocator
{
/**
* Locate the exact line and column of an HTML snippet within file content.
*
* @param string $content Full file content
* @param string $snippet HTML snippet of the violating element
* @return array{line: int, column: int}
*/
public function locate(string $content, string $snippet): array
{
$cleanSnippet = trim(preg_replace('/\s+/', ' ', $snippet) ?? '');
if ($cleanSnippet === '') {
return ['line' => 1, 'column' => 1];
}
// 1. Exact substring match pass
$exactPos = strpos($content, $snippet);
if ($exactPos !== false) {
return $this->getLineAndColumn($content, $exactPos);
}
// 2. Normalized whitespace search pass
$lines = explode("\n", $content);
$searchSnippet = mb_strlen($cleanSnippet) > 120 ? mb_substr($cleanSnippet, 0, 120) : $cleanSnippet;
foreach ($lines as $index => $line) {
$cleanLine = trim(preg_replace('/\s+/', ' ', $line) ?? '');
if ($cleanLine !== '' && str_contains($cleanLine, $searchSnippet)) {
$col = strpos($line, mb_substr($searchSnippet, 0, 20));
return [
'line' => $index + 1,
'column' => ($col !== false) ? $col + 1 : 1
];
}
}
// 3. Tag & Attribute Token Match Pass
preg_match('/<([a-zA-Z0-9:-]+)/', $snippet, $tagMatch);
$tagName = strtolower($tagMatch[1] ?? '');
if ($tagName !== '') {
preg_match_all('/([a-zA-Z0-9_:-]+)=["\']([^"\']*)["\']/', $snippet, $attrMatches, PREG_SET_ORDER);
$attributes = [];
foreach ($attrMatches as $m) {
$attributes[$m[1]] = $m[2];
}
$bestLine = 1;
$bestCol = 1;
$maxScore = 0.0;
foreach ($lines as $index => $line) {
$lineLower = strtolower($line);
$tagStr = '<' . $tagName;
if (!str_contains($lineLower, $tagStr)) {
continue;
}
$score = 1.0;
foreach ($attributes as $attrName => $attrVal) {
if (str_contains($line, "$attrName=\"$attrVal\"") || str_contains($line, "$attrName='$attrVal'")) {
$score += 3.0;
} elseif (str_contains($line, "$attrName=")) {
$score += 1.0;
}
}
if ($score > $maxScore) {
$maxScore = $score;
$bestLine = $index + 1;
$col = strpos($lineLower, $tagStr);
$bestCol = ($col !== false) ? $col + 1 : 1;
}
}
if ($maxScore > 0) {
return ['line' => $bestLine, 'column' => $bestCol];
}
}
return ['line' => 1, 'column' => 1];
}
/**
* @return array{line: int, column: int}
*/
private function getLineAndColumn(string $content, int $offset): array
{
if ($offset <= 0) {
return ['line' => 1, 'column' => 1];
}
$before = substr($content, 0, $offset);
$line = substr_count($before, "\n") + 1;
$lastNewline = strrpos($before, "\n");
$column = ($lastNewline === false) ? $offset + 1 : $offset - $lastNewline;
return ['line' => $line, 'column' => $column];
}
}
+48 -15
View File
@@ -2,6 +2,11 @@
namespace YakNet\AccessibilityConsole\Core;
use DOMDocument;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Rules\RuleInterface;
class RuleEngine
{
/** @var array<int, mixed> */
@@ -13,32 +18,60 @@ class RuleEngine
}
/**
* @return array<int, mixed>
*/
public function getRules(): array
{
return $this->rules;
}
/**
* Run all registered rules against the DOMDocument using single-pass DOM traversal.
*
* @param DOMDocument $doc
* @return Violation[]
*/
public function run(\DOMDocument $doc): array
public function run(DOMDocument $doc): array
{
$allViolations = [];
$docRules = [];
$elementRules = [];
foreach ($this->rules as $rule) {
if ($rule instanceof AbstractRule) {
// Document-level rule (Core\AbstractRule style)
$violations = $rule->check($doc);
$allViolations = array_merge($allViolations, $violations);
} elseif ($rule instanceof \YakNet\AccessibilityConsole\Rules\RuleInterface) {
// Element-level rule (Rules\RuleInterface style)
$xpath = new \DOMXPath($doc);
$elements = $xpath->query('//*');
if ($elements !== false) {
foreach ($elements as $element) {
if ($element instanceof \DOMElement) {
$violation = $rule->check($element);
if ($violation) {
$allViolations[] = $violation;
}
$docRules[] = $rule;
} elseif ($rule instanceof RuleInterface) {
$elementRules[] = $rule;
}
}
// 1. Run Document-level rules
foreach ($docRules as $rule) {
$violations = $rule->check($doc);
$allViolations = array_merge($allViolations, $violations);
}
// 2. Run Element-level rules in a single DOM pass
if (!empty($elementRules)) {
$xpath = new DOMXPath($doc);
$elements = $xpath->query('//*');
if ($elements !== false) {
foreach ($elements as $element) {
if (!$element instanceof DOMElement) {
continue;
}
foreach ($elementRules as $rule) {
$violation = $rule->check($element);
if ($violation !== null) {
$allViolations[] = $violation;
}
}
}
}
}
return $allViolations;
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace YakNet\AccessibilityConsole\Core;
use ReflectionClass;
use YakNet\AccessibilityConsole\Rules\RuleInterface;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
class RuleRegistry
{
/**
* Validate an array of rule instances for ID uniqueness, interfaces, and validity.
*
* @param array<int, mixed> $rules
* @return array{valid: bool, errors: array<int, string>, count: int}
*/
public static function validate(array $rules): array
{
$errors = [];
$ids = [];
foreach ($rules as $rule) {
if (!is_object($rule)) {
$errors[] = "Non-object rule encountered in rule set.";
continue;
}
$className = get_class($rule);
$reflection = new ReflectionClass($rule);
$isDocRule = $rule instanceof AbstractRule;
$isElementRule = $rule instanceof RuleInterface;
if (!$isDocRule && !$isElementRule) {
$errors[] = "Class {$className} does not implement RuleInterface or extend AbstractRule.";
continue;
}
$ruleId = method_exists($rule, 'getId') ? $rule->getId() : $reflection->getShortName();
if (isset($ids[$ruleId])) {
$errors[] = "Duplicate Rule ID '{$ruleId}' detected across classes: {$ids[$ruleId]} and {$className}.";
} else {
$ids[$ruleId] = $className;
}
if (!method_exists($rule, 'getStandard')) {
$errors[] = "Rule {$className} is missing getStandard() method.";
}
if (!method_exists($rule, 'getSeverity')) {
$errors[] = "Rule {$className} is missing getSeverity() method.";
}
}
return [
'valid' => empty($errors),
'errors' => $errors,
'count' => count($rules),
];
}
/**
* Get metadata for a specific rule instance.
*
* @param object $rule
* @return array<string, mixed>
*/
public static function getMetadata(object $rule): array
{
$reflection = new ReflectionClass($rule);
$id = method_exists($rule, 'getId') ? $rule->getId() : $reflection->getShortName();
$desc = method_exists($rule, 'getDescription') ? $rule->getDescription() : '';
$standard = method_exists($rule, 'getStandard') ? $rule->getStandard()->value : 'A';
$severity = method_exists($rule, 'getSeverity') ? $rule->getSeverity()->value : 'error';
$level = method_exists($rule, 'getLevel') ? $rule->getLevel() : 4;
return [
'id' => $id,
'class' => $reflection->getName(),
'shortName' => $reflection->getShortName(),
'description' => $desc,
'standard' => $standard,
'severity' => $severity,
'level' => $level,
'type' => ($rule instanceof AbstractRule) ? 'document' : 'element',
];
}
}
+9
View File
@@ -16,6 +16,11 @@ class Scanner
$this->engine->addRule($rule);
}
public function getEngine(): RuleEngine
{
return $this->engine;
}
/**
* Scan HTML content for accessibility violations.
*
@@ -33,6 +38,10 @@ class Scanner
]);
$doc = $html5->loadHTML($html);
// Attach raw HTML property for syntax/token level analysis
/** @phpstan-ignore-next-line */
@$doc->rawHtml = $html;
return $this->engine->run($doc);
}
}
+80 -2
View File
@@ -18,7 +18,80 @@ class LocalHealer
$ruleId = $violation->ruleId;
switch ($ruleId) {
case 'WCAG_1_1_1_IMG_ALT':
case 'WCAG_1_1_1_ImageAlt':
case 'ImageAlt':
case 'ImgAltText':
if (preg_match('/<img\b(?![^>]*\balt=)/i', $snippet)) {
$fixed = preg_replace('/<img\b/i', '<img alt=""', $snippet) ?: $snippet;
return "EXPLANATION: Injected missing alt=\"\" attribute for decorative image.\nFIX: " . $fixed;
}
break;
case 'WCAG_1_1_1_SVG':
case 'SvgAltText':
if (preg_match('/<svg\b(?![^>]*\baria-hidden=)(?![^>]*\baria-label=)/i', $snippet) && !str_contains($snippet, '<title>')) {
$fixed = preg_replace('/<svg\b/i', '<svg aria-hidden="true"', $snippet) ?: $snippet;
return "EXPLANATION: Injected aria-hidden=\"true\" to decorative SVG element.\nFIX: " . $fixed;
}
break;
case 'WCAG_LINK_TARGET_BLANK':
case 'LinkTargetBlank':
if (preg_match('/<a\b[^>]*\btarget=["\']_blank["\']/i', $snippet)) {
if (preg_match('/rel=["\']([^"\']*)["\']/i', $snippet, $matches)) {
$existingRel = $matches[1];
$newRel = trim($existingRel . ' noopener noreferrer');
$fixed = str_replace($matches[0], 'rel="' . $newRel . '"', $snippet);
} else {
$fixed = preg_replace('/<a\b/i', '<a rel="noopener noreferrer"', $snippet) ?: $snippet;
}
return "EXPLANATION: Added rel=\"noopener noreferrer\" to target=\"_blank\" link.\nFIX: " . $fixed;
}
break;
case 'WCAG_2_4_3_TABINDEX':
case 'TabindexOrder':
if (preg_match('/\btabindex=["\'][1-9]\d*["\']/i', $snippet)) {
$fixed = preg_replace('/\btabindex=["\'][1-9]\d*["\']/i', 'tabindex="0"', $snippet) ?: $snippet;
return "EXPLANATION: Normalized positive tabindex to tabindex=\"0\" to maintain natural tab order.\nFIX: " . $fixed;
}
break;
case 'WCAG_1_3_1_TABLE_SCOPE':
case 'ScopeOnlyOnHeaders':
if (preg_match('/<td\b[^>]*\bscope=["\'][^"\']*["\']/i', $snippet)) {
$fixed = preg_replace('/\s+scope=["\'][^"\']*["\']/i', '', $snippet) ?: $snippet;
return "EXPLANATION: Removed invalid scope attribute from <td> element.\nFIX: " . $fixed;
}
break;
case 'WCAG_2_2_1_META_REFRESH':
case 'MetaRefreshBanned':
if (preg_match('/<meta\b[^>]*\bhttp-equiv=["\']refresh["\'][^>]*>/i', $snippet)) {
$fixed = '<!-- ' . trim($snippet) . ' (Removed: Meta refresh disorients users) -->';
return "EXPLANATION: Commented out disorienting meta refresh tag.\nFIX: " . $fixed;
}
break;
case 'WCAG_1_3_1_OPTGROUP_LABEL':
case 'OptgroupLabel':
if (preg_match('/<optgroup\b(?![^>]*\blabel=)/i', $snippet)) {
$fixed = preg_replace('/<optgroup\b/i', '<optgroup label="Options"', $snippet) ?: $snippet;
return "EXPLANATION: Added fallback label=\"Options\" attribute to <optgroup>.\nFIX: " . $fixed;
}
break;
case 'WCAG_2_4_7_FOCUS_OUTLINE':
case 'NoFocusOutline':
if (preg_match('/style=["\'][^"\']*outline\s*:\s*(?:none|0)[^"\']*["\']/i', $snippet)) {
$fixed = preg_replace('/outline\s*:\s*(?:none|0)/i', 'outline: 2px solid transparent; outline-offset: 2px', $snippet) ?: $snippet;
return "EXPLANATION: Replaced outline removal with accessible transparent outline.\nFIX: " . $fixed;
}
break;
case 'WCAG_2_2_2_BLINK':
case 'BlinkTagBanned':
$fixed = str_replace(
['<blink>', '</blink>', '<BLINK>', '</BLINK>'],
['<span style="text-decoration: blink;">', '</span>', '<span style="text-decoration: blink;">', '</span>'],
@@ -27,14 +100,17 @@ class LocalHealer
return "EXPLANATION: Banned <blink> tag replaced with a span and text-decoration style.\nFIX: " . $fixed;
case 'WCAG_2_4_3_AUTOFOCUS':
case 'AutofocusBanned':
$fixed = preg_replace('/\s+autofocus(=["\'](.*?)["\'])?/i', '', $snippet) ?: $snippet;
return "EXPLANATION: Autofocus attribute removed to prevent screen reader interruption on load.\nFIX: " . $fixed;
case 'WCAG_1_3_1_TABLE_SUMMARY':
case 'TableSummaryBanned':
$fixed = preg_replace('/\s+summary=["\'](.*?)["\']/i', '', $snippet) ?: $snippet;
return "EXPLANATION: Deprecated table summary attribute removed. Use caption elements instead.\nFIX: " . $fixed;
case 'WCAG_2_1_1_SCROLLABLE_FOCUS':
case 'ScrollableRegionFocusable':
if (!str_contains($snippet, 'tabindex')) {
$fixed = preg_replace('/(style=["\'](.*?)["\'])/i', '$1 tabindex="0"', $snippet) ?: $snippet;
return "EXPLANATION: Added tabindex=\"0\" to scrollable region to allow keyboard scrolling.\nFIX: " . $fixed;
@@ -42,6 +118,7 @@ class LocalHealer
break;
case 'WCAG_1_3_1_PRESENTATION_TAGS':
case 'PresentationTagsBanned':
if (preg_match('/<center>(.*?)<\/center>/is', $snippet, $matches)) {
$fixed = '<div style="text-align: center;">' . $matches[1] . '</div>';
return "EXPLANATION: Center element replaced with div and text-align CSS.\nFIX: " . $fixed;
@@ -53,9 +130,10 @@ class LocalHealer
break;
case 'WCAG_3_1_1_LANG':
case 'HtmlHasLang':
if (preg_match('/<html(\s+[^>]*>|>)/i', $snippet)) {
$fixed = preg_replace('/<html/i', '<html lang="en"', $snippet) ?: $snippet;
return "EXPLANATION: Injected default lang=\"en\" to HTML element.\nFIX: " . $fixed;
$fixed = preg_replace('/<html/i', '<html lang="tr"', $snippet) ?: $snippet;
return "EXPLANATION: Injected default lang=\"tr\" to HTML element.\nFIX: " . $fixed;
}
break;
}
+3 -3
View File
@@ -5,20 +5,20 @@ namespace YakNet\AccessibilityConsole\Core;
class Violation
{
/**
* @param array{file: string, line: int}|null $location
* @param array{file?: string, line: int, column?: int}|null $location
*/
public function __construct(
public string $ruleId,
public string $message,
public Severity $severity,
public WCAGStandard $standard,
public string $htmlSnippet,
public string $htmlSnippet = '',
public ?array $location = null, // ['file' => '...', 'line' => 0]
public ?string $fixSuggestion = null
) {}
/**
* @return array{ruleId: string, message: string, severity: string, standard: string, htmlSnippet: string, location: array{file: string, line: int}|null, fixSuggestion: string|null}
* @return array{ruleId: string, message: string, severity: string, standard: string, htmlSnippet: string, location: array{file?: string, line: int, column?: int}|null, fixSuggestion: string|null}
*/
public function toArray(): array
{
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace YakNet\AccessibilityConsole\Notifications;
use GuzzleHttp\Client;
class DiscordNotifier implements NotifierInterface
{
private Client $httpClient;
public function __construct(
private string $webhookUrl,
?Client $httpClient = null
) {
$this->httpClient = $httpClient ?? new Client(['timeout' => 5.0]);
}
public function send(NotificationPayload $payload): bool
{
if ($this->webhookUrl === '') {
return false;
}
// Color in decimal for Discord embed
$color = $payload->healthScore >= 90 ? 0x10b981 : ($payload->healthScore >= 70 ? 0xf59e0b : 0xef4444);
$body = [
'embeds' => [
[
'title' => "♿ Accessibility Audit: {$payload->target}",
'color' => $color,
'fields' => [
[
'name' => 'Health Score',
'value' => sprintf('%d / 100', $payload->healthScore),
'inline' => true,
],
[
'name' => 'Total Violations',
'value' => (string)$payload->totalViolations,
'inline' => true,
],
[
'name' => 'Breakdown',
'value' => sprintf('Errors: %d | Warnings: %d', $payload->errorCount, $payload->warningCount),
'inline' => false,
],
],
'footer' => [
'text' => 'YakNet Accessibility Console',
],
'timestamp' => date('c'),
],
],
];
try {
$response = $this->httpClient->post($this->webhookUrl, [
'json' => $body,
]);
return $response->getStatusCode() < 300;
} catch (\Throwable) {
return false;
}
}
}
@@ -0,0 +1,35 @@
<?php
namespace YakNet\AccessibilityConsole\Notifications;
class NotificationDispatcher
{
/**
* @var array<string, NotifierInterface>
*/
private array $notifiers = [];
public function addNotifier(string $channel, NotifierInterface $notifier): void
{
$this->notifiers[$channel] = $notifier;
}
/**
* Dispatch notification payload across all registered notifiers.
*
* @return array<string, bool> Channel delivery results
*/
public function dispatch(NotificationPayload $payload): array
{
$results = [];
foreach ($this->notifiers as $channel => $notifier) {
$results[$channel] = $notifier->send($payload);
}
return $results;
}
public function hasNotifiers(): bool
{
return !empty($this->notifiers);
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace YakNet\AccessibilityConsole\Notifications;
class NotificationPayload
{
/**
* @param array<int, array<string, mixed>> $topViolations
*/
public function __construct(
public string $target,
public int $healthScore,
public int $totalViolations,
public int $errorCount,
public int $warningCount,
public array $topViolations = []
) {}
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace YakNet\AccessibilityConsole\Notifications;
interface NotifierInterface
{
public function send(NotificationPayload $payload): bool;
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace YakNet\AccessibilityConsole\Notifications;
use GuzzleHttp\Client;
class SlackNotifier implements NotifierInterface
{
private Client $httpClient;
public function __construct(
private string $webhookUrl,
?Client $httpClient = null
) {
$this->httpClient = $httpClient ?? new Client(['timeout' => 5.0]);
}
public function send(NotificationPayload $payload): bool
{
if ($this->webhookUrl === '') {
return false;
}
$color = $payload->healthScore >= 90 ? '#10b981' : ($payload->healthScore >= 70 ? '#f59e0b' : '#ef4444');
$status = $payload->healthScore >= 90 ? 'PASSED' : 'FAILED';
$body = [
'attachments' => [
[
'color' => $color,
'title' => "♿ Accessibility Audit: {$payload->target}",
'text' => sprintf(
"*Health Score:* %d/100 (%s)\n*Total Violations:* %d (Errors: %d, Warnings: %d)",
$payload->healthScore,
$status,
$payload->totalViolations,
$payload->errorCount,
$payload->warningCount
),
'footer' => 'YakNet Accessibility Console',
'ts' => time(),
],
],
];
try {
$response = $this->httpClient->post($this->webhookUrl, [
'json' => $body,
]);
return $response->getStatusCode() < 300;
} catch (\Throwable) {
return false;
}
}
}
+22 -9
View File
@@ -6,15 +6,28 @@ class BladeParser implements ParserInterface
{
public function parse(string $content): string
{
// Replace {!! ... !!} with static text
$content = preg_replace('/\{\!\!(.*?)\!\!\}/s', 'StaticRawBladeContent', $content) ?? $content;
// Replace {{ ... }} with static text
$content = preg_replace('/\{\{\s*(.*?)\s*\}\}/s', 'StaticBladeContent', $content) ?? $content;
// Strip Blade directives like @if, @else, @endif, @foreach, @endforeach, etc.
$content = preg_replace('/@[a-zA-Z0-9_]+\s*(\(.*?\))?/i', '', $content) ?? $content;
// 1. Strip Blade comments {{-- ... --}} while preserving line count
$content = preg_replace_callback('/\{\{--(.*?)--\}\}/s', function ($m) {
return str_repeat("\n", substr_count($m[0], "\n"));
}, $content) ?? $content;
// 2. Replace raw echo {!! ... !!} while preserving line count
$content = preg_replace_callback('/\{\!\!(.*?)\!\!\}/s', function ($m) {
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
return 'StaticRawBladeContent' . $newlines;
}, $content) ?? $content;
// 3. Replace safe echo {{ ... }} while preserving line count
$content = preg_replace_callback('/\{\{\s*(.*?)\s*\}\}/s', function ($m) {
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
return 'StaticBladeContent' . $newlines;
}, $content) ?? $content;
// 4. Strip Blade directives like @if, @else, @endif, @foreach, @component, etc.
$content = preg_replace_callback('/@[a-zA-Z0-9_]+\s*(\([^\)]*\))?/s', function ($m) {
return str_repeat("\n", substr_count($m[0], "\n"));
}, $content) ?? $content;
return $content;
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace YakNet\AccessibilityConsole\Parser;
class TemplatePreprocessor
{
private BladeParser $bladeParser;
private TwigParser $twigParser;
private HtmlParser $htmlParser;
public function __construct(
?BladeParser $bladeParser = null,
?TwigParser $twigParser = null,
?HtmlParser $htmlParser = null
) {
$this->bladeParser = $bladeParser ?? new BladeParser();
$this->twigParser = $twigParser ?? new TwigParser();
$this->htmlParser = $htmlParser ?? new HtmlParser();
}
/**
* Preprocess file content according to its file extension or template dialect.
*
* @param string $content
* @param string|null $filePath
* @return string
*/
public function preprocess(string $content, ?string $filePath = null): string
{
if ($filePath !== null) {
$lower = strtolower($filePath);
if (str_ends_with($lower, '.blade.php')) {
return $this->bladeParser->parse($content);
}
if (str_ends_with($lower, '.twig')) {
return $this->twigParser->parse($content);
}
if (str_ends_with($lower, '.php')) {
return $this->preprocessPhp($content);
}
}
// Detect Blade or Twig by content heuristic if no path is provided
if (str_contains($content, '{{') || str_contains($content, '@if') || str_contains($content, '@foreach')) {
return $this->bladeParser->parse($content);
}
if (str_contains($content, '{%') || str_contains($content, '{#')) {
return $this->twigParser->parse($content);
}
if (str_contains($content, '<' . '?php') || str_contains($content, '<' . '?=')) {
return $this->preprocessPhp($content);
}
return $this->htmlParser->parse($content);
}
private function preprocessPhp(string $content): string
{
// Replace short echo tags with placeholder text preserving newlines
$content = preg_replace_callback('/<\?=(.*?)\?>/s', function ($m) {
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
return 'StaticPhpEcho' . $newlines;
}, $content) ?? $content;
// Replace PHP execution blocks with placeholder preserving newlines
$content = preg_replace_callback('/<\?php(.*?)\?>/s', function ($m) {
return str_repeat("\n", substr_count($m[0], "\n"));
}, $content) ?? $content;
return $content;
}
}
+16 -9
View File
@@ -6,15 +6,22 @@ class TwigParser implements ParserInterface
{
public function parse(string $content): string
{
// Strip Twig comments {# ... #}
$content = preg_replace('/\{\#.*?\#\}/s', '', $content) ?? $content;
// Replace Twig output {{ ... }} with static text
$content = preg_replace('/\{\{\s*(.*?)\s*\}\}/s', 'StaticTwigOutput', $content) ?? $content;
// Strip Twig statements {% ... %}
$content = preg_replace('/\{\%.*?\%\}/s', '', $content) ?? $content;
// 1. Strip Twig comments {# ... #} while preserving line count
$content = preg_replace_callback('/\{\#.*?\#\}/s', function ($m) {
return str_repeat("\n", substr_count($m[0], "\n"));
}, $content) ?? $content;
// 2. Replace Twig output {{ ... }} while preserving line count
$content = preg_replace_callback('/\{\{\s*(.*?)\s*\}\}/s', function ($m) {
$newlines = str_repeat("\n", substr_count($m[0], "\n"));
return 'StaticTwigOutput' . $newlines;
}, $content) ?? $content;
// 3. Strip Twig statements {% ... %} while preserving line count
$content = preg_replace_callback('/\{\%.*?\%\}/s', function ($m) {
return str_repeat("\n", substr_count($m[0], "\n"));
}, $content) ?? $content;
return $content;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace YakNet\AccessibilityConsole\Presets;
class ECommercePreset implements PresetInterface
{
public function getName(): string
{
return 'ecommerce';
}
public function getDescription(): string
{
return 'E-Commerce storefront and checkout flow accessibility profile.';
}
public function getLevel(): int
{
return 4;
}
public function getIncludedRules(): array
{
return [
'WCAG_1_1_1_IMG_ALT',
'WCAG_4_1_2_BUTTON',
'WCAG_1_3_1_FORM_LABEL',
'WCAG_3_3_7_REDUNDANT_ENTRY',
'WCAG_2_5_8_TARGET_SIZE',
'WCAG_1_4_3_CONTRAST',
'WCAG_4_1_2_DIALOG',
];
}
public function getExcludedRules(): array
{
return [];
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace YakNet\AccessibilityConsole\Presets;
class En301549Preset implements PresetInterface
{
public function getName(): string
{
return 'en301549';
}
public function getDescription(): string
{
return 'European Union EN 301 549 public sector digital accessibility profile.';
}
public function getLevel(): int
{
return 4;
}
public function getIncludedRules(): array
{
return [
'WCAG_1_4_3_CONTRAST',
'WCAG_2_4_7_FOCUS_OUTLINE',
'WCAG_2_5_8_TARGET_SIZE',
'WCAG_1_4_12_TEXT_SPACING',
'WCAG_2_5_3_LABEL_IN_NAME',
];
}
public function getExcludedRules(): array
{
return [];
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace YakNet\AccessibilityConsole\Presets;
interface PresetInterface
{
public function getName(): string;
public function getDescription(): string;
public function getLevel(): int;
/**
* @return string[]
*/
public function getIncludedRules(): array;
/**
* @return string[]
*/
public function getExcludedRules(): array;
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace YakNet\AccessibilityConsole\Presets;
class PresetRegistry
{
/**
* @var array<string, PresetInterface>
*/
private array $presets = [];
public function __construct()
{
$this->register(new Section508Preset());
$this->register(new En301549Preset());
$this->register(new ECommercePreset());
}
public function register(PresetInterface $preset): void
{
$this->presets[strtolower($preset->getName())] = $preset;
}
public function get(string $name): ?PresetInterface
{
return $this->presets[strtolower($name)] ?? null;
}
/**
* @return array<string, PresetInterface>
*/
public function all(): array
{
return $this->presets;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace YakNet\AccessibilityConsole\Presets;
class Section508Preset implements PresetInterface
{
public function getName(): string
{
return 'section508';
}
public function getDescription(): string
{
return 'US Federal Government Section 508 accessibility compliance profile.';
}
public function getLevel(): int
{
return 3;
}
public function getIncludedRules(): array
{
return [
'WCAG_1_1_1_IMG_ALT',
'WCAG_1_3_1_TABLE',
'WCAG_1_3_1_TABLE_HEADERS_ATTR',
'WCAG_1_3_1_FORM_LABEL',
'WCAG_2_1_1_KEYBOARD_CLICK',
'WCAG_2_4_2_PAGE_TITLE',
'WCAG_3_1_1_LANG',
];
}
public function getExcludedRules(): array
{
return [];
}
}
+169
View File
@@ -112,6 +112,175 @@ class WcagDatabase
badExample: '<input name="search" autofocus>',
goodExample: '<input name="search">'
));
self::add(new WcagCriterion(
id: 'WCAG_2_5_8_TARGET_SIZE',
title: '2.5.8 Target Size (Minimum)',
level: 'AA',
url: 'https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html',
description: 'The size of the target for pointer inputs is at least 24 by 24 CSS pixels.',
badExample: '<button style="width: 16px; height: 16px;">X</button>',
goodExample: '<button style="width: 24px; height: 24px;">X</button>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_3_1_DETAILS_SUMMARY',
title: '1.3.1 Info and Relationships',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships.html',
description: '<details> elements must have a <summary> element to serve as an accessible disclosure trigger.',
badExample: '<details><p>Details content</p></details>',
goodExample: '<details><summary>More info</summary><p>Details content</p></details>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_CURRENT',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: 'The aria-current attribute must have a valid value indicating the current item in a set.',
badExample: '<a href="/home" aria-current="active">Home</a>',
goodExample: '<a href="/home" aria-current="page">Home</a>'
));
self::add(new WcagCriterion(
id: 'WCAG_3_3_1_ARIA_ERRORMESSAGE',
title: '3.3.1 Error Identification',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/error-identification.html',
description: 'aria-errormessage must reference a valid error element and control must have aria-invalid="true".',
badExample: '<input name="email" aria-errormessage="email_error">',
goodExample: '<input name="email" aria-invalid="true" aria-errormessage="email_err"><span id="email_err">Invalid email</span>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_ROLEDESCRIPTION',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: 'aria-roledescription must only be used on elements with a non-generic role.',
badExample: '<div aria-roledescription="slide">Slide 1</div>',
goodExample: '<div role="region" aria-roledescription="slide" aria-label="Slide 1">Slide 1</div>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_PROHIBITED_ATTR',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: 'Prohibited ARIA attributes must not be used on presentation or generic roles.',
badExample: '<div role="presentation" aria-label="decorative"></div>',
goodExample: '<div role="presentation"></div>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_3_2_HTML_DIR',
title: '1.3.2 Meaningful Sequence',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/meaningful-sequence.html',
description: 'The dir attribute must only use valid values: ltr, rtl, or auto.',
badExample: '<p dir="left">Text</p>',
goodExample: '<p dir="ltr">Text</p>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_3_1_SELECT_CHILDREN',
title: '1.3.1 Info and Relationships',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships.html',
description: '<select> elements must only contain valid child elements (<option>, <optgroup>).',
badExample: '<select><div>Option 1</div></select>',
goodExample: '<select><option>Option 1</option></select>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_1_1_ROLE_IMG',
title: '1.1.1 Non-text Content',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html',
description: 'Elements with role="img" must have an accessible name.',
badExample: '<span role="img" class="icon-star"></span>',
goodExample: '<span role="img" class="icon-star" aria-label="5 stars rating"></span>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_4_2_MEDIA_CONTROLS',
title: '1.4.2 Audio Control',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/audio-control.html',
description: 'Audio and video media elements should provide user controls for playback and volume.',
badExample: '<audio src="podcast.mp3"></audio>',
goodExample: '<audio src="podcast.mp3" controls></audio>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_2_2_TRACK_VALIDATION',
title: '1.2.2 Captions (Prerecorded)',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/captions-prerecorded.html',
description: '<track> elements must have valid kind, srclang, and label attributes.',
badExample: '<track src="sub.vtt" kind="captions">',
goodExample: '<track src="sub.vtt" kind="captions" srclang="en" label="English">'
));
self::add(new WcagCriterion(
id: 'WCAG_2_1_1_ACCESSKEY_DUPLICATE',
title: '2.1.1 Keyboard',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/keyboard.html',
description: 'accesskey attribute values must be unique across the document.',
badExample: '<a href="/" accesskey="h">Home</a><a href="/help" accesskey="h">Help</a>',
goodExample: '<a href="/" accesskey="h">Home</a><a href="/help" accesskey="p">Help</a>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_BUTTON_NESTED_INTERACTIVE',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: '<button> elements must not contain nested interactive elements.',
badExample: '<button><a href="/cart">Checkout</a></button>',
goodExample: '<a href="/cart" class="btn">Checkout</a>'
));
self::add(new WcagCriterion(
id: 'WCAG_2_4_11_FOCUS_NOT_OBSCURED',
title: '2.4.11 Focus Not Obscured (Minimum)',
level: 'AA',
url: 'https://www.w3.org/WAI/WCAG22/Understanding/focus-not-obscured-minimum.html',
description: 'Fixed or sticky headers and overlays must not completely obscure keyboard-focused elements.',
badExample: '<header style="position: fixed; top: 0; width: 100%; height: 80px;"></header>',
goodExample: '<html style="scroll-padding-top: 80px;"><header style="position: fixed; top: 0; width: 100%; height: 80px;"></header></html>'
));
self::add(new WcagCriterion(
id: 'WCAG_2_5_7_DRAGGING_MOVEMENTS',
title: '2.5.7 Dragging Movements',
level: 'AA',
url: 'https://www.w3.org/WAI/WCAG22/Understanding/dragging-movements.html',
description: 'Elements supporting drag-and-drop operations must provide a single-pointer alternative.',
badExample: '<div draggable="true" class="list-item">Item 1</div>',
goodExample: '<div draggable="true" class="list-item">Item 1 <button>Move Up</button> <button>Move Down</button></div>'
));
self::add(new WcagCriterion(
id: 'WCAG_4_1_2_ARIA_LABEL_GENERIC',
title: '4.1.2 Name, Role, Value',
level: 'A',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
description: 'Generic <div> or <span> elements should not use aria-label without an explicit ARIA role.',
badExample: '<div aria-label="Important Notice">Text</div>',
goodExample: '<div role="region" aria-label="Important Notice">Text</div>'
));
self::add(new WcagCriterion(
id: 'WCAG_1_3_5_AUTOCOMPLETE_APPROPRIATE',
title: '1.3.5 Identify Input Purpose',
level: 'AA',
url: 'https://www.w3.org/WAI/WCAG21/Understanding/identify-input-purpose.html',
description: 'Input autocomplete value must be semantically appropriate for the input type.',
badExample: '<input type="number" autocomplete="email">',
goodExample: '<input type="email" autocomplete="email">'
));
}
public static function add(WcagCriterion $criterion): void
+4
View File
@@ -18,6 +18,10 @@ class ExcelReportExporter
*/
public static function exportExcel(array $scanResult, string $targetUrl): string
{
if (!class_exists(Spreadsheet::class)) {
throw new \RuntimeException('To export Excel audit reports, please install phpspreadsheet via: composer require phpoffice/phpspreadsheet');
}
/** @var int $score */
$score = is_numeric($scanResult['score'] ?? null) ? intval($scanResult['score']) : 0;
+10 -2
View File
@@ -92,6 +92,7 @@ class HtmlDashboardReporter
$explanation = '';
$fixedCode = '';
$explanation = '';
if ($aiSuggestion && str_contains($aiSuggestion, 'FIX:')) {
preg_match('/EXPLANATION:(.*)FIX:(.*)/s', $aiSuggestion, $matches);
$explanation = trim($matches[1] ?? '');
@@ -103,8 +104,15 @@ class HtmlDashboardReporter
$escapedSnippet = htmlspecialchars($v->htmlSnippet, ENT_QUOTES, 'UTF-8');
$escapedFixed = $fixedCode ? htmlspecialchars($fixedCode, ENT_QUOTES, 'UTF-8') : '';
$escapedExplanation = $explanation ? htmlspecialchars($explanation, ENT_QUOTES, 'UTF-8') : '';
$locationStr = $v->location ? htmlspecialchars($v->location['file'] . ':' . (string)$v->location['line'], ENT_QUOTES, 'UTF-8') : 'N/A';
$escapedExplanation = $explanation !== '' ? htmlspecialchars($explanation, ENT_QUOTES, 'UTF-8') : '';
$locationStr = 'N/A';
if ($v->location !== null) {
$filePart = $v->location['file'] ?? '';
$lineNum = (string)$v->location['line'];
$locText = $filePart !== '' ? $filePart . ':' . $lineNum : 'Line ' . $lineNum;
$locationStr = htmlspecialchars($locText, ENT_QUOTES, 'UTF-8');
}
$escapedRuleId = htmlspecialchars($v->ruleId, ENT_QUOTES, 'UTF-8');
$escapedMessage = htmlspecialchars($v->message, ENT_QUOTES, 'UTF-8');
+122
View File
@@ -0,0 +1,122 @@
<?php
namespace YakNet\AccessibilityConsole\Reporting;
use SimpleXMLElement;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\Violation;
class JunitFormatter implements FormatterInterface
{
/**
* @param Violation[] $violations
* @param int $baselinedCount
* @param SymfonyStyle $io
* @return int
*/
public function format(array $violations, int $baselinedCount, SymfonyStyle $io): int
{
$xml = $this->render($violations, $baselinedCount);
$io->write($xml);
return empty($violations) ? Command::SUCCESS : Command::FAILURE;
}
/**
* Render the violations in JUnit XML format.
*
* @param Violation[] $violations
* @param int $baselinedCount
* @return string
*/
public function render(array $violations, int $baselinedCount = 0): string
{
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$testsuites = $dom->createElement('testsuites');
$testsuites->setAttribute('name', 'YakNet Accessibility Console');
$testsuites->setAttribute('tests', (string)max(1, count($violations)));
$testsuites->setAttribute('failures', (string)count($violations));
$testsuites->setAttribute('errors', '0');
$testsuites->setAttribute('time', '0.000');
$dom->appendChild($testsuites);
if (empty($violations)) {
$testsuite = $dom->createElement('testsuite');
$testsuite->setAttribute('name', 'AccessibilityScan');
$testsuite->setAttribute('tests', '1');
$testsuite->setAttribute('failures', '0');
$testsuite->setAttribute('errors', '0');
$testsuite->setAttribute('time', '0.000');
$testcase = $dom->createElement('testcase');
$testcase->setAttribute('name', 'AccessibilityCompliant');
$testcase->setAttribute('classname', 'YakNet.AccessibilityConsole');
$testcase->setAttribute('time', '0.000');
$testsuite->appendChild($testcase);
$testsuites->appendChild($testsuite);
return (string)$dom->saveXML();
}
// Group violations by file
/** @var array<string, Violation[]> $grouped */
$grouped = [];
foreach ($violations as $v) {
$file = $v->location['file'] ?? 'unknown';
$grouped[$file][] = $v;
}
foreach ($grouped as $file => $fileViolations) {
$testsuite = $dom->createElement('testsuite');
$testsuite->setAttribute('name', str_replace('\\', '/', $file));
$testsuite->setAttribute('tests', (string)count($fileViolations));
$testsuite->setAttribute('failures', (string)count($fileViolations));
$testsuite->setAttribute('errors', '0');
$testsuite->setAttribute('time', '0.000');
foreach ($fileViolations as $v) {
$line = $v->location['line'] ?? 1;
$col = $v->location['column'] ?? 1;
$testcase = $dom->createElement('testcase');
$testcase->setAttribute('name', sprintf('[%s] %s', $v->ruleId, $v->message));
$testcase->setAttribute('classname', str_replace(['/', '\\'], '.', $file));
$testcase->setAttribute('time', '0.000');
$failure = $dom->createElement('failure');
$failure->setAttribute('type', $v->severity->value);
$failure->setAttribute('message', $v->message);
$details = sprintf(
"Rule: %s (%s)\nStandard: %s\nSeverity: %s\nLocation: %s:%d:%d\n\nSnippet:\n%s",
$v->ruleId,
$v->message,
$v->standard->value,
$v->severity->value,
$file,
$line,
$col,
$v->htmlSnippet
);
if ($v->fixSuggestion !== null && $v->fixSuggestion !== '') {
$details .= "\n\nSuggested Fix:\n" . $v->fixSuggestion;
}
$cdata = $dom->createCDATASection($details);
$failure->appendChild($cdata);
$testcase->appendChild($failure);
$testsuite->appendChild($testcase);
}
$testsuites->appendChild($testsuite);
}
return (string)$dom->saveXML();
}
}
+13 -6
View File
@@ -16,6 +16,12 @@ class PdfReportGenerator
*/
public static function generatePdf(array $scanResult, string $targetUrl): string
{
if (!class_exists(Dompdf::class)) {
throw new \RuntimeException('To generate PDF certificates, please install dompdf via: composer require dompdf/dompdf');
}
date_default_timezone_set('Europe/Istanbul');
/** @var int $score */
$score = is_numeric($scanResult['score'] ?? null) ? intval($scanResult['score']) : 0;
@@ -54,14 +60,15 @@ class PdfReportGenerator
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<title>WCAG 2.1 Erişilebilirlik Sertifikası ve Raporu</title>
<style>
body { font-family: sans-serif; color: #1e293b; line-height: 1.5; font-size: 12px; margin: 0; padding: 20px; }
* { 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: 20px; font-weight: bold; color: #0f172a; }
.subtitle { font-size: 13px; color: #64748b; margin-top: 4px; }
.badge { display: inline-block; padding: 6px 16px; border-radius: 12px; color: #fff; font-weight: bold; font-size: 14px; background: {$scoreColor}; }
.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; }
@@ -83,7 +90,7 @@ class PdfReportGenerator
<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.1</div>
<div><b>Raporu Üreten Motor:</b> YakNet AI & Accessibility Engine v3.3</div>
</div>
<h3 style='color:#0f172a; border-bottom:1px solid #cbd5e1; padding-bottom:6px;'>📋 Erişilebilirlik İhlalleri ve Çözüm Detayları</h3>
+155
View File
@@ -0,0 +1,155 @@
<?php
namespace YakNet\AccessibilityConsole\Reporting;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
class SarifFormatter implements FormatterInterface
{
/**
* @param Violation[] $violations
* @param int $baselinedCount
* @param SymfonyStyle $io
* @return int
*/
public function format(array $violations, int $baselinedCount, SymfonyStyle $io): int
{
$sarifJson = $this->render($violations, $baselinedCount);
$io->write($sarifJson);
return empty($violations) ? Command::SUCCESS : Command::FAILURE;
}
/**
* Render the violations in SARIF 2.1.0 JSON format.
*
* @param Violation[] $violations
* @param int $baselinedCount
* @return string
*/
public function render(array $violations, int $baselinedCount = 0): string
{
$rulesMap = [];
$results = [];
foreach ($violations as $v) {
$ruleId = $v->ruleId;
// Register rule metadata if not already present
if (!isset($rulesMap[$ruleId])) {
$rulesMap[$ruleId] = [
'id' => $ruleId,
'name' => $this->sanitizeRuleName($ruleId),
'shortDescription' => [
'text' => $v->message,
],
'fullDescription' => [
'text' => $v->message,
],
'defaultConfiguration' => [
'level' => $this->mapSeverityToSarifLevel($v->severity),
],
'properties' => [
'tags' => [
'accessibility',
'a11y',
'wcag',
'wcag-' . strtolower($v->standard->value),
],
],
];
}
// Location details
$file = $v->location['file'] ?? 'unknown';
$line = isset($v->location['line']) ? max(1, (int)$v->location['line']) : 1;
$column = isset($v->location['column']) ? max(1, (int)$v->location['column']) : 1;
/** @var array<string, mixed> $region */
$region = [
'startLine' => $line,
'startColumn' => $column,
];
if ($v->htmlSnippet !== '') {
$region['snippet'] = [
'text' => $v->htmlSnippet,
];
}
/** @var array<string, mixed> $locationEntry */
$locationEntry = [
'physicalLocation' => [
'artifactLocation' => [
'uri' => str_replace('\\', '/', $file),
],
'region' => $region,
],
];
/** @var array<string, mixed> $resultItem */
$resultItem = [
'ruleId' => $ruleId,
'level' => $this->mapSeverityToSarifLevel($v->severity),
'message' => [
'text' => $v->message,
],
'locations' => [
$locationEntry,
],
];
if ($v->fixSuggestion !== null && $v->fixSuggestion !== '') {
$resultItem['fixes'] = [
[
'description' => [
'text' => 'Suggested accessibility fix',
],
],
];
}
$results[] = $resultItem;
}
$sarif = [
'$schema' => 'https://json.schemastore.org/sarif-2.1.0.json',
'version' => '2.1.0',
'runs' => [
[
'tool' => [
'driver' => [
'name' => 'YakNet Accessibility Console',
'informationUri' => 'https://forum.yak.net.tr',
'semanticVersion' => '3.3.0',
'rules' => array_values($rulesMap),
],
],
'results' => $results,
],
],
];
return (string)json_encode($sarif, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
private function mapSeverityToSarifLevel(Severity $severity): string
{
return match ($severity) {
Severity::CRITICAL, Severity::ERROR => 'error',
Severity::WARNING => 'warning',
Severity::INFO => 'note',
};
}
private function sanitizeRuleName(string $ruleId): string
{
$cleaned = preg_replace('/^WCAG_\d+_\d+_\d+_?/', '', $ruleId);
$cleaned = is_string($cleaned) ? $cleaned : $ruleId;
$words = explode('_', strtolower($cleaned));
return implode('', array_map('ucfirst', $words));
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\AbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AccesskeyDuplicate extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_1_1_ACCESSKEY_DUPLICATE';
}
public function getDescription(): string
{
return 'accesskey attribute values must be unique across the document.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 2;
}
public function check(\DOMDocument $doc): array
{
$violations = [];
$xpath = new \DOMXPath($doc);
$elements = $xpath->query('//*[@accesskey]');
if ($elements === false || $elements->length === 0) {
return [];
}
$keys = [];
foreach ($elements as $el) {
if (!$el instanceof DOMElement) {
continue;
}
$val = trim($el->getAttribute('accesskey'));
if ($val === '') {
continue;
}
if (!isset($keys[$val])) {
$keys[$val] = [];
}
$keys[$val][] = $el;
}
foreach ($keys as $key => $elementsWithKey) {
if (count($elementsWithKey) > 1) {
foreach ($elementsWithKey as $el) {
$violations[] = $this->createViolation(
"Duplicate accesskey=\"{$key}\" found. Access keys must be unique across the document.",
$el,
"Assign a unique accesskey to each interactive element, or avoid using accesskey entirely."
);
}
}
}
return $violations;
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaBrailleEquivalent extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_BRAILLE';
}
public function getDescription(): string
{
return 'Elements with aria-braillelabel or aria-brailleroledescription must provide a standard accessible equivalent.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if ($element->hasAttribute('aria-braillelabel')) {
$hasName = false;
if ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '') {
$hasName = true;
} elseif ($element->hasAttribute('aria-labelledby') && trim($element->getAttribute('aria-labelledby')) !== '') {
$hasName = true;
} elseif ($element->hasAttribute('title') && trim($element->getAttribute('title')) !== '') {
$hasName = true;
} elseif ($element->hasAttribute('alt') && trim($element->getAttribute('alt')) !== '') {
$hasName = true;
} elseif (trim($element->textContent) !== '') {
$hasName = true;
}
if (!$hasName) {
return $this->createViolation(
$element,
"Element has aria-braillelabel but is missing a standard accessible name (aria-label, aria-labelledby, or text content).",
"Add a standard aria-label or aria-labelledby in addition to the aria-braillelabel."
);
}
}
if ($element->hasAttribute('aria-brailleroledescription')) {
if (!$element->hasAttribute('aria-roledescription') || trim($element->getAttribute('aria-roledescription')) === '') {
return $this->createViolation(
$element,
"Element has aria-brailleroledescription but is missing the standard aria-roledescription attribute.",
"Add an aria-roledescription attribute to accompany aria-brailleroledescription."
);
}
}
return null;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaCurrentValid extends AbstractRule
{
/** @var array<int, string> */
private static array $validValues = [
'page', 'step', 'location', 'date', 'time', 'true', 'false'
];
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_CURRENT';
}
public function getDescription(): string
{
return 'The aria-current attribute must have a valid token value.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 3;
}
public function check(DOMElement $element): ?Violation
{
if (!$element->hasAttribute('aria-current')) {
return null;
}
$value = strtolower(trim($element->getAttribute('aria-current')));
if (!in_array($value, self::$validValues, true)) {
$validList = implode(', ', self::$validValues);
return $this->createViolation(
$element,
"Invalid aria-current value \"{$value}\". Valid values are: {$validList}.",
"Set aria-current to one of the valid token values: page, step, location, date, time, true, or false."
);
}
return null;
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaDisabledFocusable extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_DISABLED';
}
public function getDescription(): string
{
return 'Disabled elements should not have conflicting focusable tabindex settings.';
}
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
{
// 1. Native disabled element with explicit positive/zero tabindex
if ($element->hasAttribute('disabled')) {
if ($element->hasAttribute('tabindex')) {
$tabindex = (int)$element->getAttribute('tabindex');
if ($tabindex >= 0) {
return $this->createViolation(
$element,
"Element has both the 'disabled' attribute and a focusable tabindex=\"{$tabindex}\".",
"Remove the tabindex or set tabindex=\"-1\" to avoid keyboard navigation confusion on disabled elements."
);
}
}
}
// 2. Elements with aria-disabled="true" on non-native elements
if (strtolower(trim($element->getAttribute('aria-disabled'))) === 'true') {
$tagName = strtolower($element->tagName);
if (in_array($tagName, ['a', 'button'], true) && $element->hasAttribute('tabindex')) {
$tabindex = (int)$element->getAttribute('tabindex');
if ($tabindex > 0) {
return $this->createViolation(
$element,
"Element has aria-disabled=\"true\" with positive tabindex=\"{$tabindex}\".",
"Avoid positive tabindex on disabled interactive elements."
);
}
}
}
return null;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaErrorMessage extends AbstractRule
{
public function getId(): string
{
return 'WCAG_3_3_1_ARIA_ERRORMESSAGE';
}
public function getDescription(): string
{
return 'aria-errormessage must reference an existing element ID and the element must have aria-invalid set.';
}
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-errormessage')) {
return null;
}
$targetId = trim($element->getAttribute('aria-errormessage'));
if ($targetId === '') {
return $this->createViolation(
$element,
"Attribute aria-errormessage is empty.",
"Provide the ID of an element containing the error message text."
);
}
// 1. Verify that target element exists in document
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new \DOMXPath($doc);
$targets = $xpath->query('//*[@id="' . $targetId . '"]');
if ($targets === false || $targets->length === 0) {
return $this->createViolation(
$element,
"Attribute aria-errormessage=\"{$targetId}\" references an ID that does not exist in the document.",
"Ensure the referenced error message element ID exists in the HTML document."
);
}
}
// 2. Check if element has aria-invalid set to a truthy value (true, grammar, spelling)
$ariaInvalid = strtolower(trim($element->getAttribute('aria-invalid')));
if ($ariaInvalid === '' || $ariaInvalid === 'false') {
return $this->createViolation(
$element,
"Element uses aria-errormessage=\"{$targetId}\" but does not have aria-invalid set to \"true\".",
"Add aria-invalid=\"true\" to the control when an error message is active."
);
}
return null;
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaLabelMisuseOnGeneric extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_LABEL_GENERIC';
}
public function getDescription(): string
{
return 'aria-label or aria-labelledby should not be used on generic <div> or <span> elements without an ARIA role.';
}
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 !== 'div' && $tag !== 'span') {
return null;
}
$hasRole = $element->hasAttribute('role') && trim($element->getAttribute('role')) !== '';
if ($hasRole) {
return null;
}
$hasAriaLabel = $element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '';
$hasAriaLabelledby = $element->hasAttribute('aria-labelledby') && trim($element->getAttribute('aria-labelledby')) !== '';
if ($hasAriaLabel || $hasAriaLabelledby) {
return $this->createViolation(
$element,
"Generic <{$tag}> uses aria-label/aria-labelledby without a semantic ARIA role (assistive technologies ignore names on generic elements).",
"Add an appropriate ARIA role (e.g. role=\"region\", role=\"group\", role=\"navigation\") or use a semantic HTML5 element."
);
}
return null;
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaProhibitedAttr extends AbstractRule
{
/** @var array<string, array<int, string>> */
private static array $prohibitedAttributesByRole = [
'presentation' => ['aria-label', 'aria-labelledby', 'aria-describedby', 'aria-details'],
'none' => ['aria-label', 'aria-labelledby', 'aria-describedby', 'aria-details'],
'generic' => ['aria-label', 'aria-labelledby', 'aria-roledescription'],
'caption' => ['aria-label', 'aria-labelledby']
];
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_PROHIBITED_ATTR';
}
public function getDescription(): string
{
return 'Prohibited ARIA attributes must not be used on roles that do not support naming (e.g. presentation, none).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 4;
}
public function check(DOMElement $element): ?Violation
{
if (!$element->hasAttribute('role')) {
return null;
}
$roles = explode(' ', strtolower(trim($element->getAttribute('role'))));
foreach ($roles as $role) {
if (isset(self::$prohibitedAttributesByRole[$role])) {
$prohibited = self::$prohibitedAttributesByRole[$role];
$foundProhibited = [];
foreach ($prohibited as $attr) {
if ($element->hasAttribute($attr)) {
$foundProhibited[] = $attr;
}
}
if (!empty($foundProhibited)) {
$attrList = implode(', ', $foundProhibited);
return $this->createViolation(
$element,
"Element with role=\"{$role}\" contains prohibited ARIA attribute(s): {$attrList}.",
"Remove the prohibited attribute(s) or change the element's ARIA role to one that supports naming."
);
}
}
}
return null;
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaRedundantRole extends AbstractRule
{
/** @var array<string, string> */
private static array $redundantMap = [
'nav' => 'navigation',
'main' => 'main',
'button' => 'button',
'article' => 'article',
'aside' => 'complementary',
'dialog' => 'dialog',
'figure' => 'figure',
];
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_REDUNDANT_ROLE';
}
public function getDescription(): string
{
return 'Avoid specifying redundant ARIA roles on HTML elements with identical implicit semantics.';
}
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 (!$element->hasAttribute('role')) {
return null;
}
$tagName = strtolower($element->tagName);
$role = strtolower(trim($element->getAttribute('role')));
if (isset(self::$redundantMap[$tagName]) && self::$redundantMap[$tagName] === $role) {
return $this->createViolation(
$element,
"Redundant ARIA role=\"{$role}\" on <{$tagName}>. The element natively possesses this implicit semantic role.",
"Remove the redundant role=\"{$role}\" attribute (First Rule of ARIA)."
);
}
return null;
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AriaRoledescription extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_ARIA_ROLEDESCRIPTION';
}
public function getDescription(): string
{
return 'aria-roledescription must only be used on elements with a non-generic role and must not be empty.';
}
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-roledescription')) {
return null;
}
$desc = trim($element->getAttribute('aria-roledescription'));
if ($desc === '') {
return $this->createViolation(
$element,
"Attribute aria-roledescription is empty or contains only whitespace.",
"Provide a meaningful description or remove the aria-roledescription attribute."
);
}
$role = strtolower(trim($element->getAttribute('role')));
if ($role === 'presentation' || $role === 'none' || $role === 'generic') {
return $this->createViolation(
$element,
"aria-roledescription must not be used on elements with role=\"{$role}\".",
"Remove aria-roledescription from presentation/generic elements, or provide an appropriate semantic ARIA role."
);
}
$tagName = strtolower($element->tagName);
if ($role === '' && in_array($tagName, ['div', 'span'], true)) {
return $this->createViolation(
$element,
"aria-roledescription is used on a generic <{$tagName}> element without an explicit ARIA role.",
"Add an explicit ARIA role (e.g. role=\"region\", role=\"button\") or use a semantic HTML element."
);
}
return null;
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class ButtonNestedInteractive extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_BUTTON_NESTED_INTERACTIVE';
}
public function getDescription(): string
{
return '<button> elements must not contain nested interactive controls.';
}
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) !== 'button') {
return null;
}
$doc = $element->ownerDocument;
if ($doc === null) {
return null;
}
$xpath = new DOMXPath($doc);
$nestedInteractives = $xpath->query('.//a[@href] | .//button | .//select | .//textarea | .//input[not(@type="hidden")]', $element);
if ($nestedInteractives !== false && $nestedInteractives->length > 0) {
$first = $nestedInteractives->item(0);
$nestedTag = $first instanceof DOMElement ? strtolower($first->tagName) : 'interactive element';
return $this->createViolation(
$element,
"<button> contains a nested interactive <{$nestedTag}> element.",
"Remove nested interactive elements from inside the <button> or restructure as sibling elements."
);
}
return null;
}
}
+9 -1
View File
@@ -23,7 +23,7 @@ class ColorContrast extends AbstractRule
// 1. Parse inline styles (highest priority)
$inlineStyle = $element->hasAttribute('style') ? $element->getAttribute('style') : '';
$color = $this->parseColorValue($inlineStyle, 'color');
$bg = $this->parseColorValue($inlineStyle, 'background-color') ?: $this->parseColorValue($inlineStyle, 'background');
$bg = $this->parseColorValue($inlineStyle, 'background-color') ?: $this->parseBackgroundValue($inlineStyle);
// 2. Fallback: Parse stylesheet styles
if (($color === null || $bg === null) && $element->ownerDocument !== null) {
@@ -327,6 +327,14 @@ class ColorContrast extends AbstractRule
return null;
}
private function parseBackgroundValue(string $style): ?string
{
if (preg_match('/(?:^|;)\s*background\s*:\s*([^;]+)/i', $style, $matches)) {
return $this->extractColorFromBackground(trim($matches[1]));
}
return null;
}
/**
* @return array{0: int, 1: int, 2: int}|null
*/
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use DOMNode;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class DetailsMissingSummary extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_DETAILS_SUMMARY';
}
public function getDescription(): string
{
return '<details> elements must contain a <summary> element to provide an accessible disclosure label.';
}
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) !== 'details') {
return null;
}
$hasSummary = false;
$summaryEmpty = false;
foreach ($element->childNodes as $child) {
if ($child instanceof DOMElement && strtolower($child->tagName) === 'summary') {
$hasSummary = true;
$text = trim($child->textContent);
$ariaLabel = trim($child->getAttribute('aria-label'));
if ($text === '' && $ariaLabel === '') {
$summaryEmpty = true;
}
break;
}
}
if (!$hasSummary) {
return $this->createViolation(
$element,
"<details> element is missing a <summary> element as its label.",
"Add a <summary> element with descriptive text as the first child of the <details> tag."
);
}
if ($summaryEmpty) {
return $this->createViolation(
$element,
"<summary> element inside <details> is empty.",
"Provide meaningful text inside the <summary> element to describe the expandable content."
);
}
return null;
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class DraggingMovements extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_5_7_DRAGGING_MOVEMENTS';
}
public function getDescription(): string
{
return 'Elements supporting drag-and-drop operations must provide a single-pointer alternative (WCAG 2.2 SC 2.5.7).';
}
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
{
$isDraggable = strtolower(trim($element->getAttribute('draggable'))) === 'true';
$hasDragEvent = $element->hasAttribute('ondragstart') || $element->hasAttribute('ondrop');
if (!$isDraggable && !$hasDragEvent) {
return null;
}
// Check if element or child has alternative buttons/actions or aria-grabbed/keyshortcuts
$hasKeyboardShortcut = $element->hasAttribute('aria-keyshortcuts');
$hasGrabbed = $element->hasAttribute('aria-grabbed');
$hasRole = $element->hasAttribute('role');
$doc = $element->ownerDocument;
$hasButtonsInside = false;
if ($doc !== null) {
$buttons = $element->getElementsByTagName('button');
if ($buttons->length > 0) {
$hasButtonsInside = true;
}
}
if (!$hasKeyboardShortcut && !$hasGrabbed && !$hasButtonsInside) {
return $this->createViolation(
$element,
"Draggable element lacks a single-pointer or keyboard-accessible alternative (WCAG 2.2 SC 2.5.7).",
"Provide alternative click buttons (e.g. Move Up / Move Down) or keyboard commands for users unable to perform dragging movements."
);
}
return null;
}
}
+26 -4
View File
@@ -8,6 +8,16 @@ use YakNet\AccessibilityConsole\Core\WCAGStandard;
class DuplicateId extends AbstractRule
{
public function getId(): string
{
return 'WCAG_4_1_2_DUPLICATE_ID';
}
public function getDescription(): string
{
return 'Element IDs must be unique across the document.';
}
public function check(\DOMDocument $doc): array
{
$violations = [];
@@ -37,7 +47,8 @@ class DuplicateId extends AbstractRule
foreach ($elementsWithId as $el) {
$violations[] = $this->createViolation(
"Duplicate ID \"{$id}\" found. Element ID attribute must be unique across the document.",
$el
$el,
"Change duplicate id=\"{$id}\" to a unique identifier."
);
}
}
@@ -46,7 +57,18 @@ class DuplicateId extends AbstractRule
return $violations;
}
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 3; }
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 3;
}
}
+95 -12
View File
@@ -3,17 +3,37 @@
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use DOMNode;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class EmptyHeading extends AbstractRule
{
public function getId(): string { return 'WCAG_1_3_1_EMPTY_HEADING'; }
public function getDescription(): string { return 'Heading elements (h1-h6) must have discernible text content.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 2; }
public function getId(): string
{
return 'WCAG_1_3_1_EMPTY_HEADING';
}
public function getDescription(): string
{
return 'Heading elements (h1-h6) must have discernible text content.';
}
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
{
@@ -26,15 +46,78 @@ class EmptyHeading extends AbstractRule
return null;
}
// 1. Check direct text content
$text = trim($element->textContent);
if ($text === '' && !$element->hasAttribute('aria-label') && !$element->hasAttribute('title')) {
return $this->createViolation(
$element,
$this->getDescription(),
'Add descriptive text or an aria-label to the heading element.'
);
if ($text !== '') {
return null;
}
return null;
// 2. Check aria-label
if ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '') {
return null;
}
// 3. Check title attribute
if ($element->hasAttribute('title') && trim($element->getAttribute('title')) !== '') {
return null;
}
// 4. Check aria-labelledby
if ($element->hasAttribute('aria-labelledby')) {
$id = trim($element->getAttribute('aria-labelledby'));
$doc = $element->ownerDocument;
if ($id !== '' && $doc !== null) {
$xpath = new \DOMXPath($doc);
$labels = $xpath->query("//*[@id='$id']");
if ($labels !== false && $labels->length > 0) {
$labelNode = $labels->item(0);
if ($labelNode instanceof DOMNode && trim($labelNode->textContent) !== '') {
return null;
}
}
}
}
// 5. Check img with alt attribute
$imgs = $element->getElementsByTagName('img');
foreach ($imgs as $img) {
if ($img->hasAttribute('alt') && trim($img->getAttribute('alt')) !== '') {
return null;
}
}
// 6. Check svg with title or aria-label
$svgs = $element->getElementsByTagName('svg');
foreach ($svgs as $svg) {
if ($svg->hasAttribute('aria-label') && trim($svg->getAttribute('aria-label')) !== '') {
return null;
}
$titles = $svg->getElementsByTagName('title');
foreach ($titles as $title) {
if (trim($title->textContent) !== '') {
return null;
}
}
}
// 7. Check element with role="img" and aria-label
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new \DOMXPath($doc);
$roleImgs = $xpath->query('.//*[@role="img"]', $element);
if ($roleImgs !== false) {
foreach ($roleImgs as $roleImg) {
if ($roleImg instanceof DOMElement && $roleImg->hasAttribute('aria-label') && trim($roleImg->getAttribute('aria-label')) !== '') {
return null;
}
}
}
}
return $this->createViolation(
$element,
$this->getDescription(),
'Add descriptive text, an <img> with alt text, or an aria-label attribute to the heading.'
);
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class FocusNotObscured extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_4_11_FOCUS_NOT_OBSCURED';
}
public function getDescription(): string
{
return 'Fixed, sticky, or overlay elements must not completely obscure keyboard-focused controls (WCAG 2.2 SC 2.4.11).';
}
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 = strtolower($element->getAttribute('style'));
if (trim($style) === '') {
return null;
}
$isFixedOrSticky = str_contains($style, 'position:fixed') || str_contains($style, 'position: fixed') ||
str_contains($style, 'position:sticky') || str_contains($style, 'position: sticky');
if (!$isFixedOrSticky) {
return null;
}
// Check if element is a top/bottom bar with high z-index without scroll-padding considerations
$hasTopOrBottom = str_contains($style, 'top:0') || str_contains($style, 'top: 0') ||
str_contains($style, 'bottom:0') || str_contains($style, 'bottom: 0');
$hasFullWidth = str_contains($style, 'width:100%') || str_contains($style, 'width: 100%') ||
str_contains($style, 'left:0') || str_contains($style, 'left: 0');
if ($hasTopOrBottom && $hasFullWidth) {
// Check if height or z-index is large
return $this->createViolation(
$element,
"Fixed/sticky header or footer overlay may obscure focused items during keyboard navigation (WCAG 2.2 SC 2.4.11).",
"Ensure html/body has adequate scroll-padding-top or scroll-padding-bottom to prevent focused elements from being hidden under sticky bars."
);
}
return null;
}
}
+61 -13
View File
@@ -3,35 +3,56 @@
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use DOMNode;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class FormLabel extends AbstractRule
{
public function getId(): string { return 'WCAG_1_3_1_LABEL'; }
public function getDescription(): string { return 'Form inputs must have an associated label.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 2; }
public function getId(): string
{
return 'WCAG_1_3_1_LABEL';
}
public function getDescription(): string
{
return 'Form inputs must have an associated label.';
}
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
{
$tags = ['input', 'select', 'textarea'];
if (!in_array(strtolower($element->tagName), $tags)) {
if (!in_array(strtolower($element->tagName), $tags, true)) {
return null;
}
// Skip hidden inputs and buttons
$type = strtolower($element->getAttribute('type'));
if ($type === 'hidden' || $type === 'submit' || $type === 'button' || $type === 'reset') {
if ($type === 'hidden' || $type === 'submit' || $type === 'button' || $type === 'reset' || $type === 'image') {
return null;
}
// 1. Check label for="id"
if ($element->hasAttribute('id')) {
$id = $element->getAttribute('id');
$id = trim($element->getAttribute('id'));
$doc = $element->ownerDocument;
if ($doc !== null) {
if ($id !== '' && $doc !== null) {
$xpath = new \DOMXPath($doc);
$labels = $xpath->query("//label[@for='$id']");
if ($labels !== false && $labels->length > 0) {
@@ -40,12 +61,35 @@ class FormLabel extends AbstractRule
}
}
// Check for aria-label, aria-labelledby, or title
if ($element->hasAttribute('aria-label') || $element->hasAttribute('aria-labelledby') || $element->hasAttribute('title')) {
// 2. Check aria-label
if ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '') {
return null;
}
// Check if wrapped in label
// 3. Check aria-labelledby
if ($element->hasAttribute('aria-labelledby')) {
$ariaLabelledby = trim($element->getAttribute('aria-labelledby'));
if ($ariaLabelledby !== '') {
$doc = $element->ownerDocument;
if ($doc !== null) {
$xpath = new \DOMXPath($doc);
$ids = array_filter(explode(' ', $ariaLabelledby));
foreach ($ids as $targetId) {
$targets = $xpath->query("//*[@id='$targetId']");
if ($targets !== false && $targets->length > 0) {
return null;
}
}
}
}
}
// 4. Check title attribute
if ($element->hasAttribute('title') && trim($element->getAttribute('title')) !== '') {
return null;
}
// 5. Check if wrapped in label
$parent = $element->parentNode;
while ($parent) {
if ($parent instanceof DOMElement && strtolower($parent->tagName) === 'label') {
@@ -54,6 +98,10 @@ class FormLabel extends AbstractRule
$parent = $parent->parentNode;
}
return $this->createViolation($element, $this->getDescription(), 'Add a <label for="..."> or an aria-label attribute.');
return $this->createViolation(
$element,
$this->getDescription(),
'Add a <label for="..."> or an aria-label attribute to associate a label with this input.'
);
}
}
+57 -24
View File
@@ -3,39 +3,72 @@
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\AbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class HeadingOrder extends AbstractRule
{
private static int $lastLevel = 0;
public function getId(): string { return 'WCAG_1_3_1_HEADING'; }
public function getDescription(): string { return 'Headings should follow a logical nesting order.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::WARNING; }
public function getLevel(): int { return 2; }
public function check(DOMElement $element): ?Violation
public function getId(): string
{
if (!preg_match('/^h([1-6])$/i', $element->tagName, $matches)) {
return null;
return 'WCAG_1_3_1_HEADING';
}
public function getDescription(): string
{
return 'Headings should follow a logical nesting order without skipping levels.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 2;
}
public function check(\DOMDocument $doc): array
{
$violations = [];
$xpath = new \DOMXPath($doc);
$headings = $xpath->query('//h1 | //h2 | //h3 | //h4 | //h5 | //h6');
if ($headings === false || $headings->length === 0) {
return [];
}
$currentLevel = (int)$matches[1];
// This rule is a bit complex in a per-element check without global state,
// but we can at least check if an h2 comes before an h1 in some cases or jumps.
// For simplicity in this engine, we warn if it's not starting with H1 or jumps too many levels.
if ($currentLevel > self::$lastLevel + 1 && self::$lastLevel !== 0) {
$violation = $this->createViolation($element, "Heading level h$currentLevel jumps from h" . self::$lastLevel, "Ensure headings follow a logical order (h1, then h2, etc.)");
self::$lastLevel = $currentLevel;
return $violation;
$lastLevel = 0;
foreach ($headings as $heading) {
if (!$heading instanceof DOMElement) {
continue;
}
if (!preg_match('/^h([1-6])$/i', $heading->tagName, $matches)) {
continue;
}
$currentLevel = (int)$matches[1];
// If heading jumps more than 1 level down (e.g. h1 to h3, h2 to h5)
if ($lastLevel > 0 && $currentLevel > $lastLevel + 1) {
$violations[] = $this->createViolation(
"Heading level <h{$currentLevel}> jumps from <h{$lastLevel}>, skipping intermediate heading levels.",
$heading,
"Ensure headings follow a logical sequence (e.g., <h1> followed by <h2>, not skipping to <h{$currentLevel}>)."
);
}
$lastLevel = $currentLevel;
}
self::$lastLevel = $currentLevel;
return null;
return $violations;
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class HtmlDirValid extends AbstractRule
{
/** @var array<int, string> */
private static array $validDirValues = ['ltr', 'rtl', 'auto'];
public function getId(): string
{
return 'WCAG_1_3_2_HTML_DIR';
}
public function getDescription(): string
{
return 'The dir attribute must have a valid value (ltr, rtl, or auto).';
}
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 (!$element->hasAttribute('dir')) {
return null;
}
$dir = strtolower(trim($element->getAttribute('dir')));
if (!in_array($dir, self::$validDirValues, true)) {
return $this->createViolation(
$element,
"Invalid dir attribute value \"{$dir}\". Valid values are 'ltr', 'rtl', or 'auto'.",
"Set dir to \"ltr\", \"rtl\", or \"auto\" for proper bidirectional text handling."
);
}
return null;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\AbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
use YakNet\AccessibilityConsole\Syntax\HtmlSyntaxLinter;
class HtmlSyntaxValid extends AbstractRule
{
private HtmlSyntaxLinter $linter;
public function __construct(?HtmlSyntaxLinter $linter = null)
{
$this->linter = $linter ?? new HtmlSyntaxLinter();
}
public function getId(): string
{
return 'WCAG_4_1_1_HTML_PARSING_SYNTAX';
}
public function getDescription(): string
{
return 'HTML documents must be well-formed without duplicate attributes, mismatched tags, or malformed syntax (WCAG 4.1.1).';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 2;
}
public function check(\DOMDocument $doc): array
{
$rawHtml = property_exists($doc, 'rawHtml') && is_string($doc->rawHtml)
? $doc->rawHtml
: $doc->saveHTML();
if (empty($rawHtml) || trim($rawHtml) === '') {
return [];
}
$issues = $this->linter->lint($rawHtml);
$violations = [];
foreach ($issues as $issue) {
$severity = ($issue->severity === 'warning') ? Severity::WARNING : Severity::ERROR;
$violations[] = new Violation(
ruleId: $this->getId(),
message: "[{$issue->code}] {$issue->message}",
severity: $severity,
standard: $this->getStandard(),
htmlSnippet: $issue->snippet,
location: [
'line' => $issue->line,
'column' => $issue->column,
],
fixSuggestion: $issue->fixSuggestion
);
}
return $violations;
}
}
+40 -12
View File
@@ -9,11 +9,30 @@ use YakNet\AccessibilityConsole\Core\WCAGStandard;
class IframeTitle extends AbstractRule
{
public function getId(): string { return 'WCAG_4_1_2_IFRAME_TITLE'; }
public function getDescription(): string { return 'Iframe elements must have a non-empty title attribute to describe their content.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 2; }
public function getId(): string
{
return 'WCAG_4_1_2_IFRAME_TITLE';
}
public function getDescription(): string
{
return 'Iframe elements must have an accessible name (title or aria-label) to describe their content.';
}
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
{
@@ -21,14 +40,23 @@ class IframeTitle extends AbstractRule
return null;
}
if (!$element->hasAttribute('title') || trim($element->getAttribute('title')) === '') {
return $this->createViolation(
$element,
"Iframe element is missing a descriptive title attribute.",
"Add a descriptive title attribute, e.g., title=\"Embedded Map\" or title=\"Video Player\"."
);
// Check if decorative / hidden
if ($element->getAttribute('aria-hidden') === 'true') {
return null;
}
return null;
$title = trim($element->getAttribute('title'));
$ariaLabel = trim($element->getAttribute('aria-label'));
$ariaLabelledby = trim($element->getAttribute('aria-labelledby'));
if ($title !== '' || $ariaLabel !== '' || $ariaLabelledby !== '') {
return null;
}
return $this->createViolation(
$element,
"Iframe element is missing an accessible title or aria-label attribute.",
"Add a descriptive title attribute, e.g., title=\"Embedded Map\" or an aria-label."
);
}
}
@@ -0,0 +1,83 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class InputAutocompleteAppropriate extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_5_AUTOCOMPLETE_APPROPRIATE';
}
public function getDescription(): string
{
return 'Input autocomplete value must be semantically appropriate for the input type (WCAG 1.3.5).';
}
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
{
if (strtolower($element->tagName) !== 'input') {
return null;
}
if (!$element->hasAttribute('autocomplete')) {
return null;
}
$type = strtolower($element->getAttribute('type') ?: 'text');
$autocomplete = strtolower(trim($element->getAttribute('autocomplete')));
if ($autocomplete === '' || in_array($autocomplete, ['on', 'off'], true)) {
return null;
}
// Email type should not have telephone or postal autocomplete
if ($type === 'email' && (str_contains($autocomplete, 'tel') || str_contains($autocomplete, 'postal') || str_contains($autocomplete, 'bday'))) {
return $this->createViolation(
$element,
"Inappropriate autocomplete=\"{$autocomplete}\" on <input type=\"email\">.",
"Use autocomplete=\"email\" or \"username\" for email inputs."
);
}
// Number type should not have name, street-address, or email
if ($type === 'number' && (str_contains($autocomplete, 'name') || str_contains($autocomplete, 'email') || str_contains($autocomplete, 'address') || str_contains($autocomplete, 'country'))) {
return $this->createViolation(
$element,
"Inappropriate autocomplete=\"{$autocomplete}\" on <input type=\"number\">.",
"Number inputs should use numeric autocomplete tokens like \"bday-year\", \"cc-exp-year\", or \"tel\"."
);
}
// Checkbox or Radio should not have email or password autocompletes
if (in_array($type, ['checkbox', 'radio'], true) && (str_contains($autocomplete, 'password') || str_contains($autocomplete, 'email'))) {
return $this->createViolation(
$element,
"Inappropriate autocomplete=\"{$autocomplete}\" on <input type=\"{$type}\">.",
"Do not apply credential or text autocompletes to checkbox/radio inputs."
);
}
return null;
}
}
+51 -27
View File
@@ -9,11 +9,30 @@ use YakNet\AccessibilityConsole\Core\WCAGStandard;
class InputMissingAutocomplete extends AbstractRule
{
public function getId(): string { return 'WCAG_1_3_5_INPUT_AUTOCOMPLETE'; }
public function getDescription(): string { return 'Input fields collecting personal data should have an autocomplete attribute.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::AA; }
public function getSeverity(): Severity { return Severity::WARNING; }
public function getLevel(): int { return 3; }
public function getId(): string
{
return 'WCAG_3_3_8_ACCESSIBLE_AUTH';
}
public function getDescription(): string
{
return 'Authentication inputs must support password managers and must not disable autocomplete or paste (WCAG 2.2 SC 3.3.8).';
}
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
{
@@ -22,32 +41,37 @@ class InputMissingAutocomplete extends AbstractRule
}
$type = strtolower($element->getAttribute('type'));
if (in_array($type, ['hidden', 'submit', 'button', 'reset', 'checkbox', 'radio', 'image', 'file'], true)) {
return null;
}
$name = strtolower($element->getAttribute('name'));
$id = strtolower($element->getAttribute('id'));
$targetKeywords = ['email', 'phone', 'tel', 'username', 'user', 'password', 'pass', 'address', 'zip', 'city', 'country', 'name', 'fname', 'lname'];
$isPersonalField = false;
if (in_array($type, ['email', 'tel'], true)) {
$isPersonalField = true;
} else {
foreach ($targetKeywords as $keyword) {
if (str_contains($name, $keyword) || str_contains($id, $keyword)) {
$isPersonalField = true;
break;
}
// 1. Check for paste blocking on input fields (which harms accessible authentication)
if ($element->hasAttribute('onpaste')) {
$onpaste = strtolower(trim($element->getAttribute('onpaste')));
if (str_contains($onpaste, 'return false') || str_contains($onpaste, 'preventdefault')) {
return $this->createViolation(
$element,
"Input field blocks pasting (onpaste handler). This violates accessible authentication (WCAG 2.2 SC 3.3.8).",
"Remove paste restrictions so users can paste credentials from password managers."
);
}
}
if ($isPersonalField && (!$element->hasAttribute('autocomplete') || trim($element->getAttribute('autocomplete')) === '')) {
return $this->createViolation(
$element,
$this->getDescription(),
'Add an autocomplete attribute (e.g., autocomplete="email", autocomplete="username") to improve accessibility and user experience.'
);
// 2. Password fields should not have autocomplete="off"
if ($type === 'password') {
$autocomplete = strtolower(trim($element->getAttribute('autocomplete')));
if ($autocomplete === 'off') {
return $this->createViolation(
$element,
"Password input has autocomplete=\"off\", preventing password managers from assisting users.",
"Change autocomplete to \"current-password\" or \"new-password\" instead of \"off\"."
);
}
if ($autocomplete === '' && !$element->hasAttribute('autocomplete')) {
return $this->createViolation(
$element,
"Password input should specify autocomplete=\"current-password\" or autocomplete=\"new-password\".",
"Add autocomplete=\"current-password\" (for login) or autocomplete=\"new-password\" (for registration/reset)."
);
}
}
return null;
+118
View File
@@ -0,0 +1,118 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use DOMNode;
use DOMXPath;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class LabelInName extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_5_3_LABEL_IN_NAME';
}
public function getDescription(): string
{
return 'Accessible name must contain the visible text label of interactive controls (WCAG 2.5.3).';
}
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($element->getAttribute('role'));
$isInteractive = in_array($tag, ['button', 'a'], true)
|| ($tag === 'input' && in_array(strtolower($element->getAttribute('type')), ['button', 'submit', 'reset'], true))
|| in_array($role, ['button', 'link'], true);
if (!$isInteractive) {
return null;
}
// Avoid template false positives
$html = $element->ownerDocument ? $element->ownerDocument->saveHTML($element) : '';
if ($html !== false && preg_match('/<\?php|\{\{|\{%/i', $html)) {
return null;
}
// Determine visible text
$visibleText = '';
if ($tag === 'input') {
$visibleText = trim($element->getAttribute('value'));
} else {
$visibleText = trim($element->textContent);
}
// If there is no visible text (e.g. icon-only button), Label in Name criterion does not apply
if ($visibleText === '' || mb_strlen($visibleText) < 2) {
return null;
}
// Get explicit accessible name
$accessibleName = '';
if ($element->hasAttribute('aria-label')) {
$accessibleName = trim($element->getAttribute('aria-label'));
} elseif ($element->hasAttribute('aria-labelledby')) {
$id = trim($element->getAttribute('aria-labelledby'));
$doc = $element->ownerDocument;
if ($doc !== null && $id !== '') {
$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//*[@id="' . $id . '"]');
if ($nodes !== false && $nodes->length > 0) {
$node = $nodes->item(0);
if ($node instanceof DOMNode) {
$accessibleName = trim($node->textContent);
}
}
}
}
// If no explicit ARIA name is set, the visible text itself is the accessible name
if ($accessibleName === '') {
return null;
}
// Normalization: clean extra whitespace and lower case
$normVisible = mb_strtolower((string)preg_replace('/\s+/', ' ', $visibleText));
$normAcc = mb_strtolower((string)preg_replace('/\s+/', ' ', $accessibleName));
// WCAG 2.5.3: Accessible name must contain the visible text
if (!str_contains($normAcc, $normVisible)) {
return $this->createViolation(
$element,
sprintf(
"Accessible name \"%s\" does not contain the visible text \"%s\".",
$accessibleName,
$visibleText
),
sprintf(
"Update aria-label to include \"%s\" (e.g. aria-label=\"%s %s\") so speech input users can activate the control.",
$visibleText,
$visibleText,
$accessibleName
)
);
}
return null;
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class MediaControls extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_4_2_MEDIA_CONTROLS';
}
public function getDescription(): string
{
return 'Audio and video elements should provide controls for user interaction.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 2;
}
public function check(DOMElement $element): ?Violation
{
$tag = strtolower($element->tagName);
if ($tag !== 'audio' && $tag !== 'video') {
return null;
}
// Check if controls attribute is present
if ($element->hasAttribute('controls')) {
return null;
}
// Allow background video if explicitly muted and looping
$isMuted = $element->hasAttribute('muted');
$isAutoplay = $element->hasAttribute('autoplay');
$isLoop = $element->hasAttribute('loop');
if ($tag === 'video' && $isMuted && $isAutoplay && $isLoop) {
return null;
}
return $this->createViolation(
$element,
"<{$tag}> element is missing the 'controls' attribute.",
"Add the 'controls' attribute to allow users to play, pause, and adjust media volume."
);
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\AbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class MetaCharsetPresent extends AbstractRule
{
public function getId(): string
{
return 'WCAG_3_1_1_META_CHARSET';
}
public function getDescription(): string
{
return 'HTML documents should specify character encoding (meta charset) inside the <head> element.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 2;
}
public function check(\DOMDocument $doc): array
{
$heads = $doc->getElementsByTagName('head');
if ($heads->length === 0) {
return [];
}
$head = $heads->item(0);
if (!$head instanceof DOMElement) {
return [];
}
$hasCharset = false;
$metas = $head->getElementsByTagName('meta');
foreach ($metas as $meta) {
if ($meta->hasAttribute('charset') && trim($meta->getAttribute('charset')) !== '') {
$hasCharset = true;
break;
}
if (strtolower($meta->getAttribute('http-equiv')) === 'content-type') {
$content = strtolower($meta->getAttribute('content'));
if (str_contains($content, 'charset=')) {
$hasCharset = true;
break;
}
}
}
if (!$hasCharset) {
return [
$this->createViolation(
"The document <head> is missing a character encoding declaration (<meta charset=\"utf-8\">).",
$head,
"Add <meta charset=\"utf-8\"> as the first child of the <head> tag to prevent screen reader character misinterpretations."
)
];
}
return [];
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class MeterAccessibility extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_METER_ACCESSIBLE';
}
public function getDescription(): string
{
return '<meter> elements must have an accessible name and valid values.';
}
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) !== 'meter') {
return null;
}
// 1. Check for accessible name
$hasName = false;
if ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '') {
$hasName = true;
} elseif ($element->hasAttribute('aria-labelledby') && trim($element->getAttribute('aria-labelledby')) !== '') {
$hasName = true;
} elseif ($element->hasAttribute('title') && trim($element->getAttribute('title')) !== '') {
$hasName = true;
} elseif ($element->hasAttribute('id')) {
$id = trim($element->getAttribute('id'));
$doc = $element->ownerDocument;
if ($id !== '' && $doc !== null) {
$xpath = new \DOMXPath($doc);
$labels = $xpath->query("//label[@for='{$id}']");
if ($labels !== false && $labels->length > 0) {
$hasName = true;
}
}
}
if (!$hasName) {
// Check if wrapped in <label>
$parent = $element->parentNode;
while ($parent) {
if ($parent instanceof DOMElement && strtolower($parent->tagName) === 'label') {
$hasName = true;
break;
}
$parent = $parent->parentNode;
}
}
if (!$hasName) {
return $this->createViolation(
$element,
"<meter> element is missing an accessible name.",
"Add an aria-label, title, or associated <label> element to describe the gauge value."
);
}
return null;
}
}
+31 -9
View File
@@ -10,16 +10,35 @@ use YakNet\AccessibilityConsole\Core\WCAGStandard;
class NestedInteractive extends AbstractRule
{
public function getId(): string { return 'WCAG_4_1_2_NestedInteractive'; }
public function getDescription(): string { return 'Checks for nested interactive elements.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 3; }
public function getId(): string
{
return 'WCAG_4_1_2_NESTED_INTERACTIVE';
}
public function getDescription(): string
{
return 'Interactive elements (<a>, <button>, etc.) must not contain nested interactive controls.';
}
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, ['a', 'button'])) {
if (!in_array($tag, ['a', 'button'], true)) {
return null;
}
@@ -27,14 +46,17 @@ class NestedInteractive extends AbstractRule
if ($doc === null) {
return null;
}
$xpath = new DOMXPath($doc);
$interactives = $xpath->query('.//a | .//button | .//input | .//select | .//textarea', $element);
$interactives = $xpath->query('.//a[@href] | .//button | .//select | .//textarea | .//input[not(@type="hidden")]', $element);
if ($interactives !== false && $interactives->length > 0) {
$first = $interactives->item(0);
$nestedTag = $first instanceof DOMElement ? strtolower($first->tagName) : 'interactive';
return $this->createViolation(
$element,
"İç içe geçmiş etkileşimli öğeler bulundu (<{$tag}> içerisinde).",
'Ensure interactive controls are not nested.'
"Nested interactive control <{$nestedTag}> found inside <{$tag}>.",
"Ensure interactive controls are not nested inside each other."
);
}
+26 -21
View File
@@ -9,11 +9,30 @@ use YakNet\AccessibilityConsole\Core\WCAGStandard;
class PageTitle extends AbstractRule
{
public function getId(): string { return 'WCAG_2_4_2_PAGE_TITLE'; }
public function getDescription(): string { return 'Web pages must have a non-empty title element in the head.'; }
public function getStandard(): WCAGStandard { return WCAGStandard::A; }
public function getSeverity(): Severity { return Severity::ERROR; }
public function getLevel(): int { return 1; }
public function getId(): string
{
return 'WCAG_2_4_2_PAGE_TITLE';
}
public function getDescription(): string
{
return 'Web pages must have a <title> element inside the <head>.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::ERROR;
}
public function getLevel(): int
{
return 1;
}
public function check(DOMElement $element): ?Violation
{
@@ -26,22 +45,8 @@ class PageTitle extends AbstractRule
if ($titles->length === 0) {
return $this->createViolation(
$element,
$this->getDescription(),
'Add a <title> element inside the <head>.'
);
}
$titleText = '';
$firstTitle = $titles->item(0);
if ($firstTitle !== null) {
$titleText = trim($firstTitle->textContent);
}
if ($titleText === '') {
return $this->createViolation(
$element,
$this->getDescription(),
'Provide descriptive text inside the <title> element.'
"The <head> element is missing a <title> element.",
'Add a <title> element inside the <head> to provide a page title.'
);
}
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use DOMXPath;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class RedundantEntry extends AbstractRule
{
public function getId(): string
{
return 'WCAG_3_3_7_REDUNDANT_ENTRY';
}
public function getDescription(): string
{
return 'Forms with repeated information (such as billing and shipping) must provide auto-population or a selection mechanism (WCAG 2.2 SC 3.3.7).';
}
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) !== 'form') {
return null;
}
$doc = $element->ownerDocument;
if ($doc === null) {
return null;
}
$xpath = new DOMXPath($doc);
// Find all input and select elements in the form
$inputs = $xpath->query('.//input | .//select | .//textarea', $element);
if ($inputs === false || $inputs->length < 4) {
return null;
}
$hasShipping = false;
$hasBilling = false;
$hasSameCheckbox = false;
foreach ($inputs as $input) {
if (!$input instanceof DOMElement) {
continue;
}
$name = strtolower($input->getAttribute('name'));
$id = strtolower($input->getAttribute('id'));
$autocomplete = strtolower($input->getAttribute('autocomplete'));
$type = strtolower($input->getAttribute('type'));
if (str_contains($name, 'shipping') || str_contains($id, 'shipping') || str_contains($autocomplete, 'shipping')) {
$hasShipping = true;
}
if (str_contains($name, 'billing') || str_contains($id, 'billing') || str_contains($autocomplete, 'billing')) {
$hasBilling = true;
}
if ($type === 'checkbox') {
if (str_contains($name, 'same') || str_contains($id, 'same') || str_contains($name, 'copy') || str_contains($id, 'copy')) {
$hasSameCheckbox = true;
}
}
}
// Also check labels for "same as"
if (!$hasSameCheckbox) {
$labels = $xpath->query('.//label', $element);
if ($labels !== false) {
foreach ($labels as $label) {
if ($label instanceof DOMElement) {
$labelText = strtolower(trim($label->textContent));
if (str_contains($labelText, 'same as') || str_contains($labelText, 'aynı') || str_contains($labelText, 'kopyala')) {
$hasSameCheckbox = true;
break;
}
}
}
}
}
// If form has both shipping and billing fields but no "same as" checkbox
if ($hasShipping && $hasBilling && !$hasSameCheckbox) {
return $this->createViolation(
$element,
"Form requires re-entering shipping and billing information without providing a 'Same as shipping' checkbox or auto-fill option (WCAG 2.2 SC 3.3.7 Redundant Entry).",
"Add a checkbox (e.g. 'Billing address is the same as shipping address') or populate with previously entered user data to reduce cognitive burden."
);
}
return null;
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class RoleImgAlt extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_1_1_ROLE_IMG';
}
public function getDescription(): string
{
return 'Elements with role="img" must have an accessible text alternative.';
}
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) === 'img') {
return null; // Handled by ImgAltText
}
$roles = explode(' ', strtolower(trim($element->getAttribute('role'))));
if (!in_array('img', $roles, true)) {
return null;
}
if ($element->getAttribute('aria-hidden') === 'true') {
return null;
}
$ariaLabel = trim($element->getAttribute('aria-label'));
$ariaLabelledby = trim($element->getAttribute('aria-labelledby'));
$title = trim($element->getAttribute('title'));
$text = trim($element->textContent);
if ($ariaLabel !== '' || $ariaLabelledby !== '' || $title !== '' || $text !== '') {
return null;
}
return $this->createViolation(
$element,
"Element with role=\"img\" (<{$element->tagName}>) does not have an accessible name.",
"Provide an accessible description using aria-label, aria-labelledby, or title, or hide it if decorative using aria-hidden=\"true\"."
);
}
}
+94
View File
@@ -0,0 +1,94 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\AbstractRule;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class RuleController
{
/**
* @var array<string, RuleInterface|AbstractRule>
*/
private array $rulesRegistry = [];
/**
* @param array<int, RuleInterface|AbstractRule>|null $rules
*/
public function __construct(?array $rules = null)
{
$allRules = $rules ?? RuleLevels::getRulesForLevel(9);
foreach ($allRules as $rule) {
$id = ($rule instanceof RuleInterface) ? $rule->getId() : (new \ReflectionClass($rule))->getShortName();
$this->rulesRegistry[$id] = $rule;
}
}
/**
* Get rule instance by ID.
*/
public function getRule(string $ruleId): RuleInterface|AbstractRule|null
{
return $this->rulesRegistry[$ruleId] ?? null;
}
/**
* Execute a specific rule directly on a DOM element.
*/
public function executeRule(string $ruleId, DOMElement $element): ?Violation
{
$rule = $this->getRule($ruleId);
if ($rule === null) {
return null;
}
if ($rule instanceof RuleInterface) {
return $rule->check($element);
}
return null;
}
/**
* Filter active rules by WCAG standard (A, AA, AAA).
*
* @return array<string, RuleInterface|AbstractRule>
*/
public function filterByStandard(WCAGStandard $standard): array
{
$filtered = [];
foreach ($this->rulesRegistry as $id => $rule) {
if (method_exists($rule, 'getStandard') && $rule->getStandard() === $standard) {
$filtered[$id] = $rule;
}
}
return $filtered;
}
/**
* Filter active rules by severity.
*
* @return array<string, RuleInterface|AbstractRule>
*/
public function filterBySeverity(Severity $severity): array
{
$filtered = [];
foreach ($this->rulesRegistry as $id => $rule) {
if (method_exists($rule, 'getSeverity') && $rule->getSeverity() === $severity) {
$filtered[$id] = $rule;
}
}
return $filtered;
}
/**
* Total number of registered rules in this controller.
*/
public function count(): int
{
return count($this->rulesRegistry);
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
class RuleExecutionStats
{
/**
* @var array<string, array{invocations: int, total_time_ms: float, violations: int}>
*/
private array $stats = [];
/**
* Record a rule execution metric.
*/
public function record(string $ruleId, float $durationMs, bool $hasViolation = false): void
{
if (!isset($this->stats[$ruleId])) {
$this->stats[$ruleId] = [
'invocations' => 0,
'total_time_ms' => 0.0,
'violations' => 0,
];
}
$this->stats[$ruleId]['invocations']++;
$this->stats[$ruleId]['total_time_ms'] += $durationMs;
if ($hasViolation) {
$this->stats[$ruleId]['violations']++;
}
}
/**
* Get top slowest rules by total execution time.
*
* @return array<string, array{invocations: int, total_time_ms: float, avg_time_ms: float, violations: int}>
*/
public function getSlowestRules(int $limit = 10): array
{
$calculated = [];
foreach ($this->stats as $id => $data) {
$avg = $data['invocations'] > 0 ? ($data['total_time_ms'] / $data['invocations']) : 0.0;
$calculated[$id] = [
'invocations' => $data['invocations'],
'total_time_ms' => round($data['total_time_ms'], 3),
'avg_time_ms' => round($avg, 4),
'violations' => $data['violations'],
];
}
uasort($calculated, function ($a, $b) {
return $b['total_time_ms'] <=> $a['total_time_ms'];
});
return array_slice($calculated, 0, $limit, true);
}
/**
* Get all recorded statistics.
*
* @return array<string, array{invocations: int, total_time_ms: float, violations: int}>
*/
public function getAllStats(): array
{
return $this->stats;
}
/**
* Reset all stats counters.
*/
public function reset(): void
{
$this->stats = [];
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class SelectValidChildren extends AbstractRule
{
/** @var array<int, string> */
private static array $validChildTags = ['option', 'optgroup', 'script', 'template', 'hr'];
public function getId(): string
{
return 'WCAG_1_3_1_SELECT_CHILDREN';
}
public function getDescription(): string
{
return '<select> elements must only contain valid child elements (<option>, <optgroup>, <script>, <template>).';
}
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) !== 'select') {
return null;
}
$invalidTags = [];
foreach ($element->childNodes as $child) {
if ($child instanceof DOMElement) {
$childTag = strtolower($child->tagName);
if (!in_array($childTag, self::$validChildTags, true)) {
$invalidTags[] = "<{$childTag}>";
}
}
}
if (!empty($invalidTags)) {
$invalidStr = implode(', ', array_unique($invalidTags));
return $this->createViolation(
$element,
"<select> contains invalid direct child elements: {$invalidStr}.",
"Remove non-option elements from the <select> or restructure using <optgroup> and <option> tags."
);
}
return null;
}
}
+4 -4
View File
@@ -8,9 +8,9 @@ class StrictRuleSet extends RuleEngine
{
public function __construct()
{
$this->addRule(new ImageAltRule());
$this->addRule(new HeadingOrderRule());
$this->addRule(new EmptyLinkRule());
// Daha fazla kural buraya eklenebilir
$rules = RuleLevels::getRulesForLevel(5);
foreach ($rules as $rule) {
$this->addRule($rule);
}
}
}
+90
View File
@@ -0,0 +1,90 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class TableHeaderNotEmpty extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_TH_NOT_EMPTY';
}
public function getDescription(): string
{
return '<th> table header cells must have discernible text or an accessible name.';
}
public function getStandard(): WCAGStandard
{
return WCAGStandard::A;
}
public function getSeverity(): Severity
{
return Severity::WARNING;
}
public function getLevel(): int
{
return 2;
}
public function check(DOMElement $element): ?Violation
{
if (strtolower($element->tagName) !== 'th') {
return null;
}
$html = $element->ownerDocument ? $element->ownerDocument->saveHTML($element) : '';
if ($html !== false && preg_match('/<\?php|\{\{|\{%/i', $html)) {
return null;
}
// 1. Text content
if (trim($element->textContent) !== '') {
return null;
}
// 2. aria-label or title
if ($element->hasAttribute('aria-label') && trim($element->getAttribute('aria-label')) !== '') {
return null;
}
if ($element->hasAttribute('title') && trim($element->getAttribute('title')) !== '') {
return null;
}
// 3. Img with alt
$imgs = $element->getElementsByTagName('img');
foreach ($imgs as $img) {
if ($img->hasAttribute('alt') && trim($img->getAttribute('alt')) !== '') {
return null;
}
}
// 4. Svg with title or aria-label
$svgs = $element->getElementsByTagName('svg');
foreach ($svgs as $svg) {
if ($svg->hasAttribute('aria-label') && trim($svg->getAttribute('aria-label')) !== '') {
return null;
}
$titles = $svg->getElementsByTagName('title');
foreach ($titles as $title) {
if (trim($title->textContent) !== '') {
return null;
}
}
}
return $this->createViolation(
$element,
"Table header cell <th> is empty and has no accessible name.",
"Add meaningful text content or an aria-label to describe the column or row represented by this <th>."
);
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class TableHeadersAttributeValid extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_3_1_TABLE_HEADERS_ATTR';
}
public function getDescription(): string
{
return 'The headers attribute on table cells must refer to valid <th> elements within the same table.';
}
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 ($tag !== 'td' && $tag !== 'th') {
return null;
}
if (!$element->hasAttribute('headers')) {
return null;
}
$headersStr = trim($element->getAttribute('headers'));
if ($headersStr === '') {
return $this->createViolation(
$element,
"Empty 'headers' attribute found on <{$tag}>.",
"Provide space-separated IDs of the corresponding <th> header cells or remove the empty attribute."
);
}
// Find enclosing table
$table = $element->parentNode;
while ($table !== null && (!($table instanceof DOMElement) || strtolower($table->tagName) !== 'table')) {
$table = $table->parentNode;
}
if (!$table instanceof DOMElement) {
return null;
}
$headerIds = array_filter(explode(' ', $headersStr));
$invalidIds = [];
$doc = $element->ownerDocument;
if ($doc === null) {
return null;
}
$xpath = new \DOMXPath($doc);
foreach ($headerIds as $hid) {
$matchingTh = $xpath->query(".//th[@id='{$hid}']", $table);
if ($matchingTh === false || $matchingTh->length === 0) {
$invalidIds[] = $hid;
}
}
if (!empty($invalidIds)) {
$invalidStr = implode(', ', $invalidIds);
return $this->createViolation(
$element,
"The headers attribute refers to ID(s) not found as <th> elements within the table: {$invalidStr}.",
"Ensure each ID specified in the 'headers' attribute matches the 'id' of a <th> element in this table."
);
}
return null;
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class TargetSizeMinimum extends AbstractRule
{
public function getId(): string
{
return 'WCAG_2_5_8_TARGET_SIZE';
}
public function getDescription(): string
{
return 'Interactive elements must have a minimum target size of at least 24x24 CSS pixels (WCAG 2.2).';
}
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
{
$tagName = strtolower($element->tagName);
$isInteractive = false;
if ($tagName === 'a' && $element->hasAttribute('href')) {
$isInteractive = true;
} elseif (in_array($tagName, ['button', 'select', 'textarea'], true)) {
$isInteractive = true;
} elseif ($tagName === 'input') {
$type = strtolower($element->getAttribute('type'));
if ($type !== 'hidden') {
$isInteractive = true;
}
} elseif ($element->hasAttribute('role')) {
$role = strtolower(trim($element->getAttribute('role')));
if (in_array($role, ['button', 'link', 'checkbox', 'radio', 'tab', 'menuitem'], true)) {
$isInteractive = true;
}
}
if (!$isInteractive) {
return null;
}
$style = $element->getAttribute('style');
if (trim($style) === '') {
return null;
}
$width = $this->parsePixelDimension($style, 'width');
$height = $this->parsePixelDimension($style, 'height');
$tooSmallWidth = ($width !== null && $width < 24.0);
$tooSmallHeight = ($height !== null && $height < 24.0);
if ($tooSmallWidth || $tooSmallHeight) {
$wStr = $width !== null ? "{$width}px" : "auto";
$hStr = $height !== null ? "{$height}px" : "auto";
return $this->createViolation(
$element,
"Interactive element target size ({$wStr} x {$hStr}) is smaller than the required 24x24px minimum (WCAG 2.2 SC 2.5.8).",
"Ensure interactive targets have a minimum width and height of at least 24x24px, or add adequate spacing/padding around them."
);
}
return null;
}
private function parsePixelDimension(string $style, string $prop): ?float
{
if (preg_match('/(?:^|;)\s*' . preg_quote($prop, '/') . '\s*:\s*([0-9.]+)\s*px/i', $style, $matches)) {
return (float)$matches[1];
}
return null;
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class TextSpacing extends AbstractRule
{
public function getId(): string
{
return 'WCAG_1_4_12_TEXT_SPACING';
}
public function getDescription(): string
{
return 'Ensure text containers do not restrict line-height or clip content when text spacing is adjusted (WCAG 1.4.12).';
}
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 (!$element->hasAttribute('style')) {
return null;
}
$style = strtolower($element->getAttribute('style'));
// Check line-height < 1.2 or <= 12px
if (preg_match('/line-height\s*:\s*([^;]+)/i', $style, $matches)) {
$lh = trim($matches[1]);
// Unitless number check
if (is_numeric($lh) && (float)$lh < 1.2 && (float)$lh > 0) {
return $this->createViolation(
$element,
"Inline line-height is set to {$lh}, which is below the recommended minimum of 1.2 to 1.5.",
"Increase line-height to at least 1.5 to satisfy WCAG 1.4.12 Text Spacing."
);
}
// Pixel check (e.g. 10px, 12px)
if (preg_match('/^(\d+(?:\.\d+)?)px$/i', $lh, $pxMatches)) {
$px = (float)$pxMatches[1];
if ($px < 14) {
return $this->createViolation(
$element,
"Inline line-height is fixed to {$px}px, risking text overlapping when resized.",
"Use relative line-height units (e.g. 1.5) instead of fixed small pixel values."
);
}
}
}
// Check fixed height combined with overflow: hidden on text containers
$textTags = ['p', 'div', 'span', 'article', 'section', 'blockquote', 'li'];
if (in_array(strtolower($element->tagName), $textTags, true)) {
if (str_contains($style, 'overflow:hidden') || str_contains($style, 'overflow: hidden')) {
if (preg_match('/(?:^|;)\s*height\s*:\s*(\d+)px/i', $style, $heightMatches)) {
$height = (int)$heightMatches[1];
$textLength = mb_strlen(trim($element->textContent));
if ($height <= 60 && $textLength > 60) {
return $this->createViolation(
$element,
"Fixed height ({$height}px) with overflow:hidden risks clipping text when user overrides text spacing.",
"Use min-height instead of fixed height or avoid overflow:hidden on text containers."
);
}
}
}
}
return null;
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace YakNet\AccessibilityConsole\Rules;
use DOMElement;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class TrackValidation extends AbstractRule
{
/** @var array<int, string> */
private static array $validKinds = ['subtitles', 'captions', 'descriptions', 'chapters', 'metadata'];
public function getId(): string
{
return 'WCAG_1_2_2_TRACK_VALIDATION';
}
public function getDescription(): string
{
return '<track> elements must specify a valid kind, and captions/subtitles must include srclang and label.';
}
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) !== 'track') {
return null;
}
// 1. Kind attribute validity
$kind = strtolower(trim($element->getAttribute('kind')));
if ($kind !== '' && !in_array($kind, self::$validKinds, true)) {
$validList = implode(', ', self::$validKinds);
return $this->createViolation(
$element,
"Invalid track kind \"{$kind}\". Valid values are: {$validList}.",
"Set kind to one of: subtitles, captions, descriptions, chapters, metadata."
);
}
// Default kind if omitted is 'subtitles'
$effectiveKind = $kind !== '' ? $kind : 'subtitles';
// 2. If captions or subtitles, check srclang and label
if (in_array($effectiveKind, ['captions', 'subtitles'], true)) {
$srclang = trim($element->getAttribute('srclang'));
$label = trim($element->getAttribute('label'));
if ($srclang === '') {
return $this->createViolation(
$element,
"<track kind=\"{$effectiveKind}\"> element is missing the required 'srclang' attribute.",
"Add a valid BCP 47 language code (e.g. srclang=\"en\" or srclang=\"tr\")."
);
}
if ($label === '') {
return $this->createViolation(
$element,
"<track kind=\"{$effectiveKind}\"> element is missing the required 'label' attribute.",
"Add a human-readable title (e.g. label=\"English Captions\" or label=\"Türkçe Altyazı\")."
);
}
}
return null;
}
}
+337
View File
@@ -0,0 +1,337 @@
<?php
namespace YakNet\AccessibilityConsole\Syntax;
class HtmlSyntaxLinter
{
/** @var array<int, string> */
private static array $voidElements = [
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
'link', 'meta', 'param', 'source', 'track', 'wbr'
];
/**
* Lint raw HTML/template content for markup syntax errors and structural defects.
*
* @param string $html
* @return SyntaxIssue[]
*/
public function lint(string $html): array
{
if (trim($html) === '') {
return [];
}
$issues = [];
// 1. Check for unclosed comments
$this->checkUnclosedComments($html, $issues);
// 2. Check for duplicate attributes on same tag & malformed attribute syntax
$this->checkAttributes($html, $issues);
// 3. Check for invalid self-closing on non-void elements
$this->checkInvalidSelfClosing($html, $issues);
// 4. Check for unclosed / mismatched tags (structural validation)
$this->checkTagStructure($html, $issues);
// 5. Check multiple DOCTYPE / HEAD / BODY declarations
$this->checkStructureTagMultiplicity($html, $issues);
return $issues;
}
/**
* @param SyntaxIssue[] $issues
*/
private function checkUnclosedComments(string $html, array &$issues): void
{
$offset = 0;
while (($pos = strpos($html, '<!--', $offset)) !== false) {
$endPos = strpos($html, '-->', $pos + 4);
if ($endPos === false) {
$line = $this->getLineFromOffset($html, $pos);
$issues[] = new SyntaxIssue(
code: 'SYNTAX_UNCLOSED_COMMENT',
message: 'HTML comment is opened with <!-- but never closed with -->.',
line: $line,
snippet: mb_substr($html, $pos, 80),
fixSuggestion: 'Close the comment with -->.',
severity: 'error'
);
break;
}
$offset = $endPos + 3;
}
}
/**
* @param SyntaxIssue[] $issues
*/
private function checkAttributes(string $html, array &$issues): void
{
// Match start tags <tagname attributes...>
$pattern = '/<([a-zA-Z0-9:-]+)(\s+[^>]*)?>/s';
if (preg_match_all($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[0] as $index => $match) {
$fullTag = $match[0];
$offset = $match[1];
$tagName = strtolower($matches[1][$index][0]);
if (str_starts_with($fullTag, '<?') || str_starts_with($fullTag, '<!')) {
continue;
}
$attrString = $matches[2][$index][0] ?? '';
if (trim($attrString) === '') {
continue;
}
$line = $this->getLineFromOffset($html, $offset);
// A. Check for missing space between attributes (e.g. href="x"class="y")
if (preg_match('/["\']([a-zA-Z0-9_:-]+)=["\']/', $attrString, $missingSpaceMatch, PREG_OFFSET_CAPTURE)) {
$mOffset = $offset + (int)$missingSpaceMatch[0][1];
$mLine = $this->getLineFromOffset($html, $mOffset);
$issues[] = new SyntaxIssue(
code: 'SYNTAX_MISSING_ATTR_SPACE',
message: "Missing whitespace separator between attributes on <{$tagName}>.",
line: $mLine,
snippet: $fullTag,
fixSuggestion: 'Insert a space between adjacent attributes.',
severity: 'warning'
);
}
// B. Parse individual attributes to check for duplicates
$attrNames = [];
$attrPattern = '/([a-zA-Z0-9_:-]+)(?:\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s>]+)))?/s';
if (preg_match_all($attrPattern, $attrString, $attrMatches)) {
foreach ($attrMatches[1] as $aName) {
$normalizedName = strtolower(trim($aName));
if ($normalizedName === '' || $normalizedName === '/') {
continue;
}
if (isset($attrNames[$normalizedName])) {
$issues[] = new SyntaxIssue(
code: 'SYNTAX_DUPLICATE_ATTR',
message: "Duplicate attribute '{$normalizedName}' declared multiple times on <{$tagName}> element (HTML5 3.2.4 violation).",
line: $line,
snippet: $fullTag,
fixSuggestion: "Remove the duplicate '{$normalizedName}' attribute.",
severity: 'error'
);
} else {
$attrNames[$normalizedName] = true;
}
}
}
}
}
}
/**
* @param SyntaxIssue[] $issues
*/
private function checkInvalidSelfClosing(string $html, array &$issues): void
{
// Match <tagname ... /> where tagname is NOT in void elements list and not SVG/MathML
$pattern = '/<([a-zA-Z0-9-]+)(\s+[^>]*)?\/>/s';
if (preg_match_all($pattern, $html, $matches, PREG_OFFSET_CAPTURE)) {
foreach ($matches[0] as $index => $match) {
$fullTag = $match[0];
$offset = $match[1];
$tagName = strtolower($matches[1][$index][0]);
if (in_array($tagName, self::$voidElements, true)) {
continue; // Allowed to self-close in HTML5/XHTML
}
// Skip SVG and MathML subtrees/elements
if (in_array($tagName, ['path', 'circle', 'rect', 'line', 'polygon', 'polyline', 'ellipse', 'use', 'stop'], true)) {
continue;
}
$line = $this->getLineFromOffset($html, $offset);
$issues[] = new SyntaxIssue(
code: 'SYNTAX_INVALID_SELF_CLOSING',
message: "Self-closing syntax (<{$tagName} />) is invalid on non-void HTML element <{$tagName}>. It causes DOM tree distortion.",
line: $line,
snippet: $fullTag,
fixSuggestion: "Replace with explicit opening and closing tags: <{$tagName}></{$tagName}>.",
severity: 'error'
);
}
}
}
/**
* @param SyntaxIssue[] $issues
*/
private function checkTagStructure(string $html, array &$issues): void
{
// Strip comments and script/style contents for structure check
$clean = preg_replace('/<!--.*?-->/s', '', $html) ?? $html;
$clean = preg_replace('/<script\b[^>]*>.*?<\/script>/si', '', $clean) ?? $clean;
$clean = preg_replace('/<style\b[^>]*>.*?<\/style>/si', '', $clean) ?? $clean;
$clean = preg_replace('/<\?php.*?\?>/si', '', $clean) ?? $clean;
// Find all tags in order: <tag> or </tag>
$tagPattern = '/<(\/)?([a-zA-Z0-9:-]+)(?:\s+[^>]*)?>/s';
if (preg_match_all($tagPattern, $clean, $matches, PREG_OFFSET_CAPTURE)) {
$stack = [];
$trackedTags = [
'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
'details', 'summary', 'dialog', 'main', 'nav', 'header', 'footer',
'section', 'article', 'aside', 'form', 'fieldset', 'div', 'span', 'p', 'a', 'button'
];
foreach ($matches[0] as $index => $match) {
$fullMatch = $match[0];
$offset = $match[1];
$isClosing = ($matches[1][$index][0] === '/');
$tagName = strtolower($matches[2][$index][0]);
if (in_array($tagName, self::$voidElements, true)) {
continue;
}
if (str_starts_with($fullMatch, '<?') || str_starts_with($fullMatch, '<!')) {
continue;
}
// Check self-closing syntax
if (str_ends_with(trim($fullMatch), '/>')) {
continue;
}
if (!in_array($tagName, $trackedTags, true)) {
continue;
}
if (!$isClosing) {
$stack[] = ['tag' => $tagName, 'offset' => $offset, 'line' => $this->getLineFromOffset($clean, $offset)];
} else {
if (empty($stack)) {
$line = $this->getLineFromOffset($clean, $offset);
$issues[] = new SyntaxIssue(
code: 'SYNTAX_UNOPENED_TAG',
message: "Closing tag </{$tagName}> has no matching opening tag.",
line: $line,
snippet: $fullMatch,
fixSuggestion: "Remove the stray </{$tagName}> closing tag.",
severity: 'error'
);
} else {
$last = end($stack);
if ($last['tag'] === $tagName) {
array_pop($stack);
} else {
// Find if $tagName exists deeper in the stack
$foundIndex = null;
for ($i = count($stack) - 1; $i >= 0; $i--) {
if ($stack[$i]['tag'] === $tagName) {
$foundIndex = $i;
break;
}
}
if ($foundIndex !== null) {
$unclosed = array_slice($stack, $foundIndex + 1);
$stack = array_slice($stack, 0, $foundIndex);
$line = $this->getLineFromOffset($clean, $offset);
foreach ($unclosed as $u) {
$issues[] = new SyntaxIssue(
code: 'SYNTAX_MISMATCHED_TAG',
message: "Mismatched closing tag </{$tagName}>; <{$u['tag']}> opened at line {$u['line']} was not closed properly.",
line: $line,
snippet: $fullMatch,
fixSuggestion: "Close <{$u['tag']}> before </{$tagName}>.",
severity: 'error'
);
}
} else {
$line = $this->getLineFromOffset($clean, $offset);
$issues[] = new SyntaxIssue(
code: 'SYNTAX_UNOPENED_TAG',
message: "Closing tag </{$tagName}> has no matching opening tag.",
line: $line,
snippet: $fullMatch,
fixSuggestion: "Remove the stray </{$tagName}> closing tag.",
severity: 'error'
);
}
}
}
}
}
// Check any unclosed structural tags left on stack
foreach ($stack as $unclosed) {
// Ignore optional closing tags like p or li if unclosed at document end
if (in_array($unclosed['tag'], ['p', 'li', 'dt', 'dd', 'span'], true)) {
continue;
}
$issues[] = new SyntaxIssue(
code: 'SYNTAX_UNCLOSED_TAG',
message: "Unclosed tag <{$unclosed['tag']}> opened at line {$unclosed['line']} was never closed.",
line: $unclosed['line'],
snippet: "<{$unclosed['tag']}>",
fixSuggestion: "Add matching closing tag </{$unclosed['tag']}>.",
severity: 'error'
);
}
}
}
/**
* @param SyntaxIssue[] $issues
*/
private function checkStructureTagMultiplicity(string $html, array &$issues): void
{
// 1. Multiple <body> tags
if (preg_match_all('/<body\b[^>]*>/i', $html, $matches, PREG_OFFSET_CAPTURE)) {
if (count($matches[0]) > 1) {
foreach (array_slice($matches[0], 1) as $match) {
$line = $this->getLineFromOffset($html, $match[1]);
$issues[] = new SyntaxIssue(
code: 'SYNTAX_MULTIPLE_BODY',
message: 'Document contains multiple <body> elements. Only one <body> is permitted per HTML document.',
line: $line,
snippet: $match[0],
fixSuggestion: 'Merge contents into a single <body> element.',
severity: 'error'
);
}
}
}
// 2. Multiple <head> tags
if (preg_match_all('/<head\b[^>]*>/i', $html, $matches, PREG_OFFSET_CAPTURE)) {
if (count($matches[0]) > 1) {
foreach (array_slice($matches[0], 1) as $match) {
$line = $this->getLineFromOffset($html, $match[1]);
$issues[] = new SyntaxIssue(
code: 'SYNTAX_MULTIPLE_HEAD',
message: 'Document contains multiple <head> elements. Only one <head> is permitted per HTML document.',
line: $line,
snippet: $match[0],
fixSuggestion: 'Merge head tags into a single <head> element.',
severity: 'error'
);
}
}
}
}
private function getLineFromOffset(string $content, int $offset): int
{
if ($offset <= 0) {
return 1;
}
$sub = substr($content, 0, $offset);
return substr_count($sub, "\n") + 1;
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace YakNet\AccessibilityConsole\Syntax;
class SyntaxIssue
{
public function __construct(
public readonly string $code,
public readonly string $message,
public readonly int $line,
public readonly int $column = 1,
public readonly string $snippet = '',
public readonly ?string $fixSuggestion = null,
public readonly string $severity = 'error'
) {}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'code' => $this->code,
'message' => $this->message,
'line' => $this->line,
'column' => $this->column,
'snippet' => $this->snippet,
'fixSuggestion' => $this->fixSuggestion,
'severity' => $this->severity,
];
}
}
@@ -0,0 +1,35 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Analytics;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Analytics\AccessibilityTelemetry;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class AccessibilityTelemetryTest extends TestCase
{
private AccessibilityTelemetry $telemetry;
protected function setUp(): void
{
$this->telemetry = new AccessibilityTelemetry();
}
public function testComputesDefectDensityAndRatios(): void
{
$violations = [
new Violation(ruleId: 'R1', message: 'M1', severity: Severity::ERROR, standard: WCAGStandard::A),
new Violation(ruleId: 'R2', message: 'M2', severity: Severity::WARNING, standard: WCAGStandard::AA),
];
$metrics = $this->telemetry->computeMetrics($violations, 2000);
$this->assertSame(2, $metrics['total_violations']);
$this->assertSame(1, $metrics['error_count']);
$this->assertSame(1, $metrics['warning_count']);
$this->assertSame(1.0, $metrics['defect_density_per_kloc']); // 2 violations / 2 kloc = 1.0
$this->assertSame(50.0, $metrics['critical_blockers_ratio']); // 1 / 2 = 50%
}
}
@@ -0,0 +1,48 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Analytics;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Analytics\ComplianceMatrixGenerator;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class ComplianceMatrixGeneratorTest extends TestCase
{
private ComplianceMatrixGenerator $generator;
protected function setUp(): void
{
$this->generator = new ComplianceMatrixGenerator();
}
public function testGeneratesMatrixSuccessfully(): void
{
$violations = [
new Violation(
ruleId: 'WCAG_1_1_1_ALT',
message: 'Image alt missing',
severity: Severity::ERROR,
standard: WCAGStandard::A
),
new Violation(
ruleId: 'WCAG_2_4_4_LINK_TEXT',
message: 'Link text empty',
severity: Severity::ERROR,
standard: WCAGStandard::A
),
];
$matrix = $this->generator->generate($violations, 127);
$this->assertArrayHasKey('overall_compliance_percentage', $matrix);
$this->assertArrayHasKey('principles', $matrix);
$this->assertArrayHasKey('levels', $matrix);
$this->assertSame(1, $matrix['principles']['Perceivable']['violations']);
$this->assertSame(1, $matrix['principles']['Operable']['violations']);
$this->assertSame(0, $matrix['principles']['Understandable']['violations']);
$this->assertSame('Pass', $matrix['principles']['Understandable']['status']);
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\AutoFix;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Core\SelfHealing\LocalHealer;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
class LocalHealerTest extends TestCase
{
private LocalHealer $healer;
protected function setUp(): void
{
$this->healer = new LocalHealer();
}
public function testHealsMissingImgAlt(): void
{
$violation = new Violation(
'WCAG_1_1_1_IMG_ALT',
'Image missing alt',
Severity::ERROR,
WCAGStandard::A,
'<img src="photo.jpg">'
);
$healed = $this->healer->heal($violation);
$this->assertNotNull($healed);
$this->assertStringContainsString('FIX: <img alt="" src="photo.jpg">', $healed);
}
public function testHealsDecorativeSvg(): void
{
$violation = new Violation(
'WCAG_1_1_1_SVG',
'SVG needs accessible text',
Severity::ERROR,
WCAGStandard::A,
'<svg class="icon"><path d="..."/></svg>'
);
$healed = $this->healer->heal($violation);
$this->assertNotNull($healed);
$this->assertStringContainsString('FIX: <svg aria-hidden="true" class="icon">', $healed);
}
public function testHealsTargetBlankLinkRel(): void
{
$violation = new Violation(
'WCAG_LINK_TARGET_BLANK',
'Target blank missing noopener',
Severity::WARNING,
WCAGStandard::A,
'<a href="https://example.com" target="_blank">External</a>'
);
$healed = $this->healer->heal($violation);
$this->assertNotNull($healed);
$this->assertStringContainsString('rel="noopener noreferrer"', $healed);
}
public function testHealsPositiveTabindex(): void
{
$violation = new Violation(
'WCAG_2_4_3_TABINDEX',
'Avoid positive tabindex',
Severity::WARNING,
WCAGStandard::A,
'<button tabindex="5">Submit</button>'
);
$healed = $this->healer->heal($violation);
$this->assertNotNull($healed);
$this->assertStringContainsString('tabindex="0"', $healed);
}
public function testHealsInvalidTableScope(): void
{
$violation = new Violation(
'WCAG_1_3_1_TABLE_SCOPE',
'Scope only on headers',
Severity::ERROR,
WCAGStandard::A,
'<td scope="col">Data cell</td>'
);
$healed = $this->healer->heal($violation);
$this->assertNotNull($healed);
$this->assertStringNotContainsString('scope=', $healed);
}
public function testHealsMetaRefresh(): void
{
$violation = new Violation(
'WCAG_2_2_1_META_REFRESH',
'Meta refresh banned',
Severity::ERROR,
WCAGStandard::A,
'<meta http-equiv="refresh" content="30">'
);
$healed = $this->healer->heal($violation);
$this->assertNotNull($healed);
$this->assertStringContainsString('<!-- <meta http-equiv="refresh" content="30"> (Removed', $healed);
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Badges;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Badges\BadgeGenerator;
class BadgeGeneratorTest extends TestCase
{
public function testGeneratesValidScoreBadgeSvg(): void
{
$svg = BadgeGenerator::generateScoreBadge(95);
$this->assertStringContainsString('<svg', $svg);
$this->assertStringContainsString('</svg>', $svg);
$this->assertStringContainsString('accessibility', $svg);
$this->assertStringContainsString('95/100', $svg);
$this->assertStringContainsString('#10b981', $svg); // green color for >= 90
}
public function testGeneratesWarningScoreBadgeSvg(): void
{
$svg = BadgeGenerator::generateScoreBadge(65);
$this->assertStringContainsString('65/100', $svg);
$this->assertStringContainsString('#ef4444', $svg); // red color for < 70
}
public function testGeneratesComplianceBadge(): void
{
$svg = BadgeGenerator::generateComplianceBadge('WCAG 2.1 AA', true);
$this->assertStringContainsString('WCAG 2.1 AA', $svg);
$this->assertStringContainsString('passed', $svg);
}
public function testGeneratesViolationsBadge(): void
{
$svg = BadgeGenerator::generateViolationsBadge(0);
$this->assertStringContainsString('0 issues', $svg);
$svgIssues = BadgeGenerator::generateViolationsBadge(4);
$this->assertStringContainsString('4 issues', $svgIssues);
}
public function testGeneratesBadgeWithCustomOptions(): void
{
$options = new \YakNet\AccessibilityConsole\Badges\BadgeOptions(
label: 'custom-a11y',
leftColor: '#003366',
rightColor: '#00cc66',
borderRadius: 6
);
$svg = BadgeGenerator::generateScoreBadge(88, $options);
$this->assertStringContainsString('custom-a11y', $svg);
$this->assertStringContainsString('#003366', $svg);
$this->assertStringContainsString('#00cc66', $svg);
$this->assertStringContainsString('rx="6"', $svg);
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Console;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
use YakNet\AccessibilityConsole\Console\Command\RulesCommand;
class RulesCommandTest extends TestCase
{
public function testListAllRules(): void
{
$command = new RulesCommand();
$tester = new CommandTester($command);
$exitCode = $tester->execute([]);
$this->assertSame(0, $exitCode);
$output = $tester->getDisplay();
$this->assertStringContainsString('Accessibility Console - Available Rules', $output);
$this->assertStringContainsString('Total rules available: 130', $output);
}
public function testFilterRulesBySearch(): void
{
$command = new RulesCommand();
$tester = new CommandTester($command);
$exitCode = $tester->execute([
'--search' => 'contrast',
]);
$this->assertSame(0, $exitCode);
$output = $tester->getDisplay();
$this->assertStringContainsString('WCAG_1_4_3_CONTRAST', $output);
$this->assertStringContainsString('Showing', $output);
}
public function testFilterRulesByStandardAndLevel(): void
{
$command = new RulesCommand();
$tester = new CommandTester($command);
$exitCode = $tester->execute([
'--standard' => 'AA',
]);
$this->assertSame(0, $exitCode);
$output = $tester->getDisplay();
$this->assertStringContainsString('AA', $output);
$this->assertStringContainsString('Showing', $output);
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Console;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
use YakNet\AccessibilityConsole\Console\Command\WatchCommand;
class WatchCommandTest extends TestCase
{
public function testWatchCommandRunsInitialScanAndExitsWithMaxIterations(): void
{
$command = new WatchCommand();
$tester = new CommandTester($command);
$exitCode = $tester->execute([
'target' => 'demo/views-fixed/home.php',
'--max-iterations' => '1',
'--interval' => '1',
]);
$this->assertSame(0, $exitCode);
$output = $tester->getDisplay();
$this->assertStringContainsString('Accessibility Console - Real-Time Watch Mode', $output);
$this->assertStringContainsString('Initial Scan', $output);
$this->assertStringContainsString('Health Score:', $output);
}
public function testDetectChangedFiles(): void
{
$command = new WatchCommand();
$old = [
'file1.php' => 100,
'file2.php' => 200,
];
$new = [
'file1.php' => 100,
'file2.php' => 205, // modified
'file3.php' => 300, // added
];
$changed = $command->detectChangedFiles($old, $new);
$this->assertContains('file2.php', $changed);
$this->assertContains('file3.php', $changed);
$this->assertNotContains('file1.php', $changed);
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Core;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Core\Locator\PreciseElementLocator;
class PreciseElementLocatorTest extends TestCase
{
private PreciseElementLocator $locator;
protected function setUp(): void
{
$this->locator = new PreciseElementLocator();
}
public function testLocatesExactMatch(): void
{
$content = "<html>\n<body>\n<div class=\"container\">\n<img src=\"logo.png\">\n</div>\n</body>\n</html>";
$snippet = '<img src="logo.png">';
$loc = $this->locator->locate($content, $snippet);
$this->assertSame(4, $loc['line']);
}
public function testLocatesAttributeTokenMatch(): void
{
$content = "<div>\n<button id=\"save-btn\" class=\"btn btn-primary\">\nSave\n</button>\n</div>";
// Snippet with different whitespace/attr arrangement
$snippet = '<button class="btn btn-primary" id="save-btn">';
$loc = $this->locator->locate($content, $snippet);
$this->assertSame(2, $loc['line']);
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Core;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Core\RuleRegistry;
use YakNet\AccessibilityConsole\Rules\RuleLevels;
class RuleRegistryTest extends TestCase
{
public function testValidateRuleSetHasZeroDuplicates(): void
{
$rules = RuleLevels::getRulesForLevel(9);
$result = RuleRegistry::validate($rules);
$this->assertTrue($result['valid'], 'Rule validation failed: ' . implode("\n", $result['errors']));
$this->assertEmpty($result['errors']);
$this->assertGreaterThanOrEqual(120, $result['count']);
}
public function testGetMetadataReturnsAccurateData(): void
{
$rules = RuleLevels::getRulesForLevel(1);
$firstRule = $rules[0];
$meta = RuleRegistry::getMetadata($firstRule);
$this->assertArrayHasKey('id', $meta);
$this->assertArrayHasKey('class', $meta);
$this->assertArrayHasKey('severity', $meta);
$this->assertArrayHasKey('standard', $meta);
$this->assertArrayHasKey('level', $meta);
}
}
@@ -0,0 +1,37 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Notifications;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Notifications\NotificationDispatcher;
use YakNet\AccessibilityConsole\Notifications\NotificationPayload;
use YakNet\AccessibilityConsole\Notifications\NotifierInterface;
class NotificationDispatcherTest extends TestCase
{
public function testDispatchToMultipleNotifiers(): void
{
$dispatcher = new NotificationDispatcher();
$mockSlack = $this->createMock(NotifierInterface::class);
$mockSlack->expects($this->once())
->method('send')
->willReturn(true);
$mockDiscord = $this->createMock(NotifierInterface::class);
$mockDiscord->expects($this->once())
->method('send')
->willReturn(true);
$dispatcher->addNotifier('slack', $mockSlack);
$dispatcher->addNotifier('discord', $mockDiscord);
$this->assertTrue($dispatcher->hasNotifiers());
$payload = new NotificationPayload('https://example.com', 95, 2, 0, 2);
$results = $dispatcher->dispatch($payload);
$this->assertTrue($results['slack']);
$this->assertTrue($results['discord']);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Parser;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Parser\TemplatePreprocessor;
class TemplatePreprocessorTest extends TestCase
{
private TemplatePreprocessor $preprocessor;
protected function setUp(): void
{
$this->preprocessor = new TemplatePreprocessor();
}
public function testPreprocessesBladeTemplate(): void
{
$blade = "<div>\n@if(true)\n<h1>{{ title }}</h1>\n@endif\n</div>";
$processed = $this->preprocessor->preprocess($blade, 'views/user.blade.php');
$this->assertStringNotContainsString('@if', $processed);
$this->assertStringNotContainsString('{{', $processed);
$this->assertStringContainsString('<h1>', $processed);
// Verify line count is preserved
$this->assertSame(substr_count($blade, "\n"), substr_count($processed, "\n"));
}
public function testPreprocessesTwigTemplate(): void
{
$twig = "<div>\n{% if logged_in %}\n<p>{{ user.email }}</p>\n{% endif %}\n</div>";
$processed = $this->preprocessor->preprocess($twig, 'templates/user.twig');
$this->assertStringNotContainsString('{%', $processed);
$this->assertStringNotContainsString('{{', $processed);
$this->assertStringContainsString('<p>', $processed);
// Verify line count is preserved
$this->assertSame(substr_count($twig, "\n"), substr_count($processed, "\n"));
}
public function testPreprocessesPhpTemplate(): void
{
$php = "<div>\n<?php if (true): ?>\n<button><?= \$label ?></button>\n<?php endif; ?>\n</div>";
$processed = $this->preprocessor->preprocess($php, 'views/button.php');
$this->assertStringNotContainsString('<?php', $processed);
$this->assertStringNotContainsString('<?=', $processed);
$this->assertStringContainsString('<button>', $processed);
// Verify line count is preserved
$this->assertSame(substr_count($php, "\n"), substr_count($processed, "\n"));
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Presets;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Presets\PresetRegistry;
use YakNet\AccessibilityConsole\Presets\Section508Preset;
use YakNet\AccessibilityConsole\Presets\En301549Preset;
use YakNet\AccessibilityConsole\Presets\ECommercePreset;
class PresetRegistryTest extends TestCase
{
public function testRegistryLoadsDefaultPresets(): void
{
$registry = new PresetRegistry();
$all = $registry->all();
$this->assertArrayHasKey('section508', $all);
$this->assertArrayHasKey('en301549', $all);
$this->assertArrayHasKey('ecommerce', $all);
}
public function testGetPresetByName(): void
{
$registry = new PresetRegistry();
$preset = $registry->get('section508');
$this->assertInstanceOf(Section508Preset::class, $preset);
$this->assertSame(3, $preset->getLevel());
$ecommerce = $registry->get('ecommerce');
$this->assertInstanceOf(ECommercePreset::class, $ecommerce);
$this->assertContains('WCAG_3_3_7_REDUNDANT_ENTRY', $ecommerce->getIncludedRules());
}
public function testGetNonExistentPresetReturnsNull(): void
{
$registry = new PresetRegistry();
$this->assertNull($registry->get('non_existent'));
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Reporting;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
use YakNet\AccessibilityConsole\Reporting\JunitFormatter;
class JunitFormatterTest extends TestCase
{
public function testRendersValidJunitXmlWithViolations(): void
{
$formatter = new JunitFormatter();
$violations = [
new Violation(
'WCAG_1_1_1_IMG_ALT',
'Images must have alternative text.',
Severity::ERROR,
WCAGStandard::A,
'<img src="photo.png">',
['file' => 'views/index.php', 'line' => 10, 'column' => 2]
),
];
$xml = $formatter->render($violations);
$this->assertStringContainsString('<?xml version="1.0" encoding="UTF-8"?>', $xml);
$this->assertStringContainsString('<testsuites', $xml);
$this->assertStringContainsString('failures="1"', $xml);
$this->assertStringContainsString('<failure', $xml);
$this->assertStringContainsString('WCAG_1_1_1_IMG_ALT', $xml);
// Verify valid XML parsing
$dom = new \DOMDocument();
$this->assertTrue($dom->loadXML($xml));
}
public function testRendersCleanXmlWhenEmpty(): void
{
$formatter = new JunitFormatter();
$input = new ArrayInput([]);
$output = new BufferedOutput();
$io = new SymfonyStyle($input, $output);
$exitCode = $formatter->format([], 0, $io);
$this->assertSame(0, $exitCode);
$xml = $output->fetch();
$this->assertStringContainsString('failures="0"', $xml);
$this->assertStringContainsString('AccessibilityCompliant', $xml);
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Reporting;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Style\SymfonyStyle;
use YakNet\AccessibilityConsole\Core\Severity;
use YakNet\AccessibilityConsole\Core\Violation;
use YakNet\AccessibilityConsole\Core\WCAGStandard;
use YakNet\AccessibilityConsole\Reporting\SarifFormatter;
class SarifFormatterTest extends TestCase
{
public function testRendersValidSarifJson(): void
{
$formatter = new SarifFormatter();
$violations = [
new Violation(
'WCAG_1_1_1_IMG_ALT',
'Images must have alternative text.',
Severity::ERROR,
WCAGStandard::A,
'<img src="test.jpg">',
['file' => 'templates/home.blade.php', 'line' => 14, 'column' => 5],
'Add alt="" attribute'
),
new Violation(
'WCAG_1_4_3_CONTRAST',
'Insufficient color contrast.',
Severity::WARNING,
WCAGStandard::AA,
'<span style="color:#ccc">Text</span>',
['file' => 'templates/home.blade.php', 'line' => 20, 'column' => 1]
),
];
$json = $formatter->render($violations);
$this->assertJson($json);
$decoded = json_decode($json, true);
$this->assertIsArray($decoded);
$this->assertSame('2.1.0', $decoded['version']);
$this->assertSame('YakNet Accessibility Console', $decoded['runs'][0]['tool']['driver']['name']);
$this->assertCount(2, $decoded['runs'][0]['results']);
$firstResult = $decoded['runs'][0]['results'][0];
$this->assertSame('WCAG_1_1_1_IMG_ALT', $firstResult['ruleId']);
$this->assertSame('error', $firstResult['level']);
$this->assertSame('templates/home.blade.php', $firstResult['locations'][0]['physicalLocation']['artifactLocation']['uri']);
$this->assertSame(14, $firstResult['locations'][0]['physicalLocation']['region']['startLine']);
}
public function testFormatOutputsToSymfonyStyle(): void
{
$formatter = new SarifFormatter();
$violations = [];
$input = new ArrayInput([]);
$output = new BufferedOutput();
$io = new SymfonyStyle($input, $output);
$exitCode = $formatter->format($violations, 0, $io);
$this->assertSame(0, $exitCode);
$content = $output->fetch();
$this->assertJson($content);
$decoded = json_decode($content, true);
$this->assertIsArray($decoded);
$this->assertEmpty($decoded['runs'][0]['results']);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Rules;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Rules\AccesskeyDuplicate;
class AccesskeyDuplicateTest extends TestCase
{
public function testFlagsDuplicateAccesskeys(): void
{
$scanner = new Scanner();
$scanner->addRule(new AccesskeyDuplicate());
$violations = $scanner->scan('<div><a href="/" accesskey="h">Home</a><a href="/help" accesskey="h">Help</a></div>');
$this->assertCount(2, $violations);
$this->assertSame('WCAG_2_1_1_ACCESSKEY_DUPLICATE', $violations[0]->ruleId);
}
public function testPassesUniqueAccesskeys(): void
{
$scanner = new Scanner();
$scanner->addRule(new AccesskeyDuplicate());
$violations = $scanner->scan('<div><a href="/" accesskey="h">Home</a><a href="/help" accesskey="p">Help</a></div>');
$this->assertCount(0, $violations);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Rules;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Rules\AriaBrailleEquivalent;
class AriaBrailleEquivalentTest extends TestCase
{
public function testFlagsBrailleLabelWithoutStandardName(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaBrailleEquivalent());
$violations = $scanner->scan('<div><button aria-braillelabel="btn"></button></div>');
$this->assertCount(1, $violations);
$this->assertSame('WCAG_4_1_2_ARIA_BRAILLE', $violations[0]->ruleId);
}
public function testPassesBrailleLabelWithAriaLabel(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaBrailleEquivalent());
$violations = $scanner->scan('<div><button aria-braillelabel="btn" aria-label="Submit Form">Submit</button></div>');
$this->assertCount(0, $violations);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Rules;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Rules\AriaCurrentValid;
class AriaCurrentValidTest extends TestCase
{
public function testFlagsInvalidAriaCurrent(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaCurrentValid());
$violations = $scanner->scan('<div><a href="/home" aria-current="active">Home</a></div>');
$this->assertCount(1, $violations);
$this->assertSame('WCAG_4_1_2_ARIA_CURRENT', $violations[0]->ruleId);
}
public function testPassesValidAriaCurrent(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaCurrentValid());
$violations = $scanner->scan('<div><a href="/home" aria-current="page">Home</a></div>');
$this->assertCount(0, $violations);
}
public function testPassesBooleanAriaCurrent(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaCurrentValid());
$violations = $scanner->scan('<div><a href="/step2" aria-current="true">Step 2</a></div>');
$this->assertCount(0, $violations);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Rules;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Rules\AriaDisabledFocusable;
class AriaDisabledFocusableTest extends TestCase
{
public function testFlagsDisabledWithPositiveTabindex(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaDisabledFocusable());
$violations = $scanner->scan('<div><button disabled tabindex="0">Disabled Button</button></div>');
$this->assertCount(1, $violations);
$this->assertSame('WCAG_4_1_2_ARIA_DISABLED', $violations[0]->ruleId);
}
public function testPassesStandardDisabled(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaDisabledFocusable());
$violations = $scanner->scan('<div><button disabled>Disabled Button</button></div>');
$this->assertCount(0, $violations);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace YakNet\AccessibilityConsole\Tests\Rules;
use PHPUnit\Framework\TestCase;
use YakNet\AccessibilityConsole\Core\Scanner;
use YakNet\AccessibilityConsole\Rules\AriaErrorMessage;
class AriaErrorMessageTest extends TestCase
{
public function testFlagsMissingTargetElement(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaErrorMessage());
$violations = $scanner->scan('<div><input id="email" aria-invalid="true" aria-errormessage="nonexistent_err"></div>');
$this->assertCount(1, $violations);
$this->assertSame('WCAG_3_3_1_ARIA_ERRORMESSAGE', $violations[0]->ruleId);
}
public function testFlagsMissingAriaInvalid(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaErrorMessage());
$violations = $scanner->scan('<div><input id="email" aria-errormessage="email_err"><span id="email_err">Error</span></div>');
$this->assertCount(1, $violations);
}
public function testPassesValidErrorMessageSetup(): void
{
$scanner = new Scanner();
$scanner->addRule(new AriaErrorMessage());
$violations = $scanner->scan('<div><input id="email" aria-invalid="true" aria-errormessage="email_err"><span id="email_err">Invalid Email Address</span></div>');
$this->assertCount(0, $violations);
}
}

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