Metadata-Version: 2.3
Name: porifera
Version: 0.4.1
Summary: PORIFERA: PHP code rewriting instrumentation for expression in AST
Requires-Dist: php-parser-py==2.1.0
Requires-Dist: filelock>=3.29
Requires-Dist: typing-extensions>=4.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# porifera

[![Python](https://img.shields.io/badge/python-%3E%3D3.10-blue)](pyproject.toml)
[![License: GPL-2.0](https://img.shields.io/badge/license-GPL--2.0-blue)](LICENSE)

> **porifera** — named after Porifera, the sponge phylum.

PHP AST instrumentation for collecting runtime values at supported expression sites. Targets PHP 5.5 and later.

## Install

```bash
pip install porifera
```

Requires Python >=3.10.

## Usage

The example requires a `php` executable on `PATH`; it is the target, and its `php -l` is the [compile check](docs/design.md#deployment-callback-types) of the staged bytes.

```python
import subprocess
from collections.abc import Mapping
from pathlib import Path
from tempfile import TemporaryDirectory

from php_parser_py import Parser, PHPVersion

import porifera

VERSION = "echo PHP_MAJOR_VERSION, ' ', PHP_MINOR_VERSION;"


def php_version() -> PHPVersion:
    found = subprocess.run(
        ["php", "-r", VERSION], capture_output=True, text=True, check=True
    )
    major, minor = found.stdout.split()
    return PHPVersion(int(major), int(minor))


def compile_check(target: PHPVersion, staged: Mapping[Path, bytes]) -> Mapping[Path, str]:
    if php_version() != target:
        raise RuntimeError(f"php on PATH is not PHP {target}")
    refused = {}
    for path, content in staged.items():
        checked = subprocess.run(["php", "-l"], input=content, capture_output=True)
        if checked.returncode:
            refused[path] = (checked.stderr + checked.stdout).decode("utf-8", errors="replace")
    return refused


with TemporaryDirectory() as directory:
    source = Path(directory) / "example.php"
    source.write_text("<?php\n$price = 40 + 2;\n", encoding="utf-8")
    target = php_version()
    ast = Parser(target_php=target).parse_file(str(source))
    node = ast.first_node(lambda item: item.node_type == "Expr_BinaryOp_Plus")
    assert node is not None
    with porifera.session(
        {node.id: "price"}, ast, target_php=target, compile_check=compile_check
    ) as active:
        subprocess.run(["php", str(source)], check=True)
        print(active.collect()["price"].values)
```

See [session states and exit cleanup](docs/model.md#state-model).

## API

- `session(targets, project_ast, *, target_php, compile_check, record_tag_expression=None, ...)` enters an instrumentation session and yields a `Session`.
- `Session.collect()` returns the exact values of ticketless requests by key; `Session.collect_unassigned()` returns every record of those requests with its status and [Record Tag](docs/glossary-instrumentation.md#record-tag) as `UnassignedRecords`. Both consume the same output.
- `Session.register_attempt()`, `Session.collect(attempt)` and `Session.ack(batch)` collect ticketed requests as a `CaptureBatch` of `CaptureRecord`.
- `plan_targets()`, `recover()`, `recover_capture()` and `recorded_session()` plan targets and recover a root.
- `require_target_provenance()` checks that an AST was parsed under the session's target version; `is_declaration_site()` tells whether a node is a variable a declaration binds.

Signatures, result types and errors: [session API](docs/design.md) and [capture API](docs/design-capture.md).

Probe strategies, outcome types and deployment callbacks are specified in the
[public API](docs/design.md). [Target admission](docs/spec-target-classification.md)
selects Expression Wrap, Wrap-Assign, Statement Probe or a refusal.

## Citation

If you use this project in academic work, please cite our paper. BibTeX (placeholder until the paper is released):

```bibtex
@misc{porifera_placeholder,
  title  = {{TODO: paper title — not yet released}},
  author = {{TODO: authors}},
  year   = {{TODO}},
  note   = {Unreleased associated work.}
}
```

## Documentation

- [Concepts](docs/concept.md) — problem context, core terminology, data flow
- [Domain model](docs/model.md) — entities, root states and invariants
- [Design](docs/design.md) — class structure, session API, exception types
- [Capture design](docs/design-capture.md) — attempts, dispatch tickets, batches and recovery
- [Lifecycle and reference checks](docs/spec.md) — transaction steps and reference contexts
- [Wrap safety](docs/spec-wrap-safety.md) — expression context checks
- [Statement probes](docs/spec-statement-probe.md) — assignment capture and placement
- [Implementation](docs/impl.md) — php-parser-py API, developer notes
- [Glossary](docs/glossary.md) — the terms these documents use

## For Agents

Agent-consumable documentation index at `docs/llms.txt` (llmstxt.org format).

## License

GPL-2.0 — see [LICENSE](LICENSE).
