static-php-py 0.1.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- resources/__init__.py +5 -0
- resources/php +0 -0
- static_php_py/__init__.py +49 -0
- static_php_py/exceptions.py +63 -0
- static_php_py/models.py +42 -0
- static_php_py/php.py +226 -0
- static_php_py/providers.py +403 -0
- static_php_py-0.1.0.dist-info/METADATA +732 -0
- static_php_py-0.1.0.dist-info/RECORD +11 -0
- static_php_py-0.1.0.dist-info/WHEEL +4 -0
- static_php_py-0.1.0.dist-info/licenses/LICENSE +339 -0
resources/__init__.py
ADDED
resources/php
ADDED
|
Binary file
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Python wrapper library for static PHP binaries.
|
|
2
|
+
|
|
3
|
+
This library provides a Python interface for PHP script execution with pre-built
|
|
4
|
+
static PHP binaries distributed via platform-specific wheels.
|
|
5
|
+
|
|
6
|
+
Inspired by crazywhalecc/static-php-cli project.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from importlib.metadata import version, PackageNotFoundError
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import re
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _read_version_from_pyproject() -> str:
|
|
15
|
+
"""Read version from pyproject.toml (development fallback)."""
|
|
16
|
+
pyproject = Path(__file__).parent.parent / "pyproject.toml"
|
|
17
|
+
if pyproject.exists():
|
|
18
|
+
content = pyproject.read_text()
|
|
19
|
+
match = re.search(r'^version\s*=\s*["\']([^"\']+)["\']', content, re.MULTILINE)
|
|
20
|
+
if match:
|
|
21
|
+
return match.group(1)
|
|
22
|
+
return "0.0.0.dev"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
__version__ = version("static-php-py")
|
|
27
|
+
except PackageNotFoundError:
|
|
28
|
+
# Package not installed (e.g., during development) - read from pyproject.toml
|
|
29
|
+
__version__ = _read_version_from_pyproject()
|
|
30
|
+
|
|
31
|
+
from static_php_py.exceptions import (
|
|
32
|
+
BinaryNotFoundError,
|
|
33
|
+
DownloadError,
|
|
34
|
+
ExecutionError,
|
|
35
|
+
InvalidArchiveError,
|
|
36
|
+
PHPError,
|
|
37
|
+
)
|
|
38
|
+
from static_php_py.models import ExecutionResult
|
|
39
|
+
from static_php_py.php import PHP
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"PHPError",
|
|
43
|
+
"BinaryNotFoundError",
|
|
44
|
+
"ExecutionError",
|
|
45
|
+
"DownloadError",
|
|
46
|
+
"InvalidArchiveError",
|
|
47
|
+
"ExecutionResult",
|
|
48
|
+
"PHP",
|
|
49
|
+
]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Exception classes for static-php-py.
|
|
2
|
+
|
|
3
|
+
All exceptions inherit from PHPError base class for easy catching.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class PHPError(Exception):
|
|
8
|
+
"""Base exception for all static-php-py errors.
|
|
9
|
+
|
|
10
|
+
All library-specific exceptions inherit from this class, allowing
|
|
11
|
+
consumers to catch all library errors with a single except clause.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BinaryNotFoundError(PHPError):
|
|
16
|
+
"""PHP binary cannot be found through any resolution method.
|
|
17
|
+
|
|
18
|
+
Raised when:
|
|
19
|
+
- Explicit path does not exist or is not executable
|
|
20
|
+
- No php executable found in system PATH
|
|
21
|
+
- Package resource binary not available (basic extra not installed)
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
message: Description of where binary resolution failed.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ExecutionError(PHPError):
|
|
29
|
+
"""PHP subprocess execution failed unexpectedly.
|
|
30
|
+
|
|
31
|
+
Raised when subprocess fails to start or encounters system-level errors,
|
|
32
|
+
not for PHP script errors (which return ExecutionResult with non-zero exit code).
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
message: Description of execution failure.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class DownloadError(PHPError):
|
|
40
|
+
"""Remote download failed due to network or HTTP error.
|
|
41
|
+
|
|
42
|
+
Raised when:
|
|
43
|
+
- Network connection fails
|
|
44
|
+
- HTTP request returns error status code
|
|
45
|
+
- Download timeout exceeded
|
|
46
|
+
- URL protocol not supported (only http/https allowed)
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
message: Description of download failure including URL.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class InvalidArchiveError(PHPError):
|
|
54
|
+
"""Archive is corrupted or does not contain php executable.
|
|
55
|
+
|
|
56
|
+
Raised when:
|
|
57
|
+
- tar.gz extraction fails (corrupt archive)
|
|
58
|
+
- Extracted archive does not contain any php executable
|
|
59
|
+
- Archive format is not supported
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
message: Description of archive validation failure.
|
|
63
|
+
"""
|
static_php_py/models.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Data models for PHP execution results."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class ExecutionResult:
|
|
5
|
+
"""Represent PHP script execution outcome.
|
|
6
|
+
|
|
7
|
+
Contains execution status, exit code, and captured output streams.
|
|
8
|
+
Success is determined by zero exit code.
|
|
9
|
+
|
|
10
|
+
Attributes:
|
|
11
|
+
success: True if script completed with exit code 0.
|
|
12
|
+
return_code: Process exit code from subprocess.
|
|
13
|
+
stdout: Standard output content as string.
|
|
14
|
+
stderr: Standard error content as string.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
return_code: int,
|
|
20
|
+
stdout: str,
|
|
21
|
+
stderr: str,
|
|
22
|
+
) -> None:
|
|
23
|
+
"""Initialize execution result.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
return_code: Process exit code.
|
|
27
|
+
stdout: Standard output content.
|
|
28
|
+
stderr: Standard error content.
|
|
29
|
+
"""
|
|
30
|
+
self.return_code = return_code
|
|
31
|
+
self.stdout = stdout
|
|
32
|
+
self.stderr = stderr
|
|
33
|
+
self.success = return_code == 0
|
|
34
|
+
|
|
35
|
+
def __repr__(self) -> str:
|
|
36
|
+
"""Return string representation for debugging."""
|
|
37
|
+
status = "success" if self.success else f"failed (code {self.return_code})"
|
|
38
|
+
return (
|
|
39
|
+
f"ExecutionResult({status}, "
|
|
40
|
+
f"stdout={len(self.stdout)} chars, "
|
|
41
|
+
f"stderr={len(self.stderr)} chars)"
|
|
42
|
+
)
|
static_php_py/php.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""PHP binary wrapper for script execution."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import re
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from platformdirs import user_cache_dir
|
|
11
|
+
|
|
12
|
+
from static_php_py.exceptions import BinaryNotFoundError, ExecutionError
|
|
13
|
+
from static_php_py.models import ExecutionResult
|
|
14
|
+
from static_php_py.providers import (
|
|
15
|
+
_PathProvider,
|
|
16
|
+
_RemoteProvider,
|
|
17
|
+
_ResourceProvider,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PHP:
|
|
24
|
+
"""Represent a PHP binary and execute PHP scripts.
|
|
25
|
+
|
|
26
|
+
Wraps a PHP executable and provides methods for script execution,
|
|
27
|
+
code evaluation, and version queries.
|
|
28
|
+
|
|
29
|
+
Attributes:
|
|
30
|
+
_binary_path: Path to PHP executable.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(self, binary_path: Path) -> None:
|
|
34
|
+
"""Initialize PHP instance with binary path.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
binary_path: Path to PHP executable.
|
|
38
|
+
"""
|
|
39
|
+
self._binary_path = binary_path
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def builtin() -> PHP:
|
|
43
|
+
"""Load built-in PHP binary from package resources.
|
|
44
|
+
|
|
45
|
+
Uses the PHP binary bundled in platform-specific wheels.
|
|
46
|
+
The binary is automatically extracted on first use.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
PHP instance wrapping the built-in binary.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
BinaryNotFoundError: If built-in binary not found (not installed
|
|
53
|
+
via platform-specific wheel).
|
|
54
|
+
"""
|
|
55
|
+
provider = _ResourceProvider()
|
|
56
|
+
binary_path = provider.resolve()
|
|
57
|
+
return PHP(binary_path)
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def local(path: Path | str) -> PHP:
|
|
61
|
+
"""Load PHP binary from local file system path.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
path: Path to PHP binary (required, cannot be None).
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
PHP instance wrapping the local binary.
|
|
68
|
+
|
|
69
|
+
Raises:
|
|
70
|
+
BinaryNotFoundError: If binary not found at specified path.
|
|
71
|
+
"""
|
|
72
|
+
if path is None:
|
|
73
|
+
raise BinaryNotFoundError("Path argument is required for local()")
|
|
74
|
+
|
|
75
|
+
provider = _PathProvider(path)
|
|
76
|
+
binary_path = provider.resolve()
|
|
77
|
+
return PHP(binary_path)
|
|
78
|
+
|
|
79
|
+
@staticmethod
|
|
80
|
+
def remote(url: str, force: bool = False, timeout: float = 300.0) -> PHP:
|
|
81
|
+
"""Download PHP binary from remote URL and return PHP instance.
|
|
82
|
+
|
|
83
|
+
Downloads PHP binary or archive (tar.gz, tgz, or zip) from remote URL,
|
|
84
|
+
extracts if needed, sets execute permission, caches locally, and returns
|
|
85
|
+
a PHP instance.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
url: Remote URL to PHP binary or archive (tar.gz, tgz, or zip).
|
|
89
|
+
force: Force re-download ignoring cache (default: False).
|
|
90
|
+
timeout: Download timeout in seconds (default: 300.0).
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
PHP instance wrapping the downloaded binary.
|
|
94
|
+
|
|
95
|
+
Raises:
|
|
96
|
+
DownloadError: If network/HTTP error occurs.
|
|
97
|
+
InvalidArchiveError: If archive format invalid or no php executable found.
|
|
98
|
+
"""
|
|
99
|
+
provider = _RemoteProvider(url, force=force, timeout=timeout)
|
|
100
|
+
binary_path = provider.resolve()
|
|
101
|
+
return PHP(binary_path)
|
|
102
|
+
|
|
103
|
+
def run(
|
|
104
|
+
self,
|
|
105
|
+
script: Path | str,
|
|
106
|
+
args: list[str] | None = None,
|
|
107
|
+
timeout: float | None = None,
|
|
108
|
+
) -> ExecutionResult:
|
|
109
|
+
"""Execute PHP script file.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
script: Path to PHP script file.
|
|
113
|
+
args: Optional arguments passed to script.
|
|
114
|
+
timeout: Optional timeout in seconds.
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
ExecutionResult with execution outcome.
|
|
118
|
+
|
|
119
|
+
Raises:
|
|
120
|
+
FileNotFoundError: If script file does not exist.
|
|
121
|
+
ExecutionError: If subprocess execution fails unexpectedly.
|
|
122
|
+
"""
|
|
123
|
+
script_path = Path(script)
|
|
124
|
+
if not script_path.exists():
|
|
125
|
+
raise FileNotFoundError(f"PHP script not found: {script_path}")
|
|
126
|
+
|
|
127
|
+
cmd = [str(self._binary_path), str(script_path)]
|
|
128
|
+
if args:
|
|
129
|
+
cmd.extend(args)
|
|
130
|
+
|
|
131
|
+
return self._execute(cmd, timeout)
|
|
132
|
+
|
|
133
|
+
def eval(self, code: str, timeout: float | None = None) -> ExecutionResult:
|
|
134
|
+
"""Execute PHP code string via php -r.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
code: PHP code to execute.
|
|
138
|
+
timeout: Optional timeout in seconds.
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
ExecutionResult with execution outcome.
|
|
142
|
+
|
|
143
|
+
Raises:
|
|
144
|
+
ExecutionError: If subprocess execution fails unexpectedly.
|
|
145
|
+
"""
|
|
146
|
+
cmd = [str(self._binary_path), "-r", code]
|
|
147
|
+
return self._execute(cmd, timeout)
|
|
148
|
+
|
|
149
|
+
def version(self) -> str:
|
|
150
|
+
"""Get PHP version string.
|
|
151
|
+
|
|
152
|
+
Supports both standard PHP and static-php-cli version formats:
|
|
153
|
+
- Standard PHP: "PHP 8.3.0 (cli) ..."
|
|
154
|
+
- static-php-cli: "static-php-cli 2.7.10"
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
Version string (e.g., "8.3.0" or "2.7.10").
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
ExecutionError: If version query fails.
|
|
161
|
+
"""
|
|
162
|
+
result = self._execute([str(self._binary_path), "--version"], timeout=5.0)
|
|
163
|
+
if not result.success:
|
|
164
|
+
logger.error("Failed to get PHP version: %s", result.stderr)
|
|
165
|
+
raise ExecutionError(f"Failed to get PHP version: {result.stderr}")
|
|
166
|
+
|
|
167
|
+
# Try standard PHP format first: "PHP 8.3.0"
|
|
168
|
+
match = re.search(r"PHP\s+(\d+\.\d+\.\d+)", result.stdout, re.IGNORECASE)
|
|
169
|
+
if match:
|
|
170
|
+
return match.group(1)
|
|
171
|
+
|
|
172
|
+
# Try static-php-cli format: "static-php-cli 2.7.10"
|
|
173
|
+
match = re.search(r"static-php-cli\s+(\d+\.\d+\.\d+)", result.stdout, re.IGNORECASE)
|
|
174
|
+
if match:
|
|
175
|
+
return f"static-php-cli {match.group(1)}"
|
|
176
|
+
|
|
177
|
+
logger.error("Cannot parse version from output: %s", result.stdout)
|
|
178
|
+
raise ExecutionError(f"Cannot parse version from: {result.stdout}")
|
|
179
|
+
|
|
180
|
+
def path(self) -> Path:
|
|
181
|
+
"""Get PHP binary path.
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
Path to PHP executable.
|
|
185
|
+
"""
|
|
186
|
+
return self._binary_path
|
|
187
|
+
|
|
188
|
+
@staticmethod
|
|
189
|
+
def cache_dir() -> Path:
|
|
190
|
+
"""Get cache directory path where binaries are stored.
|
|
191
|
+
|
|
192
|
+
Returns the platform-specific user cache directory where PHP binaries
|
|
193
|
+
from package resources or remote downloads are cached. This directory
|
|
194
|
+
is persistent and typically not cleaned by system cleanup tools.
|
|
195
|
+
|
|
196
|
+
Platform-specific locations:
|
|
197
|
+
- Linux: ~/.cache/static-php-py/
|
|
198
|
+
- macOS: ~/Library/Caches/static-php-py/
|
|
199
|
+
- Windows: C:\\Users\\<user>\\AppData\\Local\\static-php-py\\
|
|
200
|
+
|
|
201
|
+
Returns:
|
|
202
|
+
Path to cache directory.
|
|
203
|
+
"""
|
|
204
|
+
return Path(user_cache_dir("static-php-py", "static-php-py"))
|
|
205
|
+
|
|
206
|
+
def _execute(self, cmd: list[str], timeout: float | None) -> ExecutionResult:
|
|
207
|
+
"""Execute subprocess and capture output."""
|
|
208
|
+
try:
|
|
209
|
+
result = subprocess.run(
|
|
210
|
+
cmd,
|
|
211
|
+
capture_output=True,
|
|
212
|
+
text=True,
|
|
213
|
+
timeout=timeout,
|
|
214
|
+
check=False,
|
|
215
|
+
)
|
|
216
|
+
return ExecutionResult(
|
|
217
|
+
return_code=result.returncode,
|
|
218
|
+
stdout=result.stdout,
|
|
219
|
+
stderr=result.stderr,
|
|
220
|
+
)
|
|
221
|
+
except subprocess.TimeoutExpired as e:
|
|
222
|
+
logger.error("PHP execution timeout after %.2f seconds", timeout or 0)
|
|
223
|
+
raise ExecutionError(f"PHP execution timeout after {timeout}s") from e
|
|
224
|
+
except OSError as e:
|
|
225
|
+
logger.exception("Failed to execute PHP binary: %s", self._binary_path)
|
|
226
|
+
raise ExecutionError(f"Failed to execute PHP binary {self._binary_path}: {e}") from e
|