php-var-dump 1.0.0__py3-none-any.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.
php_var_dump/__init__.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Serialize simple Python values as PHP source code."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
from datetime import date, datetime
|
|
6
|
+
from decimal import Decimal
|
|
7
|
+
|
|
8
|
+
import six
|
|
9
|
+
|
|
10
|
+
__VERSION__ = "1.0.0"
|
|
11
|
+
|
|
12
|
+
_EPOCH = datetime(1970, 1, 1)
|
|
13
|
+
_DATETIME_FORMATS = ("timestamp", "timestamp_legacy", "string")
|
|
14
|
+
|
|
15
|
+
# PHP accepts ASCII letters, underscores, and non-ASCII bytes in identifiers.
|
|
16
|
+
_VARIABLE_NAME = re.compile(
|
|
17
|
+
r"\A(?:[A-Za-z_]|[^\x00-\x7f])(?:[A-Za-z_0-9]|[^\x00-\x7f])*\Z"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _php_string(value):
|
|
22
|
+
# type: (object) -> str
|
|
23
|
+
"""Quote a value as a PHP string, preserving Python 2 text types."""
|
|
24
|
+
if not isinstance(value, six.string_types):
|
|
25
|
+
value = str(value)
|
|
26
|
+
return "'%s'" % value.replace("\\", "\\\\").replace("'", "\\'")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _php_datetime(value, datetime_format):
|
|
30
|
+
# type: (datetime, str) -> str
|
|
31
|
+
"""Render an ISO 8601 literal or a PHP DateTimeImmutable expression."""
|
|
32
|
+
if datetime_format == "string":
|
|
33
|
+
return _php_string(value.isoformat())
|
|
34
|
+
|
|
35
|
+
offset = value.utcoffset()
|
|
36
|
+
if offset is None:
|
|
37
|
+
raise ValueError("Timestamp encoding requires a timezone-aware datetime")
|
|
38
|
+
|
|
39
|
+
delta = value.replace(tzinfo=None) - _EPOCH - offset
|
|
40
|
+
seconds = delta.days * 86400 + delta.seconds
|
|
41
|
+
if datetime_format == "timestamp_legacy":
|
|
42
|
+
total_microseconds = seconds * 1000000 + delta.microseconds
|
|
43
|
+
whole, fraction = divmod(abs(total_microseconds), 1000000)
|
|
44
|
+
timestamp = ("-" if total_microseconds < 0 else "") + str(whole)
|
|
45
|
+
if fraction:
|
|
46
|
+
timestamp += ".%06d" % fraction
|
|
47
|
+
return "new \\DateTimeImmutable(%s)" % _php_string("@" + timestamp)
|
|
48
|
+
|
|
49
|
+
expression = "\\DateTimeImmutable::createFromTimestamp(%d)" % seconds
|
|
50
|
+
if delta.microseconds:
|
|
51
|
+
expression += "->modify('+%d microseconds')" % delta.microseconds
|
|
52
|
+
return expression
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _php_var_dump(data, depth=0, ancestors=None, datetime_format="timestamp"):
|
|
56
|
+
# type: (object, int, set[int] | None, str) -> str
|
|
57
|
+
"""Render a literal with indentation and reject recursive containers."""
|
|
58
|
+
padding = " " * depth
|
|
59
|
+
if isinstance(data, (dict, list, tuple)):
|
|
60
|
+
if ancestors is None:
|
|
61
|
+
ancestors = set()
|
|
62
|
+
identity = id(data)
|
|
63
|
+
if identity in ancestors:
|
|
64
|
+
raise ValueError("Cannot serialize a recursive container")
|
|
65
|
+
ancestors.add(identity)
|
|
66
|
+
try:
|
|
67
|
+
if isinstance(data, dict):
|
|
68
|
+
keypadding = padding + " "
|
|
69
|
+
items = [
|
|
70
|
+
"%s%s => %s"
|
|
71
|
+
% (
|
|
72
|
+
keypadding,
|
|
73
|
+
_php_string(key),
|
|
74
|
+
_php_var_dump(value, depth + 1, ancestors, datetime_format),
|
|
75
|
+
)
|
|
76
|
+
for key, value in data.items()
|
|
77
|
+
]
|
|
78
|
+
else:
|
|
79
|
+
items = [
|
|
80
|
+
_php_var_dump(value, depth + 1, ancestors, datetime_format)
|
|
81
|
+
for value in data
|
|
82
|
+
]
|
|
83
|
+
finally:
|
|
84
|
+
ancestors.remove(identity)
|
|
85
|
+
return "%sArray(\n%s\n%s)" % (padding, ",\n".join(items), padding)
|
|
86
|
+
if isinstance(data, six.string_types):
|
|
87
|
+
return padding + _php_string(data)
|
|
88
|
+
if isinstance(data, bool):
|
|
89
|
+
return padding + ("true" if data else "false")
|
|
90
|
+
if isinstance(data, six.integer_types):
|
|
91
|
+
return padding + ("%d" % data)
|
|
92
|
+
if data is None:
|
|
93
|
+
return padding + "null"
|
|
94
|
+
if isinstance(data, datetime):
|
|
95
|
+
return padding + _php_datetime(data, datetime_format)
|
|
96
|
+
if isinstance(data, date):
|
|
97
|
+
return padding + _php_string(data.isoformat())
|
|
98
|
+
if isinstance(data, Decimal):
|
|
99
|
+
return padding + _php_string(str(data))
|
|
100
|
+
if isinstance(data, float):
|
|
101
|
+
if math.isnan(data):
|
|
102
|
+
return padding + "NAN"
|
|
103
|
+
if math.isinf(data):
|
|
104
|
+
return padding + ("-INF" if data < 0 else "INF")
|
|
105
|
+
return padding + repr(float(data))
|
|
106
|
+
raise ValueError("Unsupported data type (%s)" % type(data))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def php_var_dump(name, data, datetime_format="timestamp"):
|
|
110
|
+
# type: (str, object, str) -> str
|
|
111
|
+
"""Render a PHP assignment using the selected format for datetime values.
|
|
112
|
+
|
|
113
|
+
Dates and decimals become strings. PHP can coerce quoted integer-like
|
|
114
|
+
dictionary keys to integers. Store identifiers as values when their string
|
|
115
|
+
type must survive.
|
|
116
|
+
"""
|
|
117
|
+
if (
|
|
118
|
+
not isinstance(name, six.string_types)
|
|
119
|
+
or not _VARIABLE_NAME.match(name)
|
|
120
|
+
or name in ("this", "GLOBALS")
|
|
121
|
+
):
|
|
122
|
+
raise ValueError("Invalid PHP variable name")
|
|
123
|
+
if datetime_format not in _DATETIME_FORMATS:
|
|
124
|
+
raise ValueError(
|
|
125
|
+
"Invalid datetime_format. Use timestamp, timestamp_legacy, or string."
|
|
126
|
+
)
|
|
127
|
+
depth = 1 if isinstance(data, dict) else 0
|
|
128
|
+
return "$%s = %s;" % (
|
|
129
|
+
name,
|
|
130
|
+
_php_var_dump(data, depth=depth, datetime_format=datetime_format),
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def php_as_block(stringed_var):
|
|
135
|
+
# type: (str) -> str
|
|
136
|
+
"""Wrap PHP source in opening and closing tags."""
|
|
137
|
+
return "<?php\n\n%s\n\n?>" % stringed_var
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: php_var_dump
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A port of the var_dump function of PHP to Python. This lets you make PHP files with Python.
|
|
5
|
+
Home-page: https://github.com/jvanasco/php_var_dump
|
|
6
|
+
Author: Jonathan Vanasco
|
|
7
|
+
Author-email: jvanasco@2xlp.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Programming Language :: PHP
|
|
10
|
+
Classifier: Programming Language :: Python
|
|
11
|
+
Classifier: Programming Language :: Python :: 2
|
|
12
|
+
Classifier: Programming Language :: Python :: 2.7
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.5
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
25
|
+
Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
Requires-Dist: six
|
|
28
|
+
Provides-Extra: testing
|
|
29
|
+
Requires-Dist: pytest; extra == "testing"
|
|
30
|
+
Requires-Dist: coverage; extra == "testing"
|
|
31
|
+
|
|
32
|
+
# php_var_dump
|
|
33
|
+
|
|
34
|
+

|
|
35
|
+
|
|
36
|
+
`php_var_dump` converts Python values into PHP source code you can write to an
|
|
37
|
+
include file. It was originally built to turn state-specific voting data from
|
|
38
|
+
CSV files into PHP includes for voter registration websites and widgets.
|
|
39
|
+
The Python ingestion tool prepares the data ahead of deployment, and
|
|
40
|
+
PHP loads the generated file without having to parse the original CSV or
|
|
41
|
+
decode a serialized payload on each request.
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from php_var_dump import php_as_block, php_var_dump
|
|
47
|
+
|
|
48
|
+
assignment = php_var_dump("message", "Hello World")
|
|
49
|
+
with open("data.php", "wb") as output:
|
|
50
|
+
output.write(php_as_block(assignment).encode("utf-8"))
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The generated `data.php` contains:
|
|
54
|
+
|
|
55
|
+
```php
|
|
56
|
+
<?php
|
|
57
|
+
|
|
58
|
+
$message = 'Hello World';
|
|
59
|
+
|
|
60
|
+
?>
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Include the generated file in your PHP program:
|
|
64
|
+
|
|
65
|
+
```php
|
|
66
|
+
<?php
|
|
67
|
+
|
|
68
|
+
require __DIR__ . '/data.php';
|
|
69
|
+
echo $message;
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`php_as_block()` wraps raw PHP source in PHP tags. Serialize data with
|
|
73
|
+
`php_var_dump()` before passing the resulting assignment to `php_as_block()`.
|
|
74
|
+
|
|
75
|
+
### Datetime values
|
|
76
|
+
|
|
77
|
+
Pass `datetime_format` to `php_var_dump()` to select how it encodes every
|
|
78
|
+
Python `datetime` in the assignment, including values nested in containers.
|
|
79
|
+
|
|
80
|
+
| Format | PHP output |
|
|
81
|
+
| --- | --- |
|
|
82
|
+
| `"timestamp"` (default) | A `DateTimeImmutable` created with `createFromTimestamp()`. Requires PHP 8.4 or later. |
|
|
83
|
+
| `"timestamp_legacy"` | A `DateTimeImmutable` created with an `@timestamp` string. Use this for PHP 8.3 and earlier. |
|
|
84
|
+
| `"string"` | A quoted ISO 8601 string with the original UTC offset when present. |
|
|
85
|
+
|
|
86
|
+
Both timestamp modes require a timezone-aware datetime and preserve the instant
|
|
87
|
+
and microseconds in UTC. The string mode also accepts naive datetimes, whose
|
|
88
|
+
output has no UTC offset.
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from datetime import datetime, timezone
|
|
92
|
+
from php_var_dump import php_var_dump
|
|
93
|
+
|
|
94
|
+
value = datetime(2026, 11, 16, 12, 0, tzinfo=timezone.utc)
|
|
95
|
+
php_var_dump("value", value)
|
|
96
|
+
php_var_dump("value", value, datetime_format="timestamp_legacy")
|
|
97
|
+
php_var_dump("value", value, datetime_format="string")
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Calendar dates and exact decimals
|
|
101
|
+
|
|
102
|
+
`datetime.date` values become `YYYY-MM-DD` strings in every datetime mode.
|
|
103
|
+
`decimal.Decimal` values become strings using Python's decimal representation,
|
|
104
|
+
which preserves precision, trailing zeros, and exponent notation when present.
|
|
105
|
+
For example, `Decimal("12.3400")` produces the PHP string `'12.3400'`.
|
|
106
|
+
Non-finite decimals also become strings, such as `'Infinity'` and `'NaN'`.
|
|
107
|
+
|
|
108
|
+
## PHP value boundaries
|
|
109
|
+
|
|
110
|
+
**Array keys.** PHP can convert a quoted integer key such as `'12345'` to
|
|
111
|
+
the integer `12345`. Leading-zero keys such as `'01234'` and ZIP+4 or precinct
|
|
112
|
+
keys such as `'12345-6789'` and `'42-07'` stay strings. If every identifier
|
|
113
|
+
must remain a string, store it as a record value. If it must be a key, use a
|
|
114
|
+
consistent nonnumeric prefix. [PHP array key rules](https://www.php.net/manual/en/language.types.array.php)
|
|
115
|
+
|
|
116
|
+
PHP may represent integers outside its integer range as floats, which can
|
|
117
|
+
lose precision.
|
|
118
|
+
|
|
119
|
+
## Changelog
|
|
120
|
+
|
|
121
|
+
### v1.0.0
|
|
122
|
+
|
|
123
|
+
* Build with setuptools through `pyproject.toml` and keep package metadata and
|
|
124
|
+
tox settings in `setup.cfg`.
|
|
125
|
+
* Install `six` in isolated Python 2 builds so setuptools can read the version.
|
|
126
|
+
* Align the tox and GitHub Actions matrices through Python 3.15 and generate
|
|
127
|
+
HTML coverage reports.
|
|
128
|
+
* Escape strings and dictionary keys, validate assignment names, emit PHP
|
|
129
|
+
boolean and non-finite float literals, and reject recursive containers.
|
|
130
|
+
* Add optional PHP CLI round-trip tests for nested values and numeric boundaries.
|
|
131
|
+
* Encode datetimes as PHP 8.4+ timestamps by default, with legacy timestamp and
|
|
132
|
+
ISO 8601 string options. Run PHP round-trip tests in the Python 3.14 CI job.
|
|
133
|
+
* Encode calendar dates and decimals as strings and document PHP array key
|
|
134
|
+
coercion for identifiers.
|
|
135
|
+
* MIT License
|
|
136
|
+
|
|
137
|
+
### v0.3.2
|
|
138
|
+
|
|
139
|
+
* Packaging fixes.
|
|
140
|
+
|
|
141
|
+
### v0.3.1
|
|
142
|
+
|
|
143
|
+
* Packaging fixes.
|
|
144
|
+
|
|
145
|
+
### v0.3
|
|
146
|
+
|
|
147
|
+
* Upgraded Black to 20.8b1.
|
|
148
|
+
* Integrated with pre-commit.
|
|
149
|
+
* Added tox and GitHub Actions.
|
|
150
|
+
* Added Python 3 support.
|
|
151
|
+
|
|
152
|
+
### v0.2
|
|
153
|
+
|
|
154
|
+
* Added Flake8.
|
|
155
|
+
|
|
156
|
+
### v0.1
|
|
157
|
+
|
|
158
|
+
* Initial release.
|
|
159
|
+
|
|
160
|
+
## License
|
|
161
|
+
|
|
162
|
+
MIT. Copyright 2012–2026 Jonathan Vanasco.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
php_var_dump/__init__.py,sha256=7fGQquNT6HfvAq23gL1Hadi89R3tz7fzic41iDGtfQg,4975
|
|
2
|
+
php_var_dump-1.0.0.dist-info/METADATA,sha256=9FIhdgOur91ngB0zNgboDthbrn0lngpv6iuz1n-I2Sc,5505
|
|
3
|
+
php_var_dump-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
4
|
+
php_var_dump-1.0.0.dist-info/top_level.txt,sha256=lq_JRWJ8nhRVkKyFdbyfkjXuQC7qYBOP-Zcm29ejuSk,13
|
|
5
|
+
php_var_dump-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
php_var_dump
|