Skip to content

Instantly share code, notes, and snippets.

@calexandrepcjr
Created April 18, 2019 04:54
Show Gist options
  • Save calexandrepcjr/04e78ecca156bf36b12a4d76c1c88e04 to your computer and use it in GitHub Desktop.
Save calexandrepcjr/04e78ecca156bf36b12a4d76c1c88e04 to your computer and use it in GitHub Desktop.
A trait to control the daily limit of the entity creation
<?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