Weave Code
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

Graphql Printer Laravel Package

lastdragon-ru/graphql-printer

GraphQL printer for PHP: turns a GraphQL AST/document into well-formatted GraphQL text with configurable indentation and style. Useful for debugging, logging, code generation, and producing consistent query/schema output in Laravel or any PHP app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require lastdragon-ru/graphql-printer
    

    Publish the config (optional):

    php artisan vendor:publish --provider="LastDragon\GraphQLPrinter\GraphQLPrinterServiceProvider"
    
  2. First Use Case Print a GraphQL schema from a string:

    use LastDragon\GraphQLPrinter\GraphQLPrinter;
    
    $schema = <<<'GRAPHQL'
    type Query {
      hello: String
    }
    GRAPHQL;
    
    $printer = new GraphQLPrinter();
    echo $printer->printSchema($schema);
    
  3. Where to Look First

    • Config File: config/graphql-printer.php (if published) for default settings.
    • Printer Class: LastDragon\GraphQLPrinter\GraphQLPrinter for core functionality.
    • Tests: tests/ for usage examples and edge cases.

Implementation Patterns

Common Workflows

  1. Printing Entire Schema

    $printer = new GraphQLPrinter();
    $schema = file_get_contents('schema.graphql');
    $formattedSchema = $printer->printSchema($schema);
    
  2. Filtering Types Print only used types in a query:

    $query = '{ hello }';
    $formatted = $printer->printSchema($schema, [
        'types' => ['used'],
    ]);
    
  3. Custom Indentation Override default indentation (e.g., 2 spaces):

    $printer->setOptions(['indent' => 2]);
    $formatted = $printer->printSchema($schema);
    
  4. Integrating with Laravel Bind the printer to the container in AppServiceProvider:

    $this->app->singleton(GraphQLPrinter::class, function ($app) {
        return new GraphQLPrinter($app['config']['graphql-printer']);
    });
    

    Use in controllers/services:

    $printer = app(GraphQLPrinter::class);
    
  5. Dynamic Schema Generation Combine with graphql/php to print dynamically generated schemas:

    use GraphQL\Type\Definition\Type;
    
    $schema = new Type\ObjectType([
        'name' => 'Query',
        'fields' => [
            'hello' => Type\Type::string(),
        ],
    ]);
    $printer->printSchema($schema->toSDL());
    

Integration Tips

  • GraphQL Playground/IDE: Use the printer to generate clean, readable schemas for documentation.
  • CI/CD: Validate schema changes by comparing printed outputs in pipelines.
  • Testing: Print schemas in tests to debug type/directive issues:
    $this->assertStringContainsString('type Query', $printer->printSchema($schema));
    

Gotchas and Tips

Pitfalls

  1. Schema Parsing Errors

    • The printer relies on valid GraphQL SDL. Invalid schemas (e.g., syntax errors) may throw exceptions.
    • Fix: Validate schemas first with a parser like graphql/php.
  2. Directives vs. Types

    • Misconfigured directives option (e.g., ['directives' => 'all']) may omit critical directives.
    • Tip: Use ['directives' => 'used'] for production schemas to avoid clutter.
  3. Performance

    • Printing large schemas (e.g., 100+ types) may impact memory. Avoid in loops or high-frequency contexts.
    • Tip: Cache printed schemas in Laravel’s cache system:
      $cacheKey = 'graphql_schema_formatted';
      $formatted = Cache::remember($cacheKey, now()->addHours(1), function () use ($printer, $schema) {
          return $printer->printSchema($schema);
      });
      
  4. Config Overrides

    • Global config in config/graphql-printer.php may conflict with runtime options.
    • Tip: Pass explicit options to printSchema() to override defaults:
      $printer->printSchema($schema, ['indent' => 4, 'types' => ['wanted' => ['User']]]);
      

Debugging

  • Log Raw Input: Compare raw vs. printed output to spot formatting issues:
    \Log::debug('Raw Schema:', [$schema]);
    \Log::debug('Printed Schema:', [$printer->printSchema($schema)]);
    
  • Validate SDL: Use graphql/php's Source class to check syntax:
    use GraphQL\Language\Parser;
    
    try {
        $parser = new Parser();
        $parser->parse($schema); // Throws on invalid SDL
    } catch (\Exception $e) {
        \Log::error('Invalid GraphQL SDL:', ['error' => $e->getMessage()]);
    }
    

Extension Points

  1. Custom Formatters Extend the printer by implementing a custom formatter:

    class CustomPrinter extends GraphQLPrinter {
        protected function formatType($type) {
            // Custom logic
            return "/* Custom */ $type";
        }
    }
    
  2. Hooks for Pre/Post-Processing Override prePrint() and postPrint() in a subclass to modify input/output:

    class ExtendedPrinter extends GraphQLPrinter {
        protected function prePrint($schema) {
            return str_replace('oldTerm', 'newTerm', $schema);
        }
    }
    
  3. Directive/Type Filters Dynamically filter types/directives at runtime:

    $options = [
        'types' => ['wanted' => collect($this->getUsedTypes($query))->pluck('name')->toArray()],
    ];
    $printer->printSchema($schema, $options);
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky