Skip to content

Commit

Permalink
Make public component methods available in view (#2352)
Browse files Browse the repository at this point in the history
* Make public component methods available in view

* Remove unnecessary import
  • Loading branch information
inxilpro committed Jan 20, 2021
1 parent 7a6b84a commit 1a5285f
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/Component.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public function output($errors = null)
$view->with([
'errors' => $errors,
'_instance' => $this,
] + $this->getPublicPropertiesDefinedBySubClass());
] + $this->getPublicPropertiesDefinedBySubClass() + $this->mapPublicMethodsToClosures());

app('view')->share('errors', $errors);
app('view')->share('_instance', $this);
Expand All @@ -182,6 +182,18 @@ public function output($errors = null)
return $output;
}

public function mapPublicMethodsToClosures()
{
return collect((new \ReflectionClass($this))->getMethods(\ReflectionMethod::IS_PUBLIC))
->reject(function($method) {
return $method->getDeclaringClass() === self::class || Str::startsWith($method->getName(), '__');
})
->mapWithKeys(function($method) {
return [$method->getName() => $method->getClosure($this)];
})
->all();
}

public function normalizePublicPropertiesForJavaScript()
{
foreach ($this->getPublicPropertiesDefinedBySubClass() as $key => $value) {
Expand Down
49 changes: 49 additions & 0 deletions tests/Unit/PublicMethodsAreAvailableInTheViewTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Tests\Unit;

use Livewire\Component;
use Livewire\Livewire;

class PublicMethodsAreAvailableInTheViewTest extends TestCase
{
/** @test */
public function public_methods_is_accessible_in_view_via_this()
{
Livewire::test(PublicMethodsInViewWithoutThisStub::class)
->assertSee('Your Name is Chris');
}

/** @test */
public function public_methods_are_accessible_in_view_without_this()
{
Livewire::test(PublicMethodsInViewWithoutThisStub::class)
->assertSee('Your Name is Chris');
}
}

class PublicMethodsInViewWithThisStub extends Component
{
public function render()
{
return app('view')->make('call-name-with-this');
}

public function name($name)
{
return 'Your Name is '.$name;
}
}

class PublicMethodsInViewWithoutThisStub extends Component
{
public function render()
{
return app('view')->make('call-name');
}

public function name($name)
{
return 'Your Name is '.$name;
}
}
1 change: 1 addition & 0 deletions tests/Unit/views/call-name-with-this.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<span>{{ $this->name('Chris') }}</span>
1 change: 1 addition & 0 deletions tests/Unit/views/call-name.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<span>{{ $name('Chris') }}</span>

0 comments on commit 1a5285f

Please sign in to comment.