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

Php Svg Laravel Package

meyfa/php-svg

Lightweight PHP library to create, read, and manipulate SVGs. Build SVG documents programmatically, edit shapes and attributes via a DOM-like API, and export clean SVG/XML. Handy for generating icons, diagrams, and server-side graphics without external dependencies.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**
   ```bash
   composer require meyfa/php-svg

Note: Ensure your project uses PHP 8.4 for full compatibility with v0.16.1.

  1. First Use Case: Basic SVG Creation

    use Meyfa\Svg\Svg;
    
    $svg = new Svg();
    $svg->setViewBox('0 0 200 200');
    $svg->addElement('rect', [
        'x' => 20,
        'y' => 20,
        'width' => 160,
        'height' => 160,
        'fill' => '#3498db',
        'stroke' => '#2980b9',
        'stroke-width' => 2
    ]);
    echo $svg->render();
    

    Outputs a centered blue rectangle with a border.

  2. Where to Look First

    • Core Classes: Focus on Meyfa\Svg\Svg (main container) and Meyfa\Svg\SvgElement (individual elements).
    • Documentation: Check the GitHub repository for updated examples or tests.
    • Laravel Integration: Explore wrapping the package in a facade or service provider for cleaner usage.
    • PHP 8.4 Compatibility: Review PHP 8.4 deprecations if upgrading projects.

Implementation Patterns

Usage Patterns

  1. Dynamic SVG Generation from Data

    function generateUserBadge(string $name, string $color): string {
        $svg = new Svg();
        $svg->setViewBox('0 0 120 80');
        $svg->addElement('rect', [
            'width' => '100%',
            'height' => '100%',
            'fill' => $color,
            'rx' => 10
        ]);
        $svg->addElement('text', [
            'x' => 60,
            'y' => 45,
            'text-anchor' => 'middle',
            'font-size' => '16px',
            'fill' => '#fff'
        ], $name);
        return $svg->render();
    }
    
  2. Modifying Existing SVGs

    $svgContent = file_get_contents('existing.svg');
    $svg = Svg::loadFromString($svgContent);
    $svg->addElement('circle', [
        'cx' => 50,
        'cy'  => 50,
        'r'   => 20,
        'fill' => 'red'
    ]);
    file_put_contents('modified.svg', $svg->render());
    
  3. Laravel Facade Integration

    // In AppServiceProvider (PHP 8.4 compatible)
    public function register(): void {
        $this->app->bind('svg', fn() => new \Meyfa\Svg\Svg());
    }
    
    // Usage in controllers
    $svg = app('svg');
    $svg->addElement('path', [...]);
    return response($svg->render(), 200)
        ->header('Content-Type', 'image/svg+xml');
    
  4. Queue-Based Generation for Heavy SVGs

    // Job class (PHP 8.4 compatible)
    class GenerateComplexSvgJob implements ShouldQueue {
        public function handle(): void {
            $svg = new Svg();
            // Complex generation logic...
            Storage::put('complex.svg', $svg->render());
        }
    }
    
    // Dispatch from controller
    GenerateComplexSvgJob::dispatch();
    
  5. Blade Directives for Templating

    // In AppServiceProvider (PHP 8.4 compatible)
    Blade::directive('svg', function ($expression) {
        return "<?php echo app('svg')->{$expression}; ?>";
    });
    
    // In Blade template
    @svg('addElement("rect", ["width" => "100%", "height" => "100%", "fill" => "#f0f0f0"])')
    

Integration Tips

  • Caching: Use Laravel's cache system to store generated SVGs:
    $svg = Cache::remember("svg-badge-{$userId}", now()->addHours(1), function() use ($user) {
        return generateUserBadge($user->name, $user->color);
    });
    
  • Storage: Save SVGs to disk or cloud storage:
    Storage::disk('public')->put("avatars/{$userId}.svg", $svg->render());
    
  • API Responses: Return SVGs as proper responses:
    return response($svg->render(), 200)
        ->header('Content-Type', 'image/svg+xml');
    
  • Testing: Mock SVG generation in tests (PHP 8.4 compatible):
    $svg = Mockery::mock(Svg::class);
    $svg->shouldReceive('render')->andReturn('<svg>...</svg>');
    

Gotchas and Tips

Pitfalls

  1. PHP 8.4 Deprecations

    • Fixed in v0.16.1: The package now addresses PHP 8.4 deprecations (e.g., foreach with string keys, create_function).
    • Action Required: Update your project to PHP 8.4 if using this version.
  2. Attribute Case Sensitivity

    • SVG attributes are case-sensitive. Always use lowercase (e.g., fill not Fill).
    • Fix: Normalize attributes when adding elements:
      $attrs = array_change_key_case($attrs, CASE_LOWER);
      $svg->addElement('rect', $attrs);
      
  3. Namespace Issues

    • If parsing existing SVGs, ensure the XML declaration is correct:
      <?xml version="1.0" encoding="UTF-8"?>
      <svg xmlns="http://www.w3.org/2000/svg" ...>
      
    • Fix: Explicitly set the namespace when loading:
      $svg = Svg::loadFromString($content, 'http://www.w3.org/2000/svg');
      
  4. Performance with Complex Paths

    • Generating SVGs with thousands of path elements can be slow.
    • Fix: Use Laravel queues or pre-generate SVGs during off-peak hours.
  5. XSS Vulnerabilities

    • Dynamic text in SVGs can expose XSS risks.
    • Fix: Sanitize dynamic content:
      $text = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
      $svg->addElement('text', [...], $text);
      

Debugging Tips

  1. Validate SVG Output Use the W3C Validator to check for malformed SVGs.

  2. Inspect DOM Structure

    echo $svg->render(); // Check raw output
    

    Or use a DOM inspector in your browser to debug rendered SVGs.

  3. Enable Error Reporting (PHP 8.4)

    libxml_use_internal_errors(true);
    $svg = Svg::loadFromString($content);
    $errors = libxml_get_errors();
    if (!empty($errors)) {
        foreach ($errors as $error) {
            error_log("SVG Error: {$error->message}");
        }
        libxml_clear_errors();
    }
    

Configuration Quirks

  1. Default XML Declaration The package may not include <?xml ...?> by default. Add it manually if needed:

    $svg->setXmlDeclaration('1.0', 'UTF-8');
    
  2. Namespace Handling If working with SVG 2.0 features, ensure the namespace is set:

    $svg->setNamespace('http://www.w3.org/2000/svg');
    
  3. Attribute Ordering SVG parsers may ignore or reorder attributes. Explicitly set critical ones (e.g., viewBox) first.

Extension Points

  1. Custom Element Types Extend the library to support domain-specific elements:

    class CustomSvg extends Svg {
        public function addChart(array $data): void {
            // Custom logic for charts
        }
    }
    
  2. Event Hooks Add pre/post-render hooks for logging or validation (PHP 8.4 compatible):

    $svg = new Svg();
    $svg->on('render', function(Svg $svg) {
        error_log("Rendering SVG with " . $svg->countElements() . " elements");
    });
    
  3. Integration with Laravel Nova Create a custom SVG field for Nova:

    use Laravel\Nova\Fields\Field;
    
    class SvgField extends Field {
        public function render($value): string
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle