Skip to content

Commit

Permalink
Add ViewAwareTrait::toHtml()
Browse files Browse the repository at this point in the history
  • Loading branch information
tangrufus committed Oct 26, 2017
1 parent fa0cced commit f9e7b23
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/ViewAwareTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ public function render()
$this->getView()->render($this);
}

/**
* Convert the view to HTML with self as context object.
*
* @return string
*/
public function toHtml(): string
{
return $this->getView()->toHtml($this);
}

/**
* Returns a closure which render the view with self as the context.
*
Expand Down
7 changes: 7 additions & 0 deletions src/ViewAwareTraitInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ interface ViewAwareTraitInterface
*/
public function render();

/**
* Convert the view to HTML with self as context object.
*
* @return string
*/
public function toHtml(): string;

/**
* Returns a closure which render the view with self as the context.
*
Expand Down
4 changes: 2 additions & 2 deletions src/ViewInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function render($context = null);
*
* @param mixed $context Optional. Context object for which to render the view.
*
* @return void
* @return string
*/
public function toHtml($context = null);
public function toHtml($context = null): string;
}
14 changes: 14 additions & 0 deletions tests/_data/ViewAwareTraitDummy.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,20 @@ class ViewAwareTraitDummy implements ViewAwareTraitInterface
{
use ViewAwareTrait;

/**
* Dummy data.
*
* @var string
*/
public $name = 'Daenerys Targaryen';

/**
* Dummy data.
*
* @var int
*/
public $dragons = 3;

public function forceSetView($view)
{
$this->view = $view;
Expand Down
17 changes: 17 additions & 0 deletions tests/wpunit/ViewAwareTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,21 @@ public function it_renders_the_view_with_self_as_the_context()

$view->verifyInvokedOnce('render', [$this->subject]);
}

/** @test */
public function it_converts_the_view_to_html_with_self_as_the_context()
{
$view = new View(
codecept_data_dir('dummy-template-with-context.php'),
wp_kses_allowed_html('post')
);
$this->subject->setView($view);

$actual = $this->subject->toHtml();

$this->assertSame(
$view->toHtml($this->subject),
$actual
);
}
}

0 comments on commit f9e7b23

Please sign in to comment.