Skip to content
Permalink
Browse files

Episode 26 Complete

  • Loading branch information...
JeffreyWay committed Feb 6, 2019
1 parent baa2bd5 commit 0212f60a73a1b110a4dbd5c4e041918fb2126e53
@@ -13,6 +13,20 @@ class Activity extends Model
*/
protected $guarded = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'changes' => 'array'
];
/**
* Get the subject of the activity.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function subject()
{
return $this->morphTo();
@@ -17,6 +17,17 @@ public function created(Project $project)
$project->recordActivity('created');
}
/**
* Handle the project "updating" event.
*
* @param \App\Project $project
* @return void
*/
public function updating(Project $project)
{
$project->old = $project->getOriginal();
}
/**
* Handle the project "updated" event.
*
@@ -13,6 +13,13 @@ class Project extends Model
*/
protected $guarded = [];
/**
* The project's old attributes.
*
* @var array
*/
public $old = [];
/**
* The path to the project.
*
@@ -61,7 +68,26 @@ public function addTask($body)
*/
public function recordActivity($description)
{
$this->activity()->create(compact('description'));
$this->activity()->create([
'description' => $description,
'changes' => $this->activityChanges($description)
]);
}
/**
* Fetch the changes to the model.
*
* @param string $description
* @return array|null
*/
protected function activityChanges($description)
{
if ($description == 'updated') {
return [
'before' => array_except(array_diff($this->old, $this->getAttributes()), 'updated_at'),
'after' => array_except($this->getChanges(), 'updated_at')
];
}
}
/**
@@ -18,6 +18,7 @@ public function up()
$table->unsignedInteger('project_id');
$table->nullableMorphs('subject');
$table->string('description');
$table->text('changes')->nullable();
$table->timestamps();
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
@@ -17,18 +17,34 @@ function creating_a_project()
$project = ProjectFactory::create();
$this->assertCount(1, $project->activity);
$this->assertEquals('created', $project->activity[0]->description);
tap($project->activity->last(), function ($activity) {
$this->assertEquals('created', $activity->description);
$this->assertNull($activity->changes);
});
}
/** @test */
function updating_a_project()
{
$project = ProjectFactory::create();
$originalTitle = $project->title;
$project->update(['title' => 'Changed']);
$this->assertCount(2, $project->activity);
$this->assertEquals('updated', $project->activity->last()->description);
tap($project->activity->last(), function ($activity) use ($originalTitle) {
$this->assertEquals('updated', $activity->description);
$expected = [
'before' => ['title' => $originalTitle],
'after' => ['title' => 'Changed']
];
$this->assertEquals($expected, $activity->changes);
});
}
/** @test */

0 comments on commit 0212f60

Please sign in to comment.
You can’t perform that action at this time.