Trigger event to allow page content to be altered before display

parent 0a146571
......@@ -5,6 +5,7 @@ namespace Modules\Page\Entities;
use Dimsav\Translatable\Translatable;
use Illuminate\Database\Eloquent\Model;
use Modules\Core\Traits\NamespacedEntity;
use Modules\Page\Events\ContentIsRendering;
use Modules\Tag\Contracts\TaggableInterface;
use Modules\Tag\Traits\TaggableTrait;
......@@ -47,6 +48,13 @@ class Page extends Model implements TaggableInterface
];
protected static $entityNamespace = 'asgardcms/page';
public function getBodyAttribute($body)
{
event($event = new ContentIsRendering($body));
return $event->getBody();
}
public function __call($method, $parameters)
{
#i: Convert array to dot notation
......
<?php
namespace Modules\Page\Events;
class ContentIsRendering
{
/**
* @var string The body of the page to render
*/
private $body;
private $original;
public function __construct($body)
{
$this->body = $body;
$this->original = $body;
}
/**
* @return string
*/
public function getBody()
{
return $this->body;
}
/**
* @param string $body
*/
public function setBody($body)
{
$this->body = $body;
}
/**
* @return mixed
*/
public function getOriginal()
{
return $this->original;
}
public function __toString()
{
return $this->getBody();
}
}
<?php
namespace Modules\Page\Tests;
use Illuminate\Support\Facades\Event;
use Modules\Page\Events\ContentIsRendering;
class ContentIsRenderingTest extends BasePageTest
{
/** @test */
public function it_can_change_final_content()
{
Event::listen(ContentIsRendering::class, function (ContentIsRendering $event) {
$event->setBody('<strong>' . $event->getOriginal() . '</strong>');
});
$page = $this->createPage();
$this->assertEquals('<strong>My Page Body</strong>', $page->body);
}
/** @test */
public function it_doesnt_alter_content_if_no_listeners()
{
$page = $this->createPage();
$this->assertEquals('My Page Body', $page->body);
}
private function createPage()
{
return $this->page->create([
'is_home' => '1',
'template' => 'default',
'en' => [
'title' => 'My Other Page',
'slug' => 'my-other-page',
'body' => 'My Page Body',
],
]);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment