Skip to content

Usage

Both classes are fluent. Build the command, call run(), and read the result object. Nothing is executed until run().

Single page with Pa11y

use JkOster\Pa11y\Pa11y;

$result = Pa11y::fromUrl('https://example.com')
    ->standard('WCAG2AA')
    ->includeWarnings()
    ->includeNotices()
    ->timeout(20000)
    ->run();

Pa11y builds this command:

pa11y https://example.com --standard WCAG2AA --include-warnings --include-notices --timeout 20000 \
  --reporter json --config ./pa11y.config.json --level none

The last three options are required. Pa11y::run() reads the JSON reporter output and returns a Pa11yResult.

Pa11y options

Every convenience method maps to a pa11y CLI flag. setOption() is the escape hatch for anything not listed.

MethodCLI flagValue
standard(string $name)--standardWCAG2A, WCAG2AA, WCAG2AAA, Section508
runner(string $runner)--runnerhtmlcs or axe
ignore(string $ignore)--ignoreOne rule or a semicolon-separated list
includeNotices()--include-noticesFlag, no value
includeWarnings()--include-warningsFlag, no value
rootElement(string $selector)--root-elementCSS selector
hideElements(string $selectors)--hide-elementsCSS selector, comma separated
config(string $path)--configPath to a config file
timeout(int $ms)--timeoutNavigation timeout in milliseconds
wait(int $ms)--waitWait before the audit, in milliseconds
debug()--debugFlag, no value
screenCapture(string $path)--screen-captureOutput path for a screenshot
addRule(string $rule)--add-ruleHTML CodeSniffer rule, semicolon separated
processTimeout(int $sec)noneSymfony process timeout, default 300 seconds

setOption('wait', 1000) is the same as wait(1000). Use the flag name without the leading --, including hyphens: setOption('root-element', '#main').

ignore() and addRule() accept one string. A second call replaces the first because options are stored by key. Pass 'rule-a;rule-b' to send several values in one call.

Required options and precedence

commandArgs() merges the required map after the options set on the instance:

const REQUIRED_OPTIONS = [
    'reporter' => 'json',
    'config' => './pa11y.config.json',
    'level' => 'none',
];

The required values win over setOption() for the same key. config() therefore does not change the file used by the command. Edit pa11y.config.json or pass another option. Values in the config file are overridden by CLI flags that the package passes. commandArgs() returns the full argument list and is useful in tests.

Many pages with Pa11yCi

Pa11yCi wraps pa11y-ci. It accepts a URL list or a sitemap and returns one Pa11yCiResult for all pages.

use JkOster\Pa11y\Pa11yCi;

$result = Pa11yCi::fromUrls([
    'https://example.com',
    'https://example.org/about',
])
    ->viewport(320, 480)
    ->includeNotices(false)
    ->concurrency(2)
    ->run();
use JkOster\Pa11y\Pa11yCi;

$result = Pa11yCi::fromSitemap('https://example.com/sitemap.xml')
    ->sitemapExclude('/blog/')
    ->run();
pa11y-ci --config '{"defaults":{...},"threshold":99999999,"concurrency":1,"urls":[]}' --json

The config is passed as one inline JSON argument. That is why pa11y-ci must be the jk-oster/pa11y-ci fork.

URLs and sitemaps

MethodEffect
fromUrls(array $urls)Static constructor for a URL list
fromSitemap(string $url)Static constructor that sets sitemap
urls(array $urls)Replaces the URL list
sitemap(string $sitemapUrl)Sets the sitemap URL
sitemapFind(string $pattern)Regex replaced in sitemap URLs
sitemapReplace(string $string)Replacement for sitemapFind
sitemapExclude(string $pattern)Regex for sitemap URLs to skip

The fork follows sitemap indexes. A sitemap that points to other sitemaps is expanded recursively, and every <loc> is audited as written. The result key is the normalised page URL, usually with a trailing slash.

Pa11y options for each page

These methods write to defaults.*, so one value applies to every URL in the run.

MethodConfig key
standard(string $standard)defaults.standard
runners(array $runners = ['htmlcs'])defaults.runners
ignore(array $ignore)defaults.ignore
rules(array $rules)defaults.rules
actions(array $actions)defaults.actions
headers(array $headers)defaults.headers
viewport(int $width, int $height, int $deviceScaleFactor = 1, bool $isMobile = false)defaults.viewport
hideElements(array $elements)defaults.hideElements
rootElement(string $rootElement)defaults.rootElement
screenCapture(string $path)defaults.screenCapture
includeNotices(bool $include = true)defaults.includeNotices
includeWarnings(bool $include = true)defaults.includeWarnings
timeout(int $ms)defaults.timeout
wait(int $ms)defaults.wait
userAgent(string $userAgent)defaults.userAgent
method(string $method)defaults.method
postData(array $postData)defaults.postData

The default viewport is 1280 by 1024 at scale 1, not mobile. The default audit timeout is 10000 ms.

actions takes pa11y action strings:

->actions([
    'click element #accept-cookies',
    'wait for path to be ready /account',
])

headers and postData take associative arrays:

->headers(['Authorization' => 'Bearer token'])
->method('POST')
->postData(['search' => 'accessibility'])

Run settings

MethodDefaultEffect
concurrency(int $count)1Number of pages audited at once
debug(bool $debug = true)falseEcho the generated command before running
processTimeout(int $sec)600Symfony process timeout, not the per-page audit timeout
setOption(string $path, $value = null)noneSet any config key with dot notation

setOption('defaults.timeout', 20000) is the same as timeout(20000). setOption('threshold', 100) changes the failure threshold. The default threshold is 99999999, so an audit with findings still returns a result instead of a non-zero exit code.

Writing results to a file

saveToFile() switches the JSON reporter to a file. pa11y-ci prints the file name on stdout, and the package reads that file.

$result = Pa11yCi::fromUrls(['https://example.com'])
    ->saveToFile('/tmp/report.json')
    ->run();

$result->getOutputFilePath(); // /tmp/report.json

Call saveToFile() without an argument to create a temporary file. The package deletes that file after reading it unless deleteTempFiles(false) is set:

$result = Pa11yCi::fromUrls(['https://example.com'])
    ->saveToFile()
    ->deleteTempFiles(false)
    ->run();

file_exists($result->getOutputFilePath()); // true

The package never deletes a path you pass yourself. getOutputFilePath() returns the configured path, or null when the default stdout reporter is used.

Configuration and precedence

run() deep merges DEFAULT_CONFIG with the options set on the instance, then encodes the result as inline JSON. Later values win per key:

  1. DEFAULT_CONFIG
  2. setOption() and the convenience methods
  3. config(array $config), which deep merges its array over the current options
  4. saveToFile(), which replaces defaults.reporters

getConfig() on the result returns the final merged config, so you can check what ran.

Results

Pa11yResult

$result = Pa11y::fromUrl('https://example.com')->run();

$result->getErrorsCount();
$result->getWarningsCount();
$result->getNoticesCount();
$result->getTotalIssueCount();
$result->getRunner();
MethodReturns
getRawResults()The decoded JSON array
getErrors()Pa11yIssue[] with type error
getWarnings()Pa11yIssue[] with type warning
getNotices()Pa11yIssue[] with type notice
getErrorsCount(), getWarningsCount(), getNoticesCount()int
getTotalIssueCount()int, all issues
getIssues(?string $code = null)Pa11yIssue[], optionally filtered by rule code
getIssueCount(?string $code)int
getGroupedIssues()array<string, Pa11yIssue[]>, keyed by rule code
getRunner()Runner name from the first issue
getErrorMessage()Message when pa11y returned an error payload

Pa11yCiResult

$result = Pa11yCi::fromUrls(['https://example.com'])->run();

$result->getUrlsCount();          // pages in the run
$result->getPassesCount();        // pages without findings
$result->getFailuresCount();      // pages with findings
$result->getTotalErrorsCount();   // errors across all pages
$result->getUrls();               // result keys
$result->getResultsOfUrl('https://example.com/');
MethodReturns
getUrlsCount()int, the total field
getPassesCount()int, the passes field
getFailuresCount()int, total minus passes
getTotalIssuesCount()int, the errors field
getTotalErrorsCount()int, sum of error issues
getTotalWarningsCount()int, sum of warning issues
getTotalNoticesCount()int, sum of notice issues
getResultsGroupedByUrl()array<string, Pa11yResult>
getResultsOfUrl(string $url)Pa11yResult
getUrls()string[], result keys
getAllErrors(), getAllWarnings(), getAllNotices(), getAllIssues()Pa11yIssue[] across pages
getConfig()The merged config that was sent
getOutputFilePath()The configured file path or null

getTotalIssuesCount() reads the errors field that pa11y-ci reports. getTotalErrorsCount() sums the error issues per page. The two match for normal runs and can differ when a page fails to load, because the failure is stored as an error entry without a code.

Issues

Pa11yIssue is an ArrayAccess wrapper around one issue:

MethodReturns
getCode()Rule code, for example WCAG2AA.Principle1...
getType()error, warning, or notice
getTypeCode()int
getMessage()Human-readable message
getContext()HTML snippet
getSelector()CSS selector
getRunner()Runner name
getRunnerExtras()array or null

JSON output

json() returns a pretty-printed JSON string. saveJson($path) writes it.

$result = Pa11y::fromUrl('https://example.com')->run();

$json = $result->json();
$result->saveJson('/tmp/example.json');

Pa11yResult, Pa11yCiResult, and Pa11yIssue implement JsonSerializable, but jsonSerialize() returns the JSON string. json_encode($result) therefore produces a quoted JSON string. Call json() when you need the document.

All result classes implement ArrayAccess. Read raw fields directly:

$result['total'];
$result['results'];

Exceptions

ExceptionWhen
Symfony\Component\Process\Exception\ProcessFailedExceptionThe CLI exits non-zero. The exception holds stdout, stderr, and the command.
JkOster\Pa11y\Exceptions\CouldNotReadOutputJsonThe CLI output is empty or is not a JSON array, for example on a Chrome launch failure.

Both are thrown from run(). Catch ProcessFailedException to show the command and its error output, and CouldNotReadOutputJson to show the first 100 characters of the output.

Default config

Pa11y reads pa11y.config.json from the package root. The process runs with the package root as its working directory. The file in this repository contains:

{
    "chromeLaunchConfig": {
        "args": [
            "--no-sandbox"
        ]
    },
    "timeout": 10000,
    "viewport": {
        "width": 320,
        "height": 480
    },
    "includeWarnings": true,
    "includeNotices": true
}

Pa11yCi does not read that file. It uses DEFAULT_CONFIG inside Pa11yCi, which enables --no-sandbox, headless Chrome, a 1280 by 1024 viewport, warnings, and notices. Override any value with the methods above or with config().

The CLI tools live on PATH. The package also looks in node_modules/bin next to the package, /usr/local/bin, and /opt/homebrew/bin.