Python wrapper for PHP-Parser using cpg2py
Project description
php-parser-py
Python wrapper for PHP-Parser using cpg2py's graph framework.
Overview
php-parser-py provides a Python interface to PHP-Parser, enabling Abstract Syntax Tree (AST) parsing and manipulation of PHP code. The library integrates with cpg2py's graph framework for powerful graph-based code analysis.
Features
- Native PHP-Parser Integration: Delegates all parsing and code generation to PHP-Parser for maximum compatibility
- Zero-Configuration PHP: Bundled PHP binaries via static-php-py - no system PHP installation required
- Graph-Based Analysis: Uses cpg2py's graph framework for AST traversal and querying
- Dynamic Node Types: No hardcoded PHP node types - all types come from PHP-Parser's JSON output
- Lossless Round-Trip: Parse → Modify → Generate code with full fidelity
- Cross-Platform Support: Pre-built PHP 8.4 binaries for Linux (x86_64/aarch64), macOS (x86_64/arm64), and Windows (x64)
Installation
pip install php-parser-py
Note: Platform-specific wheels include pre-built PHP 8.4 binaries. No separate PHP installation required!
Quick Start
Parse PHP Code
from php_parser_py import parse
# Parse PHP code
code = """<?php
function greet($name) {
echo "Hello, $name!";
}
"""
ast = parse(code)
# Query nodes by type
for func in ast.nodes(lambda n: n.label == "Stmt_Function"):
name = func.get_property("name")
print(f"Found function: {name}")
Parse PHP File
from php_parser_py import parse_file
ast = parse_file("example.php")
Traverse AST
# Find all echo statements
for echo in ast.nodes(lambda n: n.label == "Stmt_Echo"):
print(f"Echo at line {echo.get_property('startLine')}")
# Get children of a node
for child in ast.children(some_node):
print(f"Child type: {child.label}")
# Get all descendants
for descendant in ast.descendants(some_node):
print(f"Descendant: {descendant.label}")
Generate PHP Code
from php_parser_py import parse, PrettyPrinter
# Parse code
ast = parse("<?php echo 'hello';")
# Modify AST (example: change properties)
# ... modify nodes as needed ...
# Generate code
printer = PrettyPrinter()
generated_code = printer.print(ast)
print(generated_code)
Advanced Usage
Custom PHP Binary
If you need to use a specific PHP version or custom binary:
from php_parser_py import Parser
from pathlib import Path
# Use local PHP binary
parser = Parser(php_binary_path=Path("/usr/local/bin/php"))
ast = parser.parse("<?php echo 'hello';")
# Or download from remote URL
parser = Parser(php_binary_url="https://example.com/php-8.4.zip")
ast = parser.parse("<?php echo 'hello';")
API Reference
Main Functions
parse(code: str) -> AST: Parse PHP code string and return ASTparse_file(path: str) -> AST: Parse PHP file and return AST
Classes
-
AST: Represents the complete AST as a graphnode(id): Get node by IDnodes(predicate): Iterate nodes matching predicatefirst_node(predicate): Get first matching nodechildren(node): Get child nodesdescendants(node): Get all descendantsto_json(): Reconstruct PHP-Parser JSON
-
Node: Wraps a single AST nodeid: Node identifierlabel: Node type (e.g., "Stmt_Function")properties: All node propertiesget_property(*names): Get property value
-
Parser: Parses PHP code__init__(php_binary_path=None, php_binary_url=None): Initialize parserphp_binary_path: Optional path to local PHP binaryphp_binary_url: Optional URL to download PHP binary from
parse(code, prefix=""): Parse code stringprefix: Optional prefix for node IDs (useful for multi-file parsing)
parse_file(path, prefix=None): Parse fileprefix: Optional prefix (auto-generated from file path if not provided)
-
PrettyPrinter: Generates PHP code__init__(php_binary_path=None, php_binary_url=None): Initialize printerphp_binary_path: Optional path to local PHP binaryphp_binary_url: Optional URL to download PHP binary from
print(ast): Generate code from AST
Exceptions
ParseError: Raised when PHP-Parser reports syntax errorRunnerError: Raised when PHP execution fails
Architecture
The library follows a delegation-based architecture:
- PHP-Parser handles all parsing and code generation
- cpg2py Storage stores the AST as a graph
- Python classes provide convenient access to the graph
This design ensures:
- No need to maintain PHP node type definitions in Python
- Automatic compatibility with PHP-Parser updates
- Full access to PHP-Parser's features
Requirements
- Python >= 3.11
- cpg2py
- static-php-py (bundled PHP binaries)
License
MIT License - see LICENSE file for details.
Documentation
For detailed design documentation, see:
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file php_parser_py-0.1.1.tar.gz.
File metadata
- Download URL: php_parser_py-0.1.1.tar.gz
- Upload date:
- Size: 305.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f4d42ddf7704f8c344928dfca4c08c3a814cf600856a02e363cd4852ec13d803
|
|
| MD5 |
623c9c7869e547533ebfa3126dc73e0a
|
|
| BLAKE2b-256 |
1b08766240b5f2ad58fc466e58281b98a5e931b705652712503bb1b9bd72ed67
|
File details
Details for the file php_parser_py-0.1.1-py3-none-any.whl.
File metadata
- Download URL: php_parser_py-0.1.1-py3-none-any.whl
- Upload date:
- Size: 309.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ae418472bc816a47483f3bc0081ce9c4d43599e2de49156140dbb572135fbcce
|
|
| MD5 |
a91a060ffe9f12bf93c4f65169137bd5
|
|
| BLAKE2b-256 |
dc7f612dc2ea6a445a05ef42b0c1107e41585389c0911363d219c4247a8bd2bd
|