diff --git a/examples/output/pie-chart.svg b/examples/output/pie-chart.svg index e8f4d9d..5046b1d 100644 --- a/examples/output/pie-chart.svg +++ b/examples/output/pie-chart.svg @@ -1,7 +1,8 @@ - -Toys - 14% -Furniture - 43% -Home - 15% -Electronics - 28% + + +Toys - 14% +Furniture - 43% +Home - 15% +Electronics - 28% \ No newline at end of file diff --git a/src/Pie/PieChart.php b/src/Pie/PieChart.php index dfd0147..91889b3 100644 --- a/src/Pie/PieChart.php +++ b/src/Pie/PieChart.php @@ -3,6 +3,7 @@ namespace Maantje\Charts\Pie; use Closure; +use Maantje\Charts\SVG\Rect; class PieChart { @@ -14,6 +15,9 @@ class PieChart public function __construct( private readonly int $size = 400, private readonly array $slices = [], + public ?string $background = 'white', + public int $fontSize = 14, + public string $fontFamily = 'arial', ?Closure $formatter = null ) { $this->formatter = $formatter ?? fn (string $label, float $percentage) => "$label - $percentage%"; @@ -22,7 +26,8 @@ public function __construct( public function render(): string { return << + + {$this->background()} {$this->renderSlices()} SVG; @@ -94,4 +99,17 @@ private function renderSlices(): string return $svg; } + + protected function background(): string + { + if (is_null($this->background)) { + return ''; + } + + return new Rect( + width: $this->size, + height: $this->size, + fill: $this->background, + ); + } } diff --git a/src/Pie/Slice.php b/src/Pie/Slice.php index 0598ea4..e8b7196 100644 --- a/src/Pie/Slice.php +++ b/src/Pie/Slice.php @@ -12,7 +12,7 @@ public function __construct( public float $value, public string $color, public string $label, - public int $labelSize = 12, + public ?int $fontSize = null, public string $labelColor = '#000', public float $explodeDistance = 0.0, ) {} @@ -30,7 +30,8 @@ public function render(PieChart $chart, string $pathData, float $labelX, float $ content: $labelText, x: $labelX, y: $labelY, - fontSize: $this->labelSize, + fontFamily: $chart->fontFamily, + fontSize: $this->fontSize ?? $chart->fontSize, fill: $this->labelColor, textAnchor: 'middle', dominantBaseline: 'middle', diff --git a/tests/Unit/PieChartTest.php b/tests/Unit/PieChartTest.php index 77cc9b8..088cbb5 100644 --- a/tests/Unit/PieChartTest.php +++ b/tests/Unit/PieChartTest.php @@ -33,14 +33,17 @@ expect(pretty($chart->render()))->toBe(<<<'SVG' + + + - Toys - 14% + Toys - 14% - Furniture - 43% + Furniture - 43% - Home - 15% + Home - 15% - Electronics - 28% + Electronics - 28% SVG ); @@ -60,8 +63,11 @@ expect(pretty($chart->render()))->toBe(<<<'SVG' + + + - Furniture - 100% + Furniture - 100% SVG ); @@ -75,7 +81,9 @@ expect(pretty($chart->render()))->toBe(<<<'SVG' - + + + SVG );