Skip to content

Instantly share code, notes, and snippets.

@liamja
Created August 22, 2023 17:54
Show Gist options
  • Save liamja/22963b9f5f18781bfd60c5f3c942367c to your computer and use it in GitHub Desktop.
Save liamja/22963b9f5f18781bfd60c5f3c942367c to your computer and use it in GitHub Desktop.
Generate sparklines with vanilla PHP
<?php
class Sparkline
{
public $values = [];
public $width = '4em';
public $height = '1em';
public $stroke_width = 1;
public $stroke_colour = '#000000';
public $fill_colour = '#000000';
public $fill_opacity = 0.05;
public function __construct($values = [])
{
$this->values = $values;
}
public static function from_values($values = [])
{
return (new static)->set_values($values);
}
public function set_values($values)
{
$this->values = $values;
return $this;
}
public function set_width($width)
{
$this->width = $width;
return $this;
}
public function set_height($height)
{
$this->height = $height;
return $this;
}
public function set_colour($colour)
{
$this->stroke_colour = $colour;
$this->fill_colour = $colour;
return $this;
}
public function set_stroke_width($stroke_width)
{
$this->stroke_width = $stroke_width;
return $this;
}
public function set_stroke_colour($stroke_colour)
{
$this->stroke_colour = $stroke_colour;
return $this;
}
public function set_fill_colour($fill_colour)
{
$this->fill_colour = $fill_colour;
return $this;
}
public function set_fill_opacity($fill_opacity)
{
$this->fill_opacity = $fill_opacity;
return $this;
}
public function render()
{
[$min, $max, $count] = [min($this->values), max($this->values), count($this->values)];
[$view_box_width, $view_box_height] = [$count - 1, $max];
$i = 0;
$points = [];
foreach ($this->values as $value) {
[$x, $y] = [$i, $max - $value];
if ($i === 0) {
$points[] = "M {$x} {$y}";
} else {
$points[] = "L {$x} {$y}";
}
$i++;
}
$points = implode(' ', $points);
return <<<SVG
<svg width="{$this->width}" height="{$this->height}" viewBox="0 0 {$view_box_width} {$view_box_height}" preserveAspectRatio="none" role="img" xmlns="http://www.w3.org/2000/svg">
<path d="{$points}" stroke-width="{$this->stroke_width}" stroke="{$this->stroke_colour}" fill="transparent" vector-effect="non-scaling-stroke" />
<path d="{$points} V {$max} H 0 Z" fill="{$this->fill_colour}" fill-opacity="{$this->fill_opacity}" vector-effect="non-scaling-stroke" />
</svg>
SVG;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment