Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alistaircol/56209c820ade2a93e3b8fff86e1de653 to your computer and use it in GitHub Desktop.
Save alistaircol/56209c820ade2a93e3b8fff86e1de653 to your computer and use it in GitHub Desktop.
Laravel, Browsershot, Chartjs - see https://ac93.uk/articles/laravel-chartjs-blade-browsershot/ for context
<?php
namespace App\Charts\Generators;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\Storage;
use Spatie\TemporaryDirectory\TemporaryDirectory;
use Spatie\Browsershot\Browsershot;
use App\Models\Article;
use App\Models\Asset;
use App\Charts\HorizontalBarChart;
class ConcreteMonthWinnersRelativeChartGenerator
{
public Article $article;
public TemporaryDirectory $temp;
public Filesystem $disk;
public function __construct()
{
$this->temp = (new TemporaryDirectory)->create();
$this->disk = Storage::createLocalDriver(['root' => $this->temp->path()]);
}
public function setArticle(Article $article): self
{
$this->article = $article;
return $this;
}
public function getArticle(): Article
{
return $this->article;
}
public function getMediaLocationName(): string
{
// TODO: add region/date affixes
return 'concrete_month_winners_relative';
}
public function getMeasurement(): string
{
return StatsCollector::MEASUREMENT_RELATIVE;
}
public function getRows(): Collection
{
return $this->stats->getConcreteMonthWinnersRelativeData();
}
public function getView(): string
{
return 'charts.concrete_month_winners_relative';
}
public function getTrend(): string
{
return 'winners';
}
public function getPeriod(): string
{
return 'month';
}
public function getViewAttributeBag(): array
{
return [
'chart' => $this->getChart(),
];
}
public function getChart(): array
{
return HorizontalBarChart::make(
$this->getRows(),
$this->getMeasurement()
)->toArray();
}
public function html(): string
{
return app('view')
->make($this->getView(), $this->getViewAttributeBag())
->render();
}
public function png(): Asset
{
Browsershot::html($this->html())
->deviceScaleFactor(3)
->windowSize(
896,
1
)
->fullPage()
->save($this->disk->path($name = $this->getMediaLocationName() . '.png'));
Storage::disk($driver = 's3')->put(
$remotePath = sprintf('article_charts/%d/%s', $this->getArticle()->id, $name),
$this->disk->get($name),
'public'
);
$asset = new Asset();
$asset->relatable_id = $this->getArticle()->id;
$asset->relatable_type = $this->getArticle()->getMorphClass();
$asset->media_location = Storage::disk($driver)->url($remotePath);
$asset->save();
// TODO: store the associated meta
// $this->getTrend()
// $this->getPeriod()
// $this->getMeasurement()
return $asset;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment