Created
April 2, 2017 16:36
-
-
Save w00p/d38047537dcdfd0dc1da0adb1cddc090 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 | |
| { | |
| /** | |
| * Register the necessary event listeners. | |
| * | |
| * @return void | |
| */ | |
| protected static function bootRecordsActivity() | |
| { | |
| foreach (static::getModelEvents() as $event) { | |
| static::$event(function ($model) use ($event) { | |
| $model->recordActivity($event); | |
| }); | |
| } | |
| } | |
| /** | |
| * Record activity for the model. | |
| * | |
| * @param string $event | |
| * @return void | |
| */ | |
| public function recordActivity($event) | |
| { | |
| Activity::create([ | |
| 'subject_id' => $this->id, | |
| 'subject_type' => get_class($this), | |
| 'name' => $this->getActivityName($this, $event), | |
| 'user_id' => auth()->user()->id | |
| ]); | |
| } | |
| /** | |
| * Prepare the appropriate activity name. | |
| * | |
| * @param mixed $model | |
| * @param string $action | |
| * @return string | |
| */ | |
| protected function getActivityName($model, $action) | |
| { | |
| $name = strtolower((new ReflectionClass($model))->getShortName()); | |
| return "{$action}_{$name}"; | |
| } | |
| /** | |
| * Get the model events to record activity for. | |
| * | |
| * @return array | |
| */ | |
| protected static function getModelEvents() | |
| { | |
| if (isset(static::$recordEvents)) { | |
| return static::$recordEvents; | |
| } | |
| return [ | |
| 'created', 'deleted', 'updated' | |
| ]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment