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

Svg Chart Bundle Laravel Package

creative-web-solution/svg-chart-bundle

Symfony bundle to generate SVG charts (pie/donut and line) using meyfa/php-svg. Create charts from JSON-configured data and styles, including legend labels, slice colors, donut thickness, line connectors, dimensions, and offsets; returns SVG responses.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require creative-web-solution/svg-chart-bundle
    

    Ensure meyfa/php-svg is installed as a dependency.

  2. First Use Case: Create a JSON config file (e.g., pie_chart_data.json) with minimal data:

    {
        "data": [{
            "values": [{
                "value": 0.5,
                "color": "#ff0000",
                "label": "50%"
            }]
        }],
        "styles": {
            "mode": "pie",
            "width": 300,
            "height": 200
        }
    }
    

    Generate the chart in a controller:

    use Cws\Bundle\SVGChartBundle\SVGChart\SVGChart;
    use Symfony\Component\HttpFoundation\Response;
    
    public function showChart()
    {
        $config = json_decode(file_get_contents('pie_chart_data.json'));
        $svg = SVGChart::createPie($config->data[0], $config->styles);
        return new Response($svg, 200, ['Content-Type' => 'image/svg+xml']);
    }
    
  3. Quick Integration:

    • For Symfony routes, map the controller method to a route (e.g., /chart/pie).
    • For Twig templates, embed the SVG via <img src="{{ path('chart_route') }}" />.

Implementation Patterns

Data Preparation

  1. Dynamic Data Binding: Fetch data from a database or API and transform it into the required JSON structure:

    $chartData = $entityManager->getRepository(YourEntity::class)
        ->findBy([], ['value' => 'DESC'])
        ->map(fn($item) => [
            'value' => $item->getPercentage(),
            'color' => $item->getColor(),
            'label' => $item->getLabel()
        ]);
    
  2. Reusable Config Classes: Create a ChartConfig class to encapsulate JSON logic:

    class PieChartConfig
    {
        public static function fromEntity(YourEntity $entity): array
        {
            return [
                'data' => [['values' => self::mapEntityToValues($entity)]],
                'styles' => self::defaultStyles()
            ];
        }
    }
    

Chart Generation Workflows

  1. Controller Layer:

    public function generateLineChart(LineData $lineData)
    {
        $config = LineChartConfig::fromData($lineData);
        $svg = SVGChart::createLines($config['data'], $config['styles']);
        return new Response($svg, 200, ['Content-Type' => 'image/svg+xml']);
    }
    
  2. Service Layer: Extract chart generation to a service for reusability:

    class ChartService
    {
        public function generatePieChart(array $data, array $styles): string
        {
            return SVGChart::createPie($data, $styles);
        }
    }
    
  3. Caching: Cache generated SVGs to reduce load:

    $cacheKey = 'chart_' . md5(serialize($config));
    if (!$svg = $cache->get($cacheKey)) {
        $svg = SVGChart::createPie($config['data'], $config['styles']);
        $cache->set($cacheKey, $svg, 3600); // Cache for 1 hour
    }
    

Integration with Symfony Ecosystem

  1. Twig Extensions: Create a Twig extension to render charts directly in templates:

    class ChartExtension extends \Twig\Extension\AbstractExtension
    {
        public function getFunctions()
        {
            return [
                new \Twig\TwigFunction('svg_pie_chart', [$this, 'renderPieChart']),
            ];
        }
    
        public function renderPieChart(array $data, array $styles)
        {
            return SVGChart::createPie($data, $styles);
        }
    }
    

    Usage in Twig:

    <img src="data:image/svg+xml;base64,{{ svg_pie_chart(data, styles)|base64_encode }}" />
    
  2. Event Listeners: Generate charts on entity events (e.g., post-save):

    public function onEntitySave(YourEntity $entity)
    {
        $config = PieChartConfig::fromEntity($entity);
        $svg = SVGChart::createPie($config['data'], $config['styles']);
        $entity->setChartData($svg);
        $entityManager->flush();
    }
    
  3. API Responses: Return SVGs as API responses:

    return $this->json([
        'chart' => base64_encode(SVGChart::createBars($data, $styles))
    ], 200, [], ['Content-Type' => 'application/json']);
    

Gotchas and Tips

Common Pitfalls

  1. JSON Validation:

    • The package expects strict JSON structure. Missing or malformed keys (e.g., values, styles) will throw errors.
    • Tip: Validate JSON with json_last_error() before passing to SVGChart:
      $json = file_get_contents('chart_data.json');
      if (json_last_error() !== JSON_ERROR_NONE) {
          throw new \RuntimeException('Invalid JSON: ' . json_last_error_msg());
      }
      
  2. SVG Content-Type:

    • Forgetting to set Content-Type: image/svg+xml will corrupt the SVG output.
    • Tip: Use a helper method:
      private function svgResponse(string $svg): Response
      {
          return new Response($svg, 200, ['Content-Type' => 'image/svg+xml']);
      }
      
  3. Data Array Indexing:

    • For pie/donut charts, only the first element of data is processed. Extra elements are ignored.
    • For line/bars charts, all elements in data are processed. Ensure correct ordering.
  4. CSS Class Conflicts:

    • Custom cssClass or cssSliceClass may conflict with global styles. Use unique prefixes (e.g., chart-pie-2023).
    • Tip: Inspect the generated SVG to debug styling issues.
  5. Donut vs. Pie Mode:

    • donutThickness and donutMainLegend are ignored in pie mode. Set "mode": "donut" explicitly.
  6. Label Rendering:

    • HTML in labels (e.g., <span>€</span>) may break if not escaped. Use htmlspecialchars or configure textTemplate carefully.

Debugging Tips

  1. Inspect Generated SVG: Save the SVG output to a file and open it in a browser to validate:

    file_put_contents('debug_chart.svg', $svg);
    
  2. Log Config: Log the $config array before passing to SVGChart to verify structure:

    \Monolog\Logger::getInstance('app')->info('Chart config:', $config);
    
  3. Dependency Conflicts:

    • Ensure meyfa/php-svg is compatible with your PHP version (e.g., PHP 8.x may require a fork or patch).

Extension Points

  1. Custom Chart Types: Extend the bundle by creating a new class (e.g., SVGChart::createRadar()) and replicate the logic from existing methods.

  2. Dynamic Styling: Override styles dynamically based on user preferences:

    $styles['cssClass'] .= ' user-' . $user->getTheme();
    
  3. Interactive Charts: Use JavaScript libraries (e.g., D3.js) to overlay interactivity on the static SVG output.

  4. Theming: Create a theme service to generate consistent styles:

    class ChartTheme
    {
        public function getPieStyles(string $themeColor): array
        {
            return [
                'cssClass' => 'theme-' . $themeColor,
                'radius' => 120,
                'colors' => ['#' . $themeColor, '#cccccc']
            ];
        }
    }
    
  5. Localization: Localize axis labels or legends by replacing static strings in the JSON config:

    "labels": [
        {"label": "{{ 'Jan.'|trans }}"},
        {"label": "{{ 'Feb.'|trans }}"}
    ]
    
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme