Last active
August 29, 2015 14:20
-
-
Save jaggy/ce2da15d28243969a0ac to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
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