generated from spatie/package-skeleton-laravel
-
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from bluefyn-international/feature/atomic-db-ac…
…tions Feature/atomic db actions
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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))); | ||
} | ||
} |