From ae1a606cd8c462b7ec89511e202296ceb4a5c254 Mon Sep 17 00:00:00 2001 From: Merlin Date: Sat, 16 Mar 2024 14:59:38 +0100 Subject: [PATCH] Add CodeExporter, fixes #30 --- src/Code.php | 29 +++++++++++++++++++ src/CodeInterface.php | 13 +++++++++ src/Internal/GenericExporter.php | 9 ++++++ src/Internal/ObjectExporter/CodeExporter.php | 30 ++++++++++++++++++++ src/VarExporter.php | 5 ++++ 5 files changed, 86 insertions(+) create mode 100644 src/Code.php create mode 100644 src/CodeInterface.php create mode 100644 src/Internal/ObjectExporter/CodeExporter.php diff --git a/src/Code.php b/src/Code.php new file mode 100644 index 0000000..dcb7847 --- /dev/null +++ b/src/Code.php @@ -0,0 +1,29 @@ +lines = $lines; + } + + public static function create(string ...$lines): self { + return new self($lines); + } + + public function toLines(): array + { + return $this->lines; + } + +} diff --git a/src/CodeInterface.php b/src/CodeInterface.php new file mode 100644 index 0000000..84219e4 --- /dev/null +++ b/src/CodeInterface.php @@ -0,0 +1,13 @@ +objectExporters[] = new ObjectExporter\CodeExporter($this); $this->objectExporters[] = new ObjectExporter\StdClassExporter($this); if (! ($options & VarExporter::NO_CLOSURES)) { @@ -113,6 +121,7 @@ public function __construct(int $options, int $indentLevel = 0) $this->inlineScalarList = (bool) ($options & VarExporter::INLINE_SCALAR_LIST); $this->closureSnapshotUses = (bool) ($options & VarExporter::CLOSURE_SNAPSHOT_USES); $this->trailingCommaInArray = (bool) ($options & VarExporter::TRAILING_COMMA_IN_ARRAY); + $this->allowCode = (bool) ($options & VarExporter::ALLOW_CODE); $this->indentLevel = $indentLevel; } diff --git a/src/Internal/ObjectExporter/CodeExporter.php b/src/Internal/ObjectExporter/CodeExporter.php new file mode 100644 index 0000000..74c1ebe --- /dev/null +++ b/src/Internal/ObjectExporter/CodeExporter.php @@ -0,0 +1,30 @@ +exporter->allowCode + && $reflectionObject->implementsInterface(CodeInterface::class); + } + + public function export(object $object, \ReflectionObject $reflectionObject, array $path, array $parentIds): array + { + assert($object instanceof CodeInterface); + return $object->toLines(); + } + +} diff --git a/src/VarExporter.php b/src/VarExporter.php index 138c431..08ad03e 100644 --- a/src/VarExporter.php +++ b/src/VarExporter.php @@ -74,6 +74,11 @@ final class VarExporter */ public const INLINE_ARRAY = 1 << 11; + /** + * Any value implementing CodeInterface will print a literal expression. + */ + public const ALLOW_CODE = 1 << 12; + /** * @param mixed $var The variable to export. * @param int $options A bitmask of options. Possible values are `VarExporter::*` constants.