Skip to content

Instantly share code, notes, and snippets.

@jaggy
Last active August 29, 2015 14:20
Show Gist options
  • Save jaggy/ce2da15d28243969a0ac to your computer and use it in GitHub Desktop.
Save jaggy/ce2da15d28243969a0ac to your computer and use it in GitHub Desktop.
<?php
namespace App;
use ReflectionClass;
trait RecordsActivity
{
public static $_recordableEvents;
public static function boot()
{
parent::boot();
self::$_recordableEvents = [
'created', 'updated', 'deleted'
];
foreach (self::getRecordableEvents() as $event) {
static::{$event}(function ($model) {
Activity::create([
'subject_id' => $model->id,
'subject_type' => get_class($model),
'name' => self::getActivityName($model, 'created'),
'user_id' => $model->user_id,
]);
});
}
}
public static function getRecordableEvents()
{
$observableEvents = (new static)->getObservableEvents();
if (isset(static::$recordableEvents)) {
return static::$recordableEvents;
}
return array_intersect(static::$_recordableEvents, $observableEvents);
}
public static function getActivityName($model, $action)
{
$name = strtolower((new ReflectionClass($model))->getShortName());
return "{$action}_{$name}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment