From db8b2ae5bea751e3c09c74e9754211bae5ede3a0 Mon Sep 17 00:00:00 2001 From: BarTracz <115506125+BarTracz@users.noreply.github.com> Date: Wed, 10 Jul 2024 01:42:08 +0200 Subject: [PATCH] #11 - Add build from query method to builder class (#13) --- readme.md | 9 +++++++++ src/LaravelHeatmapBuilder.php | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/readme.md b/readme.md index 6a2eec7..629cc63 100644 --- a/readme.md +++ b/readme.md @@ -37,3 +37,12 @@ $data = [ $heatmapBuilder = new LaravelHeatmapBuilder(); $heatmap = $heatmapBuilder->buildFromArray($data, 'created_at'); ``` +There is also option to build from query: +```php +use Blumilk\LaravelHeatmap\LaravelHeatmapBuilder; + +$query = YourModel::where('created_at', '>', '2022-11-01 00:00:00'); + +$heatmapBuilder = new LaravelHeatmapBuilder(); +$heatmap = $heatmapBuilder->buildFromQuery($query, 'created_at'); +``` diff --git a/src/LaravelHeatmapBuilder.php b/src/LaravelHeatmapBuilder.php index bc8c433..073104a 100644 --- a/src/LaravelHeatmapBuilder.php +++ b/src/LaravelHeatmapBuilder.php @@ -9,6 +9,7 @@ use Blumilk\Heatmap\HeatmapBuilder; use Blumilk\Heatmap\PeriodInterval; use Carbon\Carbon; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use InvalidArgumentException; @@ -30,6 +31,21 @@ public function buildFromArray(array $data, string $arrayAccessIndex = self::DEF return parent::build($collection); } + public function buildFromQuery(Builder $query, string $arrayAccessIndex = self::DEFAULT_ARRAY_ACCESS_INDEX): array + { + if (!is_a($query, Builder::class)) { + throw new InvalidArgumentException("The provided query is not a valid Eloquent Builder instance."); + } + + $this->arrayAccessIndex = $arrayAccessIndex; + + $results = $query->get(); + + $collection = $results instanceof Collection ? $results : collect($results); + + return $this->buildFromCollection($collection, $arrayAccessIndex); + } + /** * @param iterable $data */