Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Jsonrecast Laravel Package

boundwize/jsonrecast

JsonRecast is an editable JSON AST for PHP with visitor traversal and formatting-preserving printing. Update JSON content programmatically while keeping indentation, spacing, and key order intact, so output differs only where you made changes—ideal for composer.json and config files.

View on GitHub
Deep Wiki
Context7

Getting Started

  • Install with Composer and pin an explicit version while the package is early-stage:
    composer require boundwize/jsonrecast
    
  • Read the package docs and source tests first, specifically:
    • parser entry point
    • AST node classes
    • visitor/interfaces
    • printer/format-preserving output behavior
    • round-trip and formatting fixtures
  • Treat JsonRecast as framework-agnostic. There is likely no Laravel service provider or config file to publish; wrap it in your own small service or action class.
  • First practical Laravel use case: an Artisan command that updates a JSON manifest while preserving formatting, such as composer.json, package.json, or a tool-specific config file.
    • Parse the file.
    • Visit or locate the target node.
    • Mutate only that node.
    • Print the document.
    • Write only if the output differs from the original.
  • Do not replace Laravel request validation or normal API payload handling with this package. Use json_decode/JsonResponse for runtime JSON, and JsonRecast for developer tooling and carefully controlled file edits.

Implementation Patterns

  • Parse → transform → print → compare → write

    • Keep the original raw string.
    • Parse into the AST.
    • Apply a targeted visitor/transformation.
    • Print back to JSON.
    • Write only when the printed output differs from the original to avoid noisy diffs.
    // Illustrative shape; adapt class names to the package API.
    $original = File::get(base_path('composer.json'));
    $document = $parser->parse($original);
    
    $document->accept(new SetScript('post-install-cmd', 'php artisan migrate --force'));
    
    $updated = $printer->print($document);
    
    if ($updated !== $original) {
        // write atomically
    }
    
  • Wrap the package in a Laravel service/action

    • Keep parser/printer/visitor concerns out of commands and controllers.
    • Expose small methods such as transform(string $json, Visitor $visitor): string.
    • This makes testing and reuse across Artisan commands, queued maintenance jobs, and CI scripts easier.
  • Use visitors for repeatable transformations

    • Prefer a visitor for rules like “rename key”, “set nested value”, “remove key”, or “normalize selected values”.
    • Keep visitors narrow. A single visitor that rewrites the whole tree risks formatting loss and unclear diffs.
    • For multi-file updates, run the same visitor over a list of paths and report per-file changes.
  • Build Artisan commands with operational safety

    • Add --dry-run.
    • Print or diff the proposed output without writing.
    • Validate JSON after printing with json_decode(..., true) before replacing the file.
    • Write to a temporary file and rename into place, or use a backup, to avoid partial writes.
    • In Laravel projects, use base_path(), config_path(), or explicit paths rather than relative paths.
  • Use in CI/maintenance tooling

    • Good candidates: updating JSON manifests, normalizing selected config values, migrating fixture JSON, editing generated API schemas, and maintaining tool configuration.
    • Avoid using it on every web request. Parsing and AST traversal are overkill for normal JSON responses.
    • For many files, consider a queued job or command with progress output rather than doing work synchronously in a web request.
  • Test round-trips with fixtures

    • Store representative JSON files under tests/fixtures.
    • Assert both semantic output and formatting preservation.
    • Add tests for indentation, newline style, key order, nested edits, and no-op transforms.
    • For composer.json, follow writes with composer validate. For package.json, validate with the relevant Node tooling if available.

Gotchas and Tips

  • Formatting preservation is not the same as “any edit preserves everything”

    • Replacing an entire subtree can normalize that subtree’s layout. Test the exact node types you mutate.
    • If preserving formatting is critical, mutate leaf values or narrow nodes rather than rebuilding large sections.
  • JSON strictness matters

    • Standard JSON does not support comments or trailing commas. If the parser accepts extensions, do not assume other tools will.
    • Laravel config files, composer.json, and package.json should remain strict JSON.
  • Key order and duplicate keys

    • Decide explicitly whether order matters and how duplicate keys should be handled.
    • Add tests for both if your files are generated or edited by multiple tools.
  • Numeric precision

    • Large integers and floats can be lossy through PHP native types. Check how the AST represents numbers before editing IDs, timestamps, or monetary values.
    • Keep values as strings where precision matters.
  • Encoding and line endings

    • Watch for BOMs, CRLF vs LF, and non-ASCII content.
    • Read and write with consistent encoding. Test Windows-created files if your team uses mixed environments.
  • Avoid unnecessary writes

    • Always compare printed output to the original. A formatting-preserving printer is helpful, but a no-op write can still trigger watchers, rebuilds, or CI churn.
    • Log or report “no change” clearly in commands.
  • Atomic writes and concurrency

    • Do not write directly over a file that another process may be reading.
    • Use temp-file-plus-rename, backups, or file locks for important manifests.
    • Be especially careful with composer.json, where a bad write can break installs.
  • Visitor mutation semantics

    • Avoid mutating collections while traversing them unless the package explicitly supports it.
    • If traversal order is unclear, collect changes first and apply them in a controlled second pass.
  • Laravel config cache

    • If you edit Laravel config JSON or files that feed config, run php artisan config:clear or document the required cache refresh.
    • Do not assume a file edit is immediately reflected in a cached configuration.
  • Package maturity risk

    • Low stars, no dependents, and an early release history mean you should inspect the source and test suite before relying on it.
    • Pin the version in composer.json, wrap usage behind your own service, and keep a fallback path using json_decode/json_encode when formatting preservation is not required.
    • If you only need semantic JSON edits and do not care about diffs, native PHP JSON functions are simpler and more predictable.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route