Search by

jimbo2150 / css-indexed-dom

jimbo2150

Fast, indexed CSS selector queries over PHP's native Dom\HTMLDocument and Dom\DocumentFragment with Selectors Level 4 parity.

Package info

github.com/jimbo2150/css-indexed-dom

pkg:composer/jimbo2150/css-indexed-dom

Statistics

Installs: 7

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v2.0.1 2026-11-28 21:17 UTC

This package is auto-updated.

Last update: 2026-11-28 21:29:24 UTC


README

License PHP

Fast, indexed CSS selector queries over PHP 8.4+'s native Dom\HTMLDocument, Dom\DocumentFragment, and Dom\Element via a unified ParentNode + hybrid index architecture with strict Selectors Level 4 parity.

CSS selector parsing and tokenization are powered by jimbo2150/php-css-typed-om (^3.0).

Why Use css-indexed-dom?

  • Indexed everywhere via ParentNode & IndexedElement: IndexedHtmlDocument, IndexedDocumentFragment, and IndexedElement all implement ParentNode. Calling querySelector() or querySelectorAll() on the document, a fragment, or any returned element runs against the index automatically — never silently falling back to unindexed ext-dom scans.
  • $O(1)$ class, tag, and ID lookups: Simple selectors (.card, section.featured, #hero, :is(.a, .b), :where(.a, .b)) and getElementById() resolve directly from in-memory hash buckets instead of scanning the DOM tree linearly (including Dom\HTMLDocument::getElementById(), which is $O(N)$ in PHP ext-dom).
  • Full Selectors Level 4 accuracy: Complex selectors (:has(), :is(), :where(), multi-argument :not(), :nth-child(... of ...), [attr="val" i], SVG case-sensitivity, quirks mode, Tailwind CSS escapes) narrow to a small candidate subset via the index and verify against Lexbor via $el->matches().
  • $O(1)$ scoped descendant queries: Call $element->querySelectorAll(...) directly on any IndexedElement (or pass $scope to $doc->querySelectorAll($sel, $scope)) to restrict results to strict descendants while preserving full document ancestor context via Euler-tour intervals.
  • Standalone & spliced HTML fragments: IndexedDocumentFragment wraps Dom\DocumentFragment with the full ParentNode API; splicing fragments or moving elements between fragments and documents updates both source and target indexes incrementally in $O(\text{subtree})$.
  • Transparent auto-synced mutations: classList (IndexedTokenList), className, id, innerHTML, outerHTML, textContent, append(), prepend(), replaceChildren(), before(), after(), replaceWith(), remove(), insertAdjacentElement(), insertAdjacentHTML(), and attribute methods all keep the index synchronized without rebuilds.
  • Honest trade-off: Eager indexing takes a small upfront pass on construction (~0.1 ms for 300 elements up to ~1.4 ms for 4,700 elements), which pays off whenever you run repeated queries, #id/.class/:is() lookups, scoped element queries, or incremental edits. Pass lazyIndex: true when you only want indexing triggered on demand.

Requirements & Installation

  • PHP 8.4+ (tested on PHP 8.4 & 8.5)
  • ext-dom
  • jimbo2150/php-css-typed-om: ^3.0
composer require jimbo2150/css-indexed-dom

Quick Start

1. Basic, Complex, and Element-Scoped Queries

<?php

declare(strict_types=1);

use Jimbo2150\CssIndexedDom\IndexedHtmlDocument;
use Jimbo2150\CssIndexedDom\ParentNode;

// Eagerly indexed by default on construction
$doc = IndexedHtmlDocument::createFromString(<<<'HTML'
<!DOCTYPE html>
<html>
<body>
    <main id="app">
        <section class="card featured">
            <img src="hero.png" alt="Hero">
            <span class="badge">New</span>
        </section>
        <section class="card">
            <span class="badge">Standard</span>
        </section>
    </main>
</body>
</html>
HTML);

// Tier 1: pure index lookup + C-level bucket intersection (including :is() / :where())
$cards = $doc->querySelectorAll('section.card.featured'); // NodeList<IndexedElement>
$highlights = $doc->querySelectorAll(':is(.featured, .badge)');
echo $cards->length; // 1

// Tier 2: narrows candidates via index (.card / section), then verifies Selectors L4 via Lexbor
$withImages = $doc->querySelectorAll('main > section.card:has(img)');

// Queries on returned IndexedElement instances are automatically indexed via ParentNode
$app = $doc->getElementById('app'); // O(1) indexed lookup -> ?IndexedElement
$badges = $app?->querySelectorAll('main > section.card .badge');

// NodeList works just like native Dom\NodeList (Countable, foreach, item(), $length, ArrayAccess)
foreach ($badges ?? [] as $badge) {
    echo $badge->textContent;
}

// Polymorphic ParentNode helpers work identically across Document, Fragment, and Element
function findBadges(ParentNode $root): int
{
    return $root->querySelectorAll('.badge')->length;
}

2. Lazy Indexing (lazyIndex: true)

Indexing runs eagerly by default ($lazyIndex = false). Pass lazyIndex: true to defer index construction until the first query that needs it:

$doc = IndexedHtmlDocument::createFromString($html, lazyIndex: true);

// Single #id querySelector() / getElementById() delegates directly without building the index
$app = $doc->querySelector('#app'); // $doc->isDirty() === true

// First class, tag, :is(), or complex query builds the index lazily
$cards = $doc->querySelectorAll('.card'); // $doc->isDirty() === false

3. Standalone & DOM-Inserted Fragments (IndexedDocumentFragment)

use Jimbo2150\CssIndexedDom\IndexedDocumentFragment;

$frag = IndexedDocumentFragment::createFromString(
    '<tr class="row"><td>Alpha</td></tr><tr class="row active"><td>Beta</td></tr>',
    contextTag: 'tbody',
);

$active = $frag->querySelector('tr.row.active');

// Splicing an IndexedDocumentFragment (or raw Dom\DocumentFragment) into a document or element
// transfers all children, indexes them incrementally in O(K), and invalidates the emptied fragment:
$app?->append($frag);

4. Auto-Synced Mutations vs External Raw DOM Edits

$firstCard = $cards->item(0);
if ($firstCard !== null) {
    // O(1) class & attribute updates directly on IndexedElement (no manual sync needed)
    $firstCard->classList->add('highlighted');
    $firstCard->id = 'lead-card';

    // O(subtree) structural insertions, replacements, and innerHTML/outerHTML updates
    $newBadge = $doc->createFragment('<span class="badge">Updated</span>');
    $firstCard->append($newBadge);
    $firstCard->querySelector('.badge')?->remove();
}

// If you mutate $doc->document() or $el->element() directly outside the wrapper, call invalidate() or rebuild():
$doc->document()->body?->append($doc->document()->createElement('hr'));
$doc->invalidate(); // Frees index; next indexed query rebuilds lazily

Wrapper notes:

  • Wrapper identity (===) is guaranteed per engine via WeakMap. After transferring an IndexedElement between a fragment and a document, use $a->isSameNode($b) to compare underlying DOM node identity across wrappers.
  • ParentNode::$children returns a static NodeList snapshot of direct element children. IndexedHtmlDocument::$body is a read-only property hook (use $doc->body?->replaceWith(...) to replace).

How It Works (3-Tier Hybrid Engine)

Tier Description Examples Execution Strategy
Tier 1 (PURE_INDEX) Compound selector or :is() / :where() branches with only tag, .class, and/or #id .card, div.card.active, #hero, .bg-red-500\/50, :is(.a, .b), :where(.a, p) Pure DomIndex bucket lookup + C-level array_intersect_key() (union + preorder sort for lists). Zero DOM scan.
Tier 2 (HYBRID_SUBJECT) Complex, attributed, pseudo, or anchored/complex :is() / :where() whose subjects have a tag, .class, or #id main > section.card:has(img), article.card :is(h2.title, span.badge), li.item:not(.disabled) Intersect subject buckets in $O(1)$, then verify small candidate sets ($\le \min(256, \max(4, 2%))$) via $el->matches().
Tier 3 (NATIVE_FALLBACK) Unindexable subjects, namespaces, :scope, invalid syntax, or error cases (pseudo-elements) *[data-x], :is(.a, [data-x]), svg|rect, .123, .btn::before (throws DOMException), .btn:before (throws DOMException) Direct delegation to native querySelectorAll() / querySelector(). Pseudo-elements do not exist in the DOM and throw DOMException in native Lexbor; Tier 3 preserves exact exception parity.

API Overview

Type Key Methods & Properties
ParentNode $firstElementChild, $lastElementChild, $childElementCount, $children (snapshot), querySelector(), querySelectorAll(), append(), prepend(), replaceChildren()
IndexedHtmlDocument Implements ParentNode; createFromString(), createFromFile(), createEmpty(), fromDocument(), createElement(), createElementNS(), wrap(), createFragment(), getElementById(), appendChild(), insertBefore(), replaceChild(), removeChild(), $documentElement, $body, $head, invalidate(), rebuild(), isDirty(), indexStats(), document(), saveHtml()
IndexedDocumentFragment Implements ParentNode; createFromString(), fromFragment(), wrap(), appendChild(), insertBefore(), replaceChild(), removeChild(), invalidate(), rebuild(), isDirty(), indexStats(), fragment(), document(), saveHtml()
IndexedElement Implements ParentNode; synced properties ($className, $id, $classList, $innerHTML, $outerHTML, $textContent, $substitutedNodeValue), element navigation ($parentElement, $firstElementChild, $lastElementChild, $previousElementSibling, $nextElementSibling), addClass(), removeClass(), toggleClass(), replaceClass(), setAttribute*(), removeAttribute*(), toggleAttribute(), before(), after(), replaceWith(), remove(), appendChild(), insertBefore(), replaceChild(), removeChild(), insertAdjacentElement(), insertAdjacentHTML(), matches(), closest(), cloneNode(), contains(), isSameNode(), isEqualNode(), compareDocumentPosition(), element()
IndexedTokenList $length, $value, item(), contains(), add(), remove(), toggle(), replace(), supports(), count(), getIterator()
NodeList public readonly int $length, item(int $index): ?IndexedElement, count(), getIterator(), read-only $list[$i], toArray(), fromNative()
IndexStats elementCount, classCount, tagCount, idCount, dirty, quirksMode, rebuildCount

Benchmarks

Measured on PHP 8.5.13 (opcache.enable_cli=1, XDEBUG_MODE=off) across 6 realistic modern media-rich website DOMs (300 to 4,700 elements, ~38% media elements such as <picture>, <source>, <img>, <video>, <svg>), with 100% element-path parity verified against bare Dom\HTMLDocument across all 50 queries before timing.

Methodology note: Selector planning uses SelectorPlanner::shared() across queries, DomIndex caches packed single-bucket element arrays on an unmodified DOM, and NodeList lazily wraps IndexedElement instances on access (item() / iteration / toArray()).

Warm Query Speed (Pre-Parsed DOM, ms per Batch)

DOM Size 1 Simple .class (Bare → Indexed) 10 Mixed L4 Queries (Bare → Indexed) 50 Mixed L4 Queries (Bare → Indexed)
300 nodes 0.004 ms → 0.000 ms (9.61x) 0.046 ms → 0.039 ms (1.17x) 0.225 ms → 0.194 ms (1.16x)
600 nodes 0.006 ms → 0.000 ms (17.99x) 0.085 ms → 0.065 ms (1.30x) 0.399 ms → 0.308 ms (1.29x)
1,200 nodes 0.013 ms → 0.000 ms (34.74x) 0.159 ms → 0.112 ms (1.42x) 0.748 ms → 0.527 ms (1.42x)
2,500 nodes 0.028 ms → 0.000 ms (70.43x) 0.321 ms → 0.216 ms (1.49x) 1.499 ms → 1.007 ms (1.49x)
3,300 nodes 0.037 ms → 0.000 ms (93.26x) 0.420 ms → 0.276 ms (1.52x) 1.952 ms → 1.290 ms (1.51x)
4,700 nodes 0.055 ms → 0.000 ms (134.22x) 0.607 ms → 0.394 ms (1.54x) 2.936 ms → 1.897 ms (1.55x)

Cold Parse + Index Build + 50 Mixed Queries (End-to-End, ms per Run)

DOM Size Bare Dom\HTMLDocument IndexedHtmlDocument (Cold) Ratio
300 nodes 0.327 ms 0.403 ms 0.81x
600 nodes 0.588 ms 0.681 ms 0.86x
1,200 nodes 1.084 ms 1.225 ms 0.88x
2,500 nodes 2.176 ms 2.417 ms 0.90x
3,300 nodes 2.831 ms 3.156 ms 0.90x
4,700 nodes 4.195 ms 4.758 ms 0.88x

Why: Cold runs include a one-time $O(N)$ upfront index walk (~0.1 ms at 300 nodes to ~1.4 ms at 4,700 nodes), so repeated warm queries (especially .class, #id, :is(), and selective :has()/:not() lookups) are where indexing pays back immediately.

Incremental Mutations vs Full Rebuild (4,700-Node DOM, 200x Fragment Append + Query)

Workload Full Rebuild (invalidate()) $O(\text{subtree})$ Incremental Sync Speedup
200x fragment append + .featured query 285.97 ms 2.72 ms (0 extra rebuilds) 105.14x

Run locally via composer bench, inspect all 50 queries with php benchmarks/bench.php --list-queries, or see docs/benchmarks.md for all 7 batch sizes (1, 5, 10, 20, 30, 40, 50) and the complete 50-query catalog.

Security Boundaries

  • createFromFile($path): Delegates to PHP's Dom\HTMLDocument::createFromFile(), which honors enabled PHP stream wrappers (http://, php://, phar://, local file paths, etc.). Never pass untrusted user input directly as $path.
  • No HTML Sanitization & $contextTag: createFromString(), createFragment(), innerHTML / outerHTML, insertAdjacentHTML(), and saveHtml() preserve HTML5 input verbatim without XSS filtering. Sanitize untrusted markup at your application boundary, and restrict $contextTag in createFragment() / IndexedDocumentFragment::createFromString() to a fixed allowlist (e.g. div, tbody).
  • Untrusted HTML & CSS Selectors: Selectors exceeding 4,096 bytes bypass SelectorPlanner and run directly on native Lexbor (ext-dom); rate-limit and bound untrusted selector strings. For untrusted HTML with high-cardinality class tokens, consider lazyIndex: true when queries are conditional, and note that direct mutations to raw Dom\Attr / NamedNodeMap objects require calling $doc->invalidate().

Documentation & Development

composer check   # Runs code-style check, PHPStan (level max), and PHPUnit

License

Licensed under the Apache License, Version 2.0. See LICENSE.