Skip to content

Instantly share code, notes, and snippets.

@SumonMSelim
Forked from raselupm/CreateEvent.php
Last active October 30, 2020 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SumonMSelim/42e7951fd0753267cf1e4b6f9171dcff to your computer and use it in GitHub Desktop.
Save SumonMSelim/42e7951fd0753267cf1e4b6f9171dcff to your computer and use it in GitHub Desktop.
<?php
namespace App\Jobs;
use App\Models\Domain;
use App\Models\Event;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
class CreateEvent implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
const TYPE_UP = 1;
const TYPE_DOWN = 2;
const REASON_OK = 1;
const REASON_FORBIDDEN_ERROR = 2;
const REASON_CLIENT_ERROR = 3;
const REASON_SERVER_ERROR = 4;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
// should only get the columns you actually need
$domains = Domain::select(['id', 'event_id', 'name'])->get();
/** @var Domain $domain */
foreach ($domains as $domain) {
$ping = Http::get('http://'.$domain->name);
// domain is up | checking last previous record
// I believe getting all the events from domain relationship is unnecessary here
// as it's querying all the events first (->get()) and then taking one record (->first())
// Instead you can get the only row that you need here by doing the following
$checkLatestEvent = Event::select(['id', 'domain_id', 'type'])
->where('domain_id', $domain->id)
->latest()
->first();
// last record is not up, so adding a new one
if ($ping->successful() && $checkLatestEvent->type !== self::TYPE_UP) {
$this->recordEvent($domain, self::TYPE_UP, self::REASON_OK);
}
// last record is not down, so adding a new one
if ($ping->failed() && $checkLatestEvent->type !== self::TYPE_DOWN) {
$reason = self::REASON_FORBIDDEN_ERROR;
if ($ping->serverError()) {
$reason = self::REASON_SERVER_ERROR;
}
if ($ping->clientError()) {
$reason = self::REASON_CLIENT_ERROR;
}
$this->recordEvent($domain, self::TYPE_DOWN, $reason);
}
}
}
private function recordEvent(Domain $domain, $latestEventType, $reason)
{
$domain->events()->create([
'type' => $latestEventType,
'reason' => $reason,
]);
// todo email admin about site is up
// I would fire an event here: DomainEvent and send the email from a listener
// event(new DomainEvent($latestEventType, $reason))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment