Skip to content

Commit b82c2f8

Browse files
committed
Add ability to override with custom model
1 parent 07bcf0c commit b82c2f8

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

src/DatabaseMetricManager.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,30 @@ class DatabaseMetricManager implements MetricManager
1212
*/
1313
protected bool $capturing = false;
1414

15+
/**
16+
* The metric model to use.
17+
*
18+
* @var class-string<\Illuminate\Database\Eloquent\Model>
19+
*/
20+
public static string $model = Metric::class;
21+
1522
/**
1623
* Constructor.
1724
*/
1825
public function __construct(
1926
protected MetricRepository $repository
2027
) {}
2128

29+
/**
30+
* Set the metric model to use.
31+
*
32+
* @param class-string<\Illuminate\Database\Eloquent\Model> $model
33+
*/
34+
public static function useModel(string $model): void
35+
{
36+
static::$model = $model;
37+
}
38+
2239
/**
2340
* {@inheritDoc}
2441
*/

src/Jobs/RecordMetric.php

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace DirectoryTree\Metrics\Jobs;
44

5+
use DirectoryTree\Metrics\DatabaseMetricManager;
56
use DirectoryTree\Metrics\Measurable;
67
use DirectoryTree\Metrics\Metric;
78
use Illuminate\Bus\Queueable;
@@ -19,7 +20,7 @@ class RecordMetric implements ShouldQueue
1920
*/
2021
public function __construct(
2122
/** @var Collection<Measurable>|Measurable */
22-
public Collection|Measurable $metrics,
23+
public Collection|Measurable $metrics
2324
) {}
2425

2526
/**
@@ -38,9 +39,13 @@ public function handle(): void
3839
fn (Measurable $metric) => $metric->value()
3940
);
4041

41-
Metric::query()->getConnection()->transaction(
42-
function (ConnectionInterface $connection) use ($metric, $value) {
43-
$model = Metric::query()->firstOrCreate([
42+
/** @var \Illuminate\Database\Eloquent\Model $model */
43+
$model = new DatabaseMetricManager::$model;
44+
45+
$model->getConnection()->transaction(
46+
function (ConnectionInterface $connection) use ($metric, $value, $model) {
47+
$instance = $model->newQuery()->firstOrCreate([
48+
...$metric->additional(),
4449
'name' => $metric->name(),
4550
'category' => $metric->category(),
4651
'year' => $metric->year(),
@@ -50,7 +55,7 @@ function (ConnectionInterface $connection) use ($metric, $value) {
5055
'measurable_id' => $metric->measurable()?->getKey(),
5156
], ['value' => 0]);
5257

53-
Metric::query()->whereKey($model->getKey())->update([
58+
$model->newQuery()->whereKey($instance->getKey())->update([
5459
'value' => $connection->raw('value + '.$value),
5560
]);
5661
}

0 commit comments

Comments
 (0)