Skip to content

Instantly share code, notes, and snippets.

@patrickguevara
Created August 24, 2016 16:12
Show Gist options
  • Save patrickguevara/9987e1574f851f057bd015580f9854e9 to your computer and use it in GitHub Desktop.
Save patrickguevara/9987e1574f851f057bd015580f9854e9 to your computer and use it in GitHub Desktop.
ActivityLogQueueJob
<?php
namespace App\Jobs;
use App\Jobs\Job;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\Activitylog\Exceptions\CouldNotLogActivity;
class LogActivity extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
/**
* @var Model
*/
private $causer;
/**
* @var Model
*/
private $subject;
/**
* @var string
*/
private $logName;
/**
* @var array
*/
private $properties;
/**
* @var string
*/
private $message;
/**
* Create a new job instance.
*
* @param Model $causer
* @param Model $subject
* @param string $logName
* @param array $properties
* @param string $message
*/
public function __construct(Model $causer = null, Model $subject, string $logName = 'default',
array $properties = [], string $message = 'Look, I logged something.')
{
$this->causer = $causer;
$this->subject = $subject;
$this->logName = $logName;
$this->properties = $properties;
$this->message = $message;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
activity()->causedBy($this->getCauserToUse())
->performedOn($this->subject)
->inLog($this->getLogNameToUse())
->withProperties($this->properties)
->log($this->message);
}
/**
* Helper to determine which log name to use.
*
* @return string
*/
private function getLogNameToUse()
{
if(method_exists($this->subject, 'getLogNameToUse')) {
return $this->subject->getLogNameToUse();
} else {
return $this->logName;
}
}
/**
* Helper to resolve the activity Causer.
*
* @return \Illuminate\Contracts\Auth\Authenticatable|Model|null
* @throws CouldNotLogActivity
*/
private function getCauserToUse()
{
if(is_null($this->causer)) {
if(auth()->user()) {
return auth()->user();
} elseif (auth('customer')->user()) {
return auth('customer')->user();
} else {
throw new CouldNotLogActivity('Authenticated User not found.');
}
} else {
return $this->causer;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment