Skip to content

Commit 5a2e9f5

Browse files
committed
Fix audits prune
1 parent f92602d commit 5a2e9f5

File tree

4 files changed

+19
-21
lines changed

4 files changed

+19
-21
lines changed

src/Audit.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,13 @@ private function castDatetimeUTC($model, $value)
183183
}
184184

185185
if (preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/', $value)) {
186-
return Date::instance(Carbon::createFromFormat('Y-m-d H:i:s', $value, Date::now('UTC')->getTimezone()));
186+
$date = Carbon::createFromFormat('Y-m-d H:i:s', $value, Date::now('UTC')->getTimezone());
187+
188+
if (! $date) {
189+
return $value;
190+
}
191+
192+
return Date::instance($date);
187193
}
188194

189195
try {

src/Drivers/Database.php

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,23 +23,17 @@ public function prune(Auditable $model): bool
2323
{
2424
if (($threshold = $model->getAuditThreshold()) > 0) {
2525
$auditClass = get_class($model->audits()->getModel());
26-
$auditModel = new $auditClass;
26+
$keyName = (new $auditClass)->getKeyName();
27+
$forRemoval = array_slice(
28+
$model->audits()->latest()->pluck($keyName)->all(),
29+
$threshold
30+
);
2731

28-
return $model->audits()
29-
->leftJoinSub(
30-
$model->audits()->getQuery()
31-
->select($auditModel->getKeyName())->limit($threshold)->latest(),
32-
'audit_threshold',
33-
function ($join) use ($auditModel) {
34-
$join->on(
35-
$auditModel->gettable().'.'.$auditModel->getKeyName(),
36-
'=',
37-
'audit_threshold.'.$auditModel->getKeyName()
38-
);
39-
}
40-
)
41-
->whereNull('audit_threshold.'.$auditModel->getKeyName())
42-
->delete() > 0;
32+
if (count($forRemoval)) {
33+
return $model->audits()
34+
->whereIntegerInRaw($keyName, $forRemoval)
35+
->delete() > 0;
36+
}
4337
}
4438

4539
return false;

src/Resolvers/UrlResolver.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public static function resolve(Auditable $auditable): string
2525
public static function resolveCommandLine(): string
2626
{
2727
$command = Request::server('argv', null);
28-
if (is_array($command)) {
28+
if (is_array($command)) { // @phpstan-ignore function.impossibleType
2929
return implode(' ', $command);
3030
}
3131

tests/Functional/AuditingTest.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,9 +276,7 @@ public function test_it_will_remove_older_audits_above_the_threshold(): void
276276
]);
277277

278278
foreach (range(1, 20) as $count) {
279-
if ($count === 11) {
280-
sleep(1);
281-
}
279+
Carbon::setTestNow(now()->addSeconds($count));
282280

283281
$article->update([
284282
'title' => 'Title #'.$count,

0 commit comments

Comments
 (0)