Created
April 18, 2019 04:54
-
-
Save calexandrepcjr/04e78ecca156bf36b12a4d76c1c88e04 to your computer and use it in GitHub Desktop.
A trait to control the daily limit of the entity creation
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
<?php declare(strict_types = 1); | |
namespace Traits; | |
use Exception; | |
use Illuminate\Http\Response; | |
trait HasDailyLimit | |
{ | |
abstract protected function attrToFilter(): string; | |
abstract protected function dailyLimit(): int; | |
private function tags(): array | |
{ | |
return ['daily_limit']; | |
} | |
private function cacheKey(): string | |
{ | |
return $this->getTable() . | |
':' . | |
$this->{$this->attrToFilter()}; | |
} | |
public function dailyCheck(): void | |
{ | |
$dailyCounter = app('Cache')::tags($this->tags()) | |
->remember( | |
$this->cacheKey(), | |
now()->endOfDay(), | |
static function () { | |
return 0; | |
} | |
); | |
if ($dailyCounter >= $this->dailyLimit()) { | |
$tableEntities = explode('_', $this->getTable()); | |
throw new Exception( | |
'daily.' . end($tableEntities) . '.limit.reached', | |
Response::HTTP_FORBIDDEN | |
); | |
} | |
app('Cache')::tags($this->tags()) | |
->increment($this->cacheKey(), 1); | |
} | |
public static function boot() | |
{ | |
parent::boot(); | |
static::creating(static function ($entity) { | |
$entity->dailyCheck(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment