Skip to content

Commit

Permalink
Merge pull request #9 from bluefyn-international/feature/atomic-db-ac…
Browse files Browse the repository at this point in the history
…tions

Feature/atomic db actions
  • Loading branch information
Quentin Schmick authored Dec 15, 2021
2 parents 82c1a04 + 3e99dd9 commit 77669bc
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/Models/Traits/AtomicDatabaseActions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace BluefynInternational\Sidekick\Models\Traits;

use Illuminate\Support\Facades\Cache;

trait AtomicDatabaseActions
{
public static function firstOrCreateAtomic(array $attributes, array $values = []) : static
{
return self::atomicDatabaseAction('firstOrCreate', $attributes, $values);
}

public static function updateOrCreateAtomic(array $attributes, array $values = []) : static
{
return self::atomicDatabaseAction('updateOrCreate', $attributes, $values);
}

public static function firstOrNewAtomic(array $attributes, array $values = []) : static
{
return self::atomicDatabaseAction('firstOrNew', $attributes, $values);
}

public static function updateOrInsertAtomic(array $attributes, array $values = []) : static
{
return self::atomicDatabaseAction('updateOrInsert', $attributes, $values);
}

protected static function atomicDatabaseAction(string $action, array $attributes, array $values = []) : static
{
$cache_key = self::getAtomicCacheKey($attributes);

return retry(3, function () use ($attributes, $values, $cache_key, $action) {
$lock = Cache::lock($cache_key, 9);
$lock->block(3);
$instance = static::$action($attributes, $values);
$lock->release();

return $instance;
});
}

protected static function getAtomicCacheKey(array $attributes) : string
{
return get_called_class() . ':' . md5(serialize(sort($attributes)));
}
}

0 comments on commit 77669bc

Please sign in to comment.