repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileDownloads/SupportFileDownloads.php | src/Features/SupportFileDownloads/SupportFileDownloads.php | <?php
namespace Livewire\Features\SupportFileDownloads;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Livewire\ComponentHook;
use Illuminate\Contracts\Support\Responsable;
class SupportFileDownloads extends ComponentHook
{
function call()
{
return function ($return) {
if ($return instanceof Responsable){
$return = $return->toResponse(request());
}
if ($this->valueIsntAFileResponse($return)) return;
$response = $return;
$name = $this->getFilenameFromContentDispositionHeader(
$response->headers->get('Content-Disposition')
);
$binary = $this->captureOutput(function () use ($response) {
$response->sendContent();
});
$content = base64_encode($binary);
$this->storeSet('download', [
'name' => $name,
'content' => $content,
'contentType' => $response->headers->get('Content-Type'),
]);
};
}
function dehydrate($context)
{
if (! $download = $this->storeGet('download')) return;
$context->addEffect('download', $download);
}
function valueIsntAFileResponse($value)
{
return ! $value instanceof StreamedResponse
&& ! $value instanceof BinaryFileResponse;
}
function captureOutput($callback)
{
ob_start();
$callback();
return ob_get_clean();
}
function getFilenameFromContentDispositionHeader($header)
{
/**
* The following conditionals are here to allow for quoted and
* non quoted filenames in the Content-Disposition header.
*
* Both of these values should return the correct filename without quotes.
*
* Content-Disposition: attachment; filename=filename.jpg
* Content-Disposition: attachment; filename="test file.jpg"
*/
// Support foreign-language filenames (japanese, greek, etc..)...
if (preg_match('/filename\*=utf-8\'\'(.+)$/i', $header, $matches)) {
return rawurldecode($matches[1]);
}
if (preg_match('/.*?filename="(.+?)"/', $header, $matches)) {
return $matches[1];
}
if (preg_match('/.*?filename=([^; ]+)/', $header, $matches)) {
return $matches[1];
}
return 'download';
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileDownloads/TestsFileDownloads.php | src/Features/SupportFileDownloads/TestsFileDownloads.php | <?php
namespace Livewire\Features\SupportFileDownloads;
use PHPUnit\Framework\Assert as PHPUnit;
trait TestsFileDownloads
{
public function assertFileDownloaded($filename = null, $content = null, $contentType = null)
{
$downloadEffect = data_get($this->effects, 'download');
if ($filename) {
PHPUnit::assertEquals(
$filename,
data_get($downloadEffect, 'name')
);
} else {
PHPUnit::assertNotNull($downloadEffect);
}
if ($content) {
$downloadedContent = data_get($this->effects, 'download.content');
PHPUnit::assertEquals(
$content,
base64_decode($downloadedContent)
);
}
if ($contentType) {
PHPUnit::assertEquals(
$contentType,
data_get($this->effects, 'download.contentType')
);
}
return $this;
}
public function assertNoFileDownloaded()
{
$downloadEffect = data_get($this->effects, 'download');
PHPUnit::assertNull($downloadEffect);
return $this;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireShow/BrowserTest.php | src/Features/SupportWireShow/BrowserTest.php | <?php
namespace Livewire\Features\SupportWireShow;
use Livewire\Component;
use Livewire\Livewire;
use Tests\BrowserTestCase;
class BrowserTest extends BrowserTestCase
{
public function test_wire_show_toggles_element_visibility()
{
Livewire::visit(new class extends Component {
public $show = true;
public function render()
{
return <<<'HTML'
<div>
<button wire:click="$toggle('show')" dusk="toggle">Toggle</button>
<div wire:show="show" dusk="hello">Hello</div>
</div>
HTML;
}
})
->assertVisible('@hello')
->assertSee('Hello')
->waitForLivewire()->click('@toggle')
->assertMissing('@hello')
->assertDontSee('Hello');
}
public function test_wire_show_does_not_display_elements_when_property_is_initially_false()
{
Livewire::visit(new class extends Component {
public $show = false;
public function render()
{
return <<<'HTML'
<div>
<button wire:click="$toggle('show')" dusk="toggle">Toggle</button>
<div wire:show="show" dusk="hello">Hello</div>
</div>
HTML;
}
})
->assertMissing('@hello')
->assertDontSee('Hello')
->waitForLivewire()->click('@toggle')
->assertVisible('@hello')
->assertSee('Hello');
}
public function test_wire_show_supports_the_not_operator_before_the_expression()
{
Livewire::visit(new class extends Component {
public $show = false;
public function render()
{
return <<<'HTML'
<div>
<button wire:click="$toggle('show')" dusk="toggle">Toggle</button>
<div wire:show="!show" dusk="hello">Hello</div>
</div>
HTML;
}
})
->assertVisible('@hello')
->assertSee('Hello')
->waitForLivewire()->click('@toggle')
->assertMissing('@hello')
->assertDontSee('Hello');
}
public function test_wire_show_supports_the_not_operator_with_a_space_before_the_expression()
{
Livewire::visit(new class extends Component {
public $show = false;
public function render()
{
return <<<'HTML'
<div>
<button wire:click="$toggle('show')" dusk="toggle">Toggle</button>
<div wire:show="! show" dusk="hello">Hello</div>
</div>
HTML;
}
})
->assertVisible('@hello')
->assertSee('Hello')
->waitForLivewire()->click('@toggle')
->assertMissing('@hello')
->assertDontSee('Hello');
}
public function test_wire_show_supports_the_important_modifier()
{
Livewire::visit(new class extends Component {
public $show = true;
public function render()
{
return <<<'HTML'
<div>
<button wire:click="$toggle('show')" dusk="toggle">Toggle</button>
<div wire:show.important="show" dusk="hello">Hello</div>
</div>
HTML;
}
})
->assertVisible('@hello')
->assertSee('Hello')
->waitForLivewire()->click('@toggle')
->assertMissing('@hello')
->assertDontSee('Hello')
->assertAttributeContains('@hello', 'style', 'display: none !important;');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLockedProperties/UnitTest.php | src/Features/SupportLockedProperties/UnitTest.php | <?php
namespace Livewire\Features\SupportLockedProperties;
use Livewire\Livewire;
use Livewire\Component as BaseComponent;
use Livewire\Form;
use Tests\TestComponent;
class UnitTest extends \Tests\TestCase
{
function test_cant_update_locked_property()
{
$this->expectExceptionMessage(
'Cannot update locked property: [count]'
);
Livewire::test(new class extends TestComponent {
#[BaseLocked]
public $count = 1;
function increment() { $this->count++; }
})
->assertSetStrict('count', 1)
->set('count', 2);
}
function test_cant_deeply_update_locked_property()
{
$this->expectException(CannotUpdateLockedPropertyException::class);
$this->expectExceptionMessage(
'Cannot update locked property: [foo]'
);
Livewire::test(new class extends TestComponent {
#[BaseLocked]
public $foo = ['count' => 1];
function increment() { $this->foo['count']++; }
})
->assertSetStrict('foo.count', 1)
->set('foo.count', 2);
}
function test_can_update_locked_property_with_similar_name()
{
Livewire::test(new class extends TestComponent {
#[BaseLocked]
public $count = 1;
public $count2 = 1;
})
->assertSetStrict('count2', 1)
->set('count2', 2);
}
public function test_it_can_updates_form_with_locked_properties()
{
Livewire::test(Component::class)
->set('form.foo', 'bar')
->assertSetStrict('form.foo', 'bar')
->assertOk();
}
}
class SomeForm extends Form {
#[BaseLocked]
public ?string $id = null;
public string $foo = '';
public function init(?string $id) {
$this->id = $id;
}
}
class Component extends BaseComponent
{
public SomeForm $form;
public function mount() {
$this->form->init('id');
}
public function render()
{
return <<< 'HTML'
<div>
<input type='text' wire:model='form.foo' />
</div>
HTML;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLockedProperties/BaseLocked.php | src/Features/SupportLockedProperties/BaseLocked.php | <?php
namespace Livewire\Features\SupportLockedProperties;
use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute;
#[\Attribute]
class BaseLocked extends LivewireAttribute
{
public function update()
{
throw new CannotUpdateLockedPropertyException($this->getName());
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php | src/Features/SupportLockedProperties/CannotUpdateLockedPropertyException.php | <?php
namespace Livewire\Features\SupportLockedProperties;
class CannotUpdateLockedPropertyException extends \Exception
{
public function __construct(public $property)
{
parent::__construct(
'Cannot update locked property: ['.$this->property.']'
);
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireIgnore/BrowserTest.php | src/Features/SupportWireIgnore/BrowserTest.php | <?php
namespace Livewire\Features\SupportWireIgnore;
use Tests\BrowserTestCase;
use Livewire\Component;
use Livewire\Livewire;
class BrowserTest extends BrowserTestCase
{
public function test_wire_ignore()
{
Livewire::visit(new class extends Component {
public $foo = false;
public $bar = false;
public $baz = false;
public $bob = false;
public $lob = false;
public function render()
{
return <<<'HTML'
<div>
<button wire:click="$set('foo', true)" @if ($foo) some-new-attribute="true" @endif wire:ignore dusk="foo">Foo</button>
<button wire:click="$set('bar', true)" wire:ignore dusk="bar">
<span dusk="bar.output">{{ $bar ? 'new' : 'old' }}</span>
</button>
<button wire:click="$set('baz', true)" @if ($baz) some-new-attribute="true" @endif wire:ignore.self dusk="baz">
<span dusk="baz.output">{{ $baz ? 'new' : 'old' }}</span>
</button>
<button wire:click="$set('bob', true)" dusk="bob">
<span dusk="bob.output">{{ $bob ? 'new' : 'old' }}</span>
</button>
<button wire:click="$set('lob', true)" @if ($lob) some-new-attribute="true" @endif dusk="lob">
<span dusk="lob.output">{{ $lob ? 'new' : 'old' }}</span>
</button>
</div>
HTML;
}
})
/**
* wire:ignore doesnt modify element or children after update
*/
->assertAttributeMissing('@foo', 'some-new-attribute')
->waitForLivewire()->click('@foo')
->assertAttributeMissing('@foo', 'some-new-attribute')
/**
* wire:ignore ignores updates to children
*/
->assertSeeIn('@bar.output', 'old')
->waitForLivewire()->click('@bar')
->assertSeeIn('@bar.output', 'old')
/**
* wire:ignore.self ignores updates to self, but not children
*/
->assertSeeIn('@baz.output', 'old')
->assertAttributeMissing('@baz', 'some-new-attribute')
->waitForLivewire()->click('@baz')
->assertAttributeMissing('@baz', 'some-new-attribute')
->assertSeeIn('@baz.output', 'new')
/**
* adding .__livewire_ignore to element ignores updates to children
*/
->tap(function ($b) { $b->script("document.querySelector('[dusk=\"bob\"]').__livewire_ignore = true"); })
->assertSeeIn('@bob.output', 'old')
->waitForLivewire()->click('@bob')
->assertSeeIn('@bob.output', 'old')
/**
* adding .__livewire_ignore_self to element ignores updates to self, but not children
*/
->tap(function ($b) { $b->script("document.querySelector('[dusk=\"lob\"]').__livewire_ignore_self = true"); })
->assertSeeIn('@lob.output', 'old')
->assertAttributeMissing('@lob', 'some-new-attribute')
->waitForLivewire()->click('@lob')
->assertAttributeMissing('@lob', 'some-new-attribute')
->assertSeeIn('@lob.output', 'new')
;
}
public function test_wire_ignore_children()
{
Livewire::visit(new class extends Component {
public $baz = false;
public $lob = false;
public function render()
{
return <<<'HTML'
<div>
<button wire:click="$set('baz', true)" some-attribute="{{ $baz ? 'new' : 'old' }}" wire:ignore.children dusk="baz">
<span dusk="baz.child">{{ $baz ? 'new' : 'old' }}</span>
</button>
<button wire:click="$set('lob', true)" some-attribute="{{ $lob ? 'new' : 'old' }}" dusk="lob">
<span dusk="lob.child">{{ $lob ? 'new' : 'old' }}</span>
</button>
</div>
HTML;
}
})
/**
* wire:ignore.children ignores updates to children, but not self
*/
->assertSeeIn('@baz.child', 'old')
->assertAttribute('@baz', 'some-attribute', 'old')
->waitForLivewire()->click('@baz')
->assertAttribute('@baz', 'some-attribute', 'new')
->assertSeeIn('@baz.child', 'old')
/**
* adding .__livewire_ignore_children to element ignores updates to children, but not children
*/
->tap(function ($b) { $b->script("document.querySelector('[dusk=\"lob\"]').__livewire_ignore_children = true"); })
->assertSeeIn('@lob.child', 'old')
->assertAttribute('@lob', 'some-attribute', 'old')
->waitForLivewire()->click('@lob')
->assertAttribute('@lob', 'some-attribute', 'new')
->assertSeeIn('@lob.child', 'old')
;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireBind/BrowserTest.php | src/Features/SupportWireBind/BrowserTest.php | <?php
namespace Livewire\Features\SupportWireBind;
use Livewire\Component;
use Livewire\Livewire;
use Tests\BrowserTestCase;
class BrowserTest extends BrowserTestCase
{
public function test_wire_bind_binds_attribute_on_init()
{
Livewire::visit(new class extends Component {
public $class = 'text-red';
public function render()
{
return <<<'HTML'
<div>
<div wire:bind:class="class" dusk="target">Hello</div>
</div>
HTML;
}
})
->assertAttribute('@target', 'class', 'text-red');
}
public function test_wire_bind_updates_attribute_when_property_changes()
{
Livewire::visit(new class extends Component {
public $class = 'text-red';
public function render()
{
return <<<'HTML'
<div>
<div wire:bind:class="class" dusk="target">Hello</div>
<button wire:click="$set('class', 'text-blue')" dusk="change">Change</button>
</div>
HTML;
}
})
->assertAttribute('@target', 'class', 'text-red')
->waitForLivewire()->click('@change')
->assertAttribute('@target', 'class', 'text-blue');
}
public function test_wire_bind_can_bind_style_attribute()
{
Livewire::visit(new class extends Component {
public $color = 'red';
public function render()
{
return <<<'HTML'
<div>
<div wire:bind:style="{ 'color': color }" dusk="target">Hello</div>
<button wire:click="$set('color', 'blue')" dusk="change">Change</button>
</div>
HTML;
}
})
->assertAttribute('@target', 'style', 'color: red;')
->waitForLivewire()->click('@change')
->assertAttribute('@target', 'style', 'color: blue;');
}
public function test_wire_bind_can_bind_href_attribute()
{
Livewire::visit(new class extends Component {
public $url = 'https://example.com';
public function render()
{
return <<<'HTML'
<div>
<a wire:bind:href="url" dusk="link">Link</a>
<button wire:click="$set('url', 'https://livewire.dev')" dusk="change">Change</button>
</div>
HTML;
}
})
->assertAttribute('@link', 'href', 'https://example.com/')
->waitForLivewire()->click('@change')
->assertAttribute('@link', 'href', 'https://livewire.dev/');
}
public function test_wire_bind_can_bind_disabled_attribute()
{
Livewire::visit(new class extends Component {
public $disabled = true;
public function render()
{
return <<<'HTML'
<div>
<button wire:bind:disabled="disabled" dusk="target">Submit</button>
<button wire:click="$toggle('disabled')" dusk="toggle">Toggle</button>
</div>
HTML;
}
})
->assertAttribute('@target', 'disabled', 'true')
->waitForLivewire()->click('@toggle')
->assertAttributeMissing('@target', 'disabled');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLifecycleHooks/TraitsUnitTest.php | src/Features/SupportLifecycleHooks/TraitsUnitTest.php | <?php
namespace Livewire\Features\SupportLifecycleHooks;
use Livewire\Component;
use Livewire\Livewire;
class TraitsUnitTest extends \Tests\TestCase
{
public function test_traits_can_intercept_lifecycle_hooks()
{
Livewire::test(ComponentWithTraitStub::class)
->assertSetStrict(
'hooksFromTrait',
['initialized', 'mount', 'rendering', 'rendered:show-name', 'dehydrate']
)
->set('foo', 'bar')
->assertSetStrict(
'hooksFromTrait',
['initialized', 'hydrate', 'updating:foobar', 'updated:foobar', 'rendering', 'rendered:show-name', 'dehydrate']
)
->call(
'testExceptionInterceptor',
)
->assertSetStrict(
'hooksFromTrait',
['initialized', 'hydrate', 'exception', 'rendering', 'rendered:show-name', 'dehydrate']
);
}
public function test_multiple_traits_can_intercept_lifecycle_hooks()
{
Livewire::test(ComponentWithTwoTraitsStub::class)
->assertSetStrict('hooksFromTrait', [
'initialized', 'secondInitialized',
'mount', 'secondMount',
'rendering', 'secondRendering',
'rendered:show-name', 'secondRendered:show-name',
'dehydrate', 'secondDehydrate'
])
->set('foo', 'bar')
->assertSetStrict('hooksFromTrait', [
'initialized', 'secondInitialized',
'hydrate', 'secondHydrate',
'updating:foobar', 'secondUpdating:foobar',
'updated:foobar', 'secondUpdated:foobar',
'rendering', 'secondRendering',
'rendered:show-name', 'secondRendered:show-name',
'dehydrate', 'secondDehydrate'
]);
}
public function test_calling_test_methods_will_not_run_hooks_from_previous_methods()
{
ComponentForTestMethodsStub::$hooksFromTrait = [];
$test = Livewire::test(ComponentForTestMethodsStub::class);
$this->assertEquals(
['initialized', 'mount', 'rendering', 'rendered:show-name', 'dehydrate',],
ComponentForTestMethodsStub::$hooksFromTrait
);
ComponentForTestMethodsStub::$hooksFromTrait = [];
$test->set('foo', 'bar');
$this->assertEquals(
['initialized', 'hydrate', 'updating:foobar', 'updated:foobar', 'rendering', 'rendered:show-name', 'dehydrate'],
ComponentForTestMethodsStub::$hooksFromTrait
);
ComponentForTestMethodsStub::$hooksFromTrait = [];
$test->call('save');
$this->assertEquals(
['initialized', 'hydrate', 'rendering', 'rendered:show-name', 'dehydrate'],
ComponentForTestMethodsStub::$hooksFromTrait
);
}
public function test_trait_hooks_are_run_at_the_same_time_as_component_hooks()
{
Livewire::test(ComponentWithTraitStubAndComponentLifecycleHooks::class)
->assertSetStrict(
'hooks',
[
'bootcomponent',
'boottrait',
'initializedtrait',
'mountcomponent',
'mounttrait',
'bootedcomponent',
'bootedtrait',
'rendercomponent',
'renderingcomponent',
'renderingtrait',
'renderedcomponent:show-name',
'renderedtrait:show-name',
'dehydratecomponent',
'dehydratetrait',
]
)
->set('foo', 'bar')
->assertSetStrict(
'hooks',
[
'bootcomponent',
'boottrait',
'initializedtrait',
'hydratecomponent',
'hydratetrait',
'bootedcomponent',
'bootedtrait',
'updatingcomponent:foobar',
'updatingtrait:foobar',
'updatedcomponent:foobar',
'updatedtrait:foobar',
'rendercomponent',
'renderingcomponent',
'renderingtrait',
'renderedcomponent:show-name',
'renderedtrait:show-name',
'dehydratecomponent',
'dehydratetrait',
]
)
->call('testExceptionInterceptor')
->assertSetStrict(
'hooks',
[
'bootcomponent',
'boottrait',
'initializedtrait',
'hydratecomponent',
'hydratetrait',
'bootedcomponent',
'bootedtrait',
'exceptioncomponent',
'exceptiontrait',
'rendercomponent',
'renderingcomponent',
'renderingtrait',
'renderedcomponent:show-name',
'renderedtrait:show-name',
'dehydratecomponent',
'dehydratetrait',
]
);
}
}
class CustomException extends \Exception {};
trait TraitForComponent
{
public function mountTraitForComponent()
{
$this->hooksFromTrait[] = 'mount';
}
public function hydrateTraitForComponent()
{
$this->hooksFromTrait[] = 'hydrate';
}
public function dehydrateTraitForComponent()
{
$this->hooksFromTrait[] = 'dehydrate';
}
public function updatingTraitForComponent($name, $value)
{
$this->hooksFromTrait[] = 'updating:'.$name.$value;
}
public function updatedTraitForComponent($name, $value)
{
$this->hooksFromTrait[] = 'updated:'.$name.$value;
}
public function renderingTraitForComponent()
{
$this->hooksFromTrait[] = 'rendering';
}
public function renderedTraitForComponent($view)
{
$this->hooksFromTrait[] = 'rendered:'.$view->getName();
}
public function initializeTraitForComponent()
{
// Reset from previous requests.
$this->hooksFromTrait = [];
$this->hooksFromTrait[] = 'initialized';
}
public function exceptionTraitForComponent($e, $stopPropagation)
{
if($e instanceof CustomException) {
$this->hooksFromTrait[] = 'exception';
$stopPropagation();
}
}
}
class ComponentWithTraitStub extends Component
{
use TraitForComponent;
public $hooksFromTrait = [];
public $foo = 'bar';
public function testExceptionInterceptor()
{
throw new CustomException;
}
public function render()
{
return view('show-name', ['name' => $this->foo]);
}
}
trait SecondTraitForComponent
{
public function mountSecondTraitForComponent()
{
$this->hooksFromTrait[] = 'secondMount';
}
public function hydrateSecondTraitForComponent()
{
$this->hooksFromTrait[] = 'secondHydrate';
}
public function dehydrateSecondTraitForComponent()
{
$this->hooksFromTrait[] = 'secondDehydrate';
}
public function updatingSecondTraitForComponent($name, $value)
{
$this->hooksFromTrait[] = 'secondUpdating:'.$name.$value;
}
public function updatedSecondTraitForComponent($name, $value)
{
$this->hooksFromTrait[] = 'secondUpdated:'.$name.$value;
}
public function renderingSecondTraitForComponent()
{
$this->hooksFromTrait[] = 'secondRendering';
}
public function renderedSecondTraitForComponent($view)
{
$this->hooksFromTrait[] = 'secondRendered:'.$view->getName();
}
public function initializeSecondTraitForComponent()
{
$this->hooksFromTrait[] = 'secondInitialized';
}
}
class ComponentWithTwoTraitsStub extends ComponentWithTraitStub
{
use TraitForComponent, SecondTraitForComponent;
}
trait TraitForComponentForTestMethods
{
public function mountTraitForComponentForTestMethods()
{
static::$hooksFromTrait[] = 'mount';
}
public function hydrateTraitForComponentForTestMethods()
{
static::$hooksFromTrait[] = 'hydrate';
}
public function dehydrateTraitForComponentForTestMethods()
{
static::$hooksFromTrait[] = 'dehydrate';
}
public function updatingTraitForComponentForTestMethods($name, $value)
{
static::$hooksFromTrait[] = 'updating:'.$name.$value;
}
public function updatedTraitForComponentForTestMethods($name, $value)
{
static::$hooksFromTrait[] = 'updated:'.$name.$value;
}
public function renderingTraitForComponentForTestMethods()
{
static::$hooksFromTrait[] = 'rendering';
}
public function renderedTraitForComponentForTestMethods($view)
{
static::$hooksFromTrait[] = 'rendered:'.$view->getName();
}
public function initializeTraitForComponentForTestMethods()
{
static::$hooksFromTrait[] = 'initialized';
}
}
class ComponentForTestMethodsStub extends Component
{
use TraitForComponentForTestMethods;
/*
* Livewire tests will boot a new instance with each test method (ie. set(), call())
* Hence using static variable to track hooks across all instances
*/
public static $hooksFromTrait = [];
public $foo = 'bar';
public function save()
{
//
}
public function render()
{
return view('show-name', ['name' => $this->foo]);
}
}
trait TraitForComponentWithComponentHooks
{
public function bootTraitForComponentWithComponentHooks()
{
$this->hooks[] = 'boottrait';
}
public function mountTraitForComponentWithComponentHooks()
{
$this->hooks[] = 'mounttrait';
}
public function bootedTraitForComponentWithComponentHooks()
{
$this->hooks[] = 'bootedtrait';
}
public function hydrateTraitForComponentWithComponentHooks()
{
$this->hooks[] = 'hydratetrait';
}
public function dehydrateTraitForComponentWithComponentHooks()
{
$this->hooks[] = 'dehydratetrait';
}
public function updatingTraitForComponentWithComponentHooks($name, $value)
{
$this->hooks[] = 'updatingtrait:'.$name.$value;
}
public function updatedTraitForComponentWithComponentHooks($name, $value)
{
$this->hooks[] = 'updatedtrait:'.$name.$value;
}
public function renderingTraitForComponentWithComponentHooks()
{
$this->hooks[] = 'renderingtrait';
}
public function renderedTraitForComponentWithComponentHooks($view)
{
$this->hooks[] = 'renderedtrait:'.$view->getName();
}
public function initializeTraitForComponentWithComponentHooks()
{$this->hooks[] = 'initializedtrait';
}
public function exceptionTraitForComponentWithComponentHooks($e, $stopPropagation) {
if($e instanceof CustomException) {
$this->hooks[] = 'exceptiontrait';
$stopPropagation();
}
}
}
class ComponentWithTraitStubAndComponentLifecycleHooks extends Component
{
use TraitForComponentWithComponentHooks;
public $hooks = [];
public $foo = 'bar';
public function boot()
{
// Reset from previous requests.
$this->hooks = [];
$this->hooks[] = 'bootcomponent';
}
public function mount()
{
$this->hooks[] = 'mountcomponent';
}
public function booted()
{
$this->hooks[] = 'bootedcomponent';
}
public function hydrate()
{
$this->hooks[] = 'hydratecomponent';
}
public function dehydrate()
{
$this->hooks[] = 'dehydratecomponent';
}
public function updating($name, $value)
{
$this->hooks[] = 'updatingcomponent:'.$name.$value;
}
public function updated($name, $value)
{
$this->hooks[] = 'updatedcomponent:'.$name.$value;
}
public function rendering()
{
$this->hooks[] = 'renderingcomponent';
}
public function rendered($view)
{
$this->hooks[] = 'renderedcomponent:'.$view->getName();
}
public function initialize()
{
// Reset from previous requests.
$this->hooks = [];
$this->hooks[] = 'initializedcomponent';
}
public function exception($e, $stopPropagation) {
if($e instanceof CustomException) {
$this->hooks[] = 'exceptioncomponent';
$stopPropagation();
}
}
public function render()
{
$this->hooks[] = 'rendercomponent';
return view('show-name', ['name' => $this->foo]);
}
public function testExceptionInterceptor()
{
throw new CustomException;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLifecycleHooks/DirectlyCallingLifecycleHooksNotAllowedException.php | src/Features/SupportLifecycleHooks/DirectlyCallingLifecycleHooksNotAllowedException.php | <?php
namespace Livewire\Features\SupportLifecycleHooks;
use Livewire\Exceptions\BypassViewHandler;
class DirectlyCallingLifecycleHooksNotAllowedException extends \Exception
{
use BypassViewHandler;
public function __construct($method, $component)
{
parent::__construct(
"Unable to call lifecycle method [{$method}] directly on component: [{$component}]"
);
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLifecycleHooks/UnitTest.php | src/Features/SupportLifecycleHooks/UnitTest.php | <?php
namespace Livewire\Features\SupportLifecycleHooks;
use Illuminate\Support\Stringable;
use Livewire\Component;
use Livewire\Livewire;
use PHPUnit\Framework\Assert as PHPUnit;
use Tests\TestComponent;
class UnitTest extends \Tests\TestCase
{
public function test_cant_call_protected_lifecycle_hooks()
{
$this->assertTrue(
collect([
'mount',
'hydrate',
'hydrateFoo',
'dehydrate',
'dehydrateFoo',
'updating',
'updatingFoo',
'updated',
'updatedFoo',
'scriptSrc',
])->every(function ($method) {
return $this->cannotCallMethod($method);
})
);
}
protected function cannotCallMethod($method)
{
try {
Livewire::test(ForProtectedLifecycleHooks::class)->call($method);
} catch (DirectlyCallingLifecycleHooksNotAllowedException $e) {
return true;
}
return false;
}
public function test_boot_method_is_called_on_mount_and_on_subsequent_updates()
{
Livewire::test(ComponentWithBootMethod::class)
->assertSetStrict('memo', 'bootmountbooted')
->call('$refresh')
->assertSetStrict('memo', 'boothydratebooted');
}
public function test_boot_method_can_be_added_to_trait()
{
Livewire::test(ComponentWithBootTrait::class)
->assertSetStrict('memo', 'boottraitboottraitinitializemountbootedtraitbooted')
->call('$refresh')
->assertSetStrict('memo', 'boottraitboottraitinitializehydratebootedtraitbooted');
}
public function test_boot_method_supports_dependency_injection()
{
Livewire::test(ComponentWithBootMethodDI::class)
->assertSetStrict('memo', 'boottraitbootbootedtraitbooted')
->call('$refresh')
->assertSetStrict('memo', 'boottraitbootbootedtraitbooted');
}
public function test_it_resolves_the_mount_parameters()
{
$component = Livewire::test(ComponentWithOptionalParameters::class);
$this->assertSame(null, $component->foo);
$this->assertSame([], $component->bar);
$component = Livewire::test(ComponentWithOptionalParameters::class, ['foo' => 'caleb']);
$this->assertSame('caleb', $component->foo);
$this->assertSame([], $component->bar);
$component = Livewire::test(ComponentWithOptionalParameters::class, ['bar' => 'porzio']);
$this->assertSame(null, $component->foo);
$this->assertSame('porzio', $component->bar);
$component = Livewire::test(ComponentWithOptionalParameters::class, ['foo' => 'caleb', 'bar' => 'porzio']);
$this->assertSame('caleb', $component->foo);
$this->assertSame('porzio', $component->bar);
$component = Livewire::test(ComponentWithOptionalParameters::class, ['foo' => null, 'bar' => null]);
$this->assertSame(null, $component->foo);
$this->assertSame(null, $component->bar);
}
public function test_it_sets_missing_dynamically_passed_in_parameters_to_null()
{
$fooBar = ['foo' => 10, 'bar' => 5];
$componentWithFooBar = Livewire::test(ComponentWithOptionalParameters::class, $fooBar);
$componentWithOnlyFoo = Livewire::test(ComponentWithOnlyFooParameter::class, $fooBar);
$this->assertSame(10, $componentWithFooBar->foo);
$this->assertSame(10, $componentWithOnlyFoo->foo);
$this->assertSame(5, $componentWithFooBar->bar);
$this->assertSame(null, data_get($componentWithOnlyFoo->instance(), 'bar'));
}
public function test_mount_hook()
{
$component = Livewire::test(ForLifecycleHooks::class);
$this->assertEquals([
'mount' => true,
'hydrate' => 0,
'hydrateFoo' => 0,
'rendering' => 1,
'rendered' => 1,
'dehydrate' => 1,
'dehydrateFoo' => 1,
'updating' => false,
'updated' => false,
'updatingFoo' => false,
'updatedFoo' => false,
'updatingBar' => false,
'updatingBarBaz' => false,
'updatedBar' => false,
'updatedBarBaz' => false,
], $component->lifecycles);
}
public function test_update_property()
{
$component = Livewire::test(ForLifecycleHooks::class, [
'expected' => [
'updating' => [[
'foo' => 'bar',
]],
'updated' => [[
'foo' => 'bar',
]],
'updatingFoo' => ['bar'],
'updatedFoo' => ['bar'],
]
])->set('foo', 'bar');
$this->assertEquals([
'mount' => true,
'hydrate' => 1,
'hydrateFoo' => 1,
'rendering' => 2,
'rendered' => 2,
'dehydrate' => 2,
'dehydrateFoo' => 2,
'updating' => true,
'updated' => true,
'updatingFoo' => true,
'updatedFoo' => true,
'updatingBar' => false,
'updatingBarBaz' => false,
'updatedBar' => false,
'updatedBarBaz' => false,
], $component->lifecycles);
}
public function test_update_nested_properties()
{
$component = Livewire::test(ForLifecycleHooks::class, [
'expected' => [
'updating' => [
['bar.foo' => 'baz',],
['bar.cocktail.soft' => 'Shirley Ginger'],
['bar.cocktail.soft' => 'Shirley Cumin']
],
'updated' => [
['bar.foo' => 'baz',],
['bar.cocktail.soft' => 'Shirley Ginger'],
['bar.cocktail.soft' => 'Shirley Cumin']
],
'updatingBar' => [
['foo' => [null, 'baz']],
['cocktail.soft' => [null, 'Shirley Ginger']],
['cocktail.soft' => ['Shirley Ginger', 'Shirley Cumin']]
],
'updatedBar' => [
['foo' => 'baz'],
['cocktail.soft' => 'Shirley Ginger'],
['cocktail.soft' => 'Shirley Cumin']
],
],
]);
$component->set('bar.foo', 'baz');
$component->set('bar.cocktail.soft', 'Shirley Ginger');
$component->set('bar.cocktail.soft', 'Shirley Cumin');
$this->assertEquals([
'mount' => true,
'hydrate' => 3,
'hydrateFoo' => 3,
'rendering' => 4,
'rendered' => 4,
'dehydrate' => 4,
'dehydrateFoo' => 4,
'updating' => true,
'updated' => true,
'updatingFoo' => false,
'updatedFoo' => false,
'updatingBar' => true,
'updatingBarBaz' => false,
'updatedBar' => true,
'updatedBarBaz' => false,
], $component->lifecycles);
}
public function test_update_nested_properties_with_nested_update_hook()
{
$component = Livewire::test(ForLifecycleHooks::class, [
'expected' => [
'updating' => [
['bar.baz' => 'bop'],
],
'updated' => [
['bar.baz' => 'bop'],
],
'updatingBar' => [
['baz' => [null, 'bop']],
],
'updatedBar' => [
['baz' => 'bop'],
],
'updatingBarBaz' => [
['baz' => [null, 'bop']],
],
'updatedBarBaz' => [
['baz' => 'bop'],
],
]
]);
$component->set('bar.baz', 'bop');
$this->assertEquals([
'mount' => true,
'hydrate' => true,
'hydrateFoo' => true,
'rendering' => true,
'rendered' => true,
'dehydrate' => true,
'dehydrateFoo' => true,
'updating' => true,
'updated' => true,
'updatingFoo' => false,
'updatedFoo' => false,
'updatingBar' => true,
'updatingBarBaz' => true,
'updatedBar' => true,
'updatedBarBaz' => true,
], $component->lifecycles);
}
}
class ForProtectedLifecycleHooks extends TestComponent
{
public function mount()
{
//
}
public function hydrate()
{
//
}
public function hydrateFoo()
{
//
}
public function dehydrate()
{
//
}
public function dehydrateFoo()
{
//
}
public function updating($name, $value)
{
//
}
public function updated($name, $value)
{
//
}
public function updatingFoo($value)
{
//
}
public function updatedFoo($value)
{
//
}
public function scriptSrc()
{
//
}
}
class ComponentWithBootMethod extends Component
{
// Use protected property to record all memo's
// as hydrating memo wipes out changes from boot
protected $_memo = '';
public $memo = '';
public function boot()
{
$this->_memo .= 'boot';
}
public function mount()
{
$this->_memo .= 'mount';
}
public function hydrate()
{
$this->_memo .= 'hydrate';
}
public function booted()
{
$this->_memo .= 'booted';
}
public function render()
{
$this->memo = $this->_memo;
return view('null-view');
}
}
class ComponentWithBootTrait extends Component
{
use BootMethodTrait;
// Use protected property to record all memo's
// as hydrating memo wipes out changes from boot
protected $_memo = '';
public $memo = '';
public function boot()
{
$this->_memo .= 'boot';
}
public function mount()
{
$this->_memo .= 'mount';
}
public function hydrate()
{
$this->_memo .= 'hydrate';
}
public function booted()
{
$this->_memo .= 'booted';
}
public function render()
{
$this->memo = $this->_memo;
return view('null-view');
}
}
trait BootMethodTrait
{
public function bootBootMethodTrait()
{
$this->_memo .= 'traitboot';
}
public function initializeBootMethodTrait()
{
$this->_memo .= 'traitinitialize';
}
public function bootedBootMethodTrait()
{
$this->_memo .= 'traitbooted';
}
}
trait BootMethodTraitWithDI
{
public function bootBootMethodTraitWithDI(Stringable $string)
{
$this->_memo .= $string->append('traitboot');
}
public function bootedBootMethodTraitWithDI(Stringable $string)
{
$this->_memo .= $string->append('traitbooted');
}
}
class ComponentWithBootMethodDI extends Component
{
use BootMethodTraitWithDI;
// Use protected property to record all memo's
// as hydrating memo wipes out changes from boot
protected $_memo = '';
public $memo = '';
public function boot(Stringable $string)
{
$this->_memo .= $string->append('boot');
}
public function booted(Stringable $string)
{
$this->_memo .= $string->append('booted');
}
public function render()
{
$this->memo = $this->_memo;
return view('null-view');
}
}
class ComponentWithOptionalParameters extends TestComponent
{
public $foo;
public $bar;
public function mount($foo = null, $bar = [])
{
$this->foo = $foo;
$this->bar = $bar;
}
}
class ComponentWithOnlyFooParameter extends TestComponent
{
public $foo;
public function mount($foo = null)
{
$this->foo = $foo;
}
}
class ComponentWithoutMount extends TestComponent
{
public $foo = 0;
}
class ForLifecycleHooks extends TestComponent
{
public $foo;
public $baz;
public $bar = [];
public $expected;
public $lifecycles = [
'mount' => false,
'hydrate' => 0,
'hydrateFoo' => 0,
'rendering' => 0,
'rendered' => 0,
'dehydrate' => 0,
'dehydrateFoo' => 0,
'updating' => false,
'updated' => false,
'updatingFoo' => false,
'updatedFoo' => false,
'updatingBar' => false,
'updatingBarBaz' => false,
'updatedBar' => false,
'updatedBarBaz' => false,
];
public function mount(array $expected = [])
{
$this->expected = $expected;
$this->lifecycles['mount'] = true;
}
public function hydrate()
{
$this->lifecycles['hydrate']++;
}
public function hydrateFoo()
{
$this->lifecycles['hydrateFoo']++;
}
public function dehydrate()
{
$this->lifecycles['dehydrate']++;
}
public function dehydrateFoo()
{
$this->lifecycles['dehydrateFoo']++;
}
public function updating($name, $value)
{
PHPUnit::assertEquals(array_shift($this->expected['updating']), [$name => $value]);
$this->lifecycles['updating'] = true;
}
public function updated($name, $value)
{
PHPUnit::assertEquals(array_shift($this->expected['updated']), [$name => $value]);
$this->lifecycles['updated'] = true;
}
public function updatingFoo($value)
{
PHPUnit::assertEquals(array_shift($this->expected['updatingFoo']), $value);
$this->lifecycles['updatingFoo'] = true;
}
public function updatedFoo($value)
{
PHPUnit::assertEquals(array_shift($this->expected['updatedFoo']), $value);
$this->lifecycles['updatedFoo'] = true;
}
public function updatingBar($value, $key)
{
$expected = array_shift($this->expected['updatingBar']);
$expected_key = array_keys($expected)[0];
$expected_value = $expected[$expected_key];
[$before, $after] = $expected_value;
PHPUnit::assertNotInstanceOf(Stringable::class, $key);
PHPUnit::assertEquals($expected_key, $key);
PHPUnit::assertEquals($before, data_get($this->bar, $key));
PHPUnit::assertEquals($after, $value);
$this->lifecycles['updatingBar'] = true;
}
public function updatedBar($value, $key)
{
$expected = array_shift($this->expected['updatedBar']);
$expected_key = array_keys($expected)[0];
$expected_value = $expected[$expected_key];
PHPUnit::assertNotInstanceOf(Stringable::class, $key);
PHPUnit::assertEquals($expected_key, $key);
PHPUnit::assertEquals($expected_value, $value);
PHPUnit::assertEquals($expected_value, data_get($this->bar, $key));
$this->lifecycles['updatedBar'] = true;
}
public function updatingBarBaz($value, $key)
{
$expected = array_shift($this->expected['updatingBarBaz']);
$expected_key = array_keys($expected)[0];
$expected_value = $expected[$expected_key];
[$before, $after] = $expected_value;
PHPUnit::assertNotInstanceOf(Stringable::class, $key);
PHPUnit::assertEquals($expected_key, $key);
PHPUnit::assertEquals($before, data_get($this->bar, $key));
PHPUnit::assertEquals($after, $value);
$this->lifecycles['updatingBarBaz'] = true;
}
public function updatedBarBaz($value, $key)
{
$expected = array_shift($this->expected['updatedBarBaz']);
$expected_key = array_keys($expected)[0];
$expected_value = $expected[$expected_key];
PHPUnit::assertNotInstanceOf(Stringable::class, $key);
PHPUnit::assertEquals($expected_key, $key);
PHPUnit::assertEquals($expected_value, $value);
PHPUnit::assertEquals($expected_value, data_get($this->bar, $key));
$this->lifecycles['updatedBarBaz'] = true;
}
public function rendering()
{
$this->lifecycles['rendering']++;
}
public function rendered()
{
$this->lifecycles['rendered']++;
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLifecycleHooks/SupportLifecycleHooks.php | src/Features/SupportLifecycleHooks/SupportLifecycleHooks.php | <?php
namespace Livewire\Features\SupportLifecycleHooks;
use function Livewire\store;
use function Livewire\wrap;
use Livewire\ComponentHook;
class SupportLifecycleHooks extends ComponentHook
{
// Performance optimization: Cache trait lookups per component class...
protected static $traitCache = [];
// Performance optimization: Cache method existence checks per component class...
protected static $methodCache = [];
public function mount($params)
{
if (store($this->component)->has('skipMount')) { return; }
$this->callHook('boot');
$this->callTraitHook('boot');
$this->callTraitHook('initialize');
$this->callHook('mount', $params);
$this->callTraitHook('mount', $params);
$this->callHook('booted');
$this->callTraitHook('booted');
}
public function hydrate()
{
if (store($this->component)->has('skipHydrate')) { return; }
$this->callHook('boot');
$this->callTraitHook('boot');
$this->callTraitHook('initialize');
$this->callHook('hydrate');
$this->callTraitHook('hydrate');
// Call "hydrateXx" hooks for each property...
foreach ($this->getProperties() as $property => $value) {
$this->callHook('hydrate'.str($property)->studly(), [$value]);
}
$this->callHook('booted');
$this->callTraitHook('booted');
}
public function update($propertyName, $fullPath, $newValue)
{
$name = str($fullPath);
$propertyName = $name->studly()->before('.');
$keyAfterFirstDot = $name->contains('.') ? $name->after('.')->__toString() : null;
$keyAfterLastDot = $name->contains('.') ? $name->afterLast('.')->__toString() : null;
$beforeMethod = 'updating'.$propertyName;
$afterMethod = 'updated'.$propertyName;
$beforeNestedMethod = $name->contains('.')
? 'updating'.$name->replace('.', '_')->studly()
: false;
$afterNestedMethod = $name->contains('.')
? 'updated'.$name->replace('.', '_')->studly()
: false;
$this->callHook('updating', [$fullPath, $newValue]);
$this->callTraitHook('updating', [$fullPath, $newValue]);
$this->callHook($beforeMethod, [$newValue, $keyAfterFirstDot]);
$this->callHook($beforeNestedMethod, [$newValue, $keyAfterLastDot]);
return function () use ($fullPath, $afterMethod, $afterNestedMethod, $keyAfterFirstDot, $keyAfterLastDot, $newValue) {
$this->callHook('updated', [$fullPath, $newValue]);
$this->callTraitHook('updated', [$fullPath, $newValue]);
$this->callHook($afterMethod, [$newValue, $keyAfterFirstDot]);
$this->callHook($afterNestedMethod, [$newValue, $keyAfterLastDot]);
};
}
public function call($methodName, $params, $returnEarly, $metadata)
{
$protectedMethods = [
'mount',
'exception',
'hydrate*',
'dehydrate*',
'updating*',
'updated*',
'scriptSrc',
];
throw_if(
str($methodName)->is($protectedMethods),
new DirectlyCallingLifecycleHooksNotAllowedException($methodName, $this->component->getName())
);
$this->callTraitHook('call', ['methodName' => $methodName, 'params' => $params, 'returnEarly' => $returnEarly, 'metadata' => $metadata]);
}
public function exception($e, $stopPropagation)
{
$this->callHook('exception', ['e' => $e, 'stopPropagation' => $stopPropagation]);
$this->callTraitHook('exception', ['e' => $e, 'stopPropagation' => $stopPropagation]);
}
public function render($view, $data)
{
$this->callHook('rendering', ['view' => $view, 'data' => $data]);
$this->callTraitHook('rendering', ['view' => $view, 'data' => $data]);
return function ($html) use ($view) {
$this->callHook('rendered', ['view' => $view, 'html' => $html]);
$this->callTraitHook('rendered', ['view' => $view, 'html' => $html]);
};
}
public function dehydrate()
{
$this->callHook('dehydrate');
$this->callTraitHook('dehydrate');
// Call "dehydrateXx" hooks for each property...
foreach ($this->getProperties() as $property => $value) {
$this->callHook('dehydrate'.str($property)->studly(), [$value]);
}
}
public function callHook($name, $params = [])
{
// Performance optimization: Cache method existence checks
$class = get_class($this->component);
$cacheKey = "{$class}::{$name}";
if (!isset(static::$methodCache[$cacheKey])) {
static::$methodCache[$cacheKey] = method_exists($this->component, $name);
}
if (static::$methodCache[$cacheKey]) {
wrap($this->component)->__call($name, $params);
}
}
function callTraitHook($name, $params = [])
{
// Performance optimization: Cache trait lookups per component class
$class = get_class($this->component);
if (!isset(static::$traitCache[$class])) {
static::$traitCache[$class] = class_uses_recursive($this->component);
}
foreach (static::$traitCache[$class] as $trait) {
$method = $name.class_basename($trait);
// Performance optimization: Cache method existence checks
$cacheKey = "{$class}::{$method}";
if (!isset(static::$methodCache[$cacheKey])) {
static::$methodCache[$cacheKey] = method_exists($this->component, $method);
}
if (static::$methodCache[$cacheKey]) {
wrap($this->component)->$method(...$params);
}
}
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Json.php | src/Attributes/Json.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportJson\BaseJson;
#[\Attribute(\Attribute::TARGET_METHOD)]
class Json extends BaseJson
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Isolate.php | src/Attributes/Isolate.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportIsolating\BaseIsolate;
#[\Attribute]
class Isolate extends BaseIsolate
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Computed.php | src/Attributes/Computed.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportComputed\BaseComputed;
#[\Attribute]
class Computed extends BaseComputed
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Lazy.php | src/Attributes/Lazy.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportLazyLoading\BaseLazy;
#[\Attribute]
class Lazy extends BaseLazy
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Reactive.php | src/Attributes/Reactive.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportReactiveProps\BaseReactive;
#[\Attribute]
class Reactive extends BaseReactive
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Modelable.php | src/Attributes/Modelable.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportWireModelingNestedComponents\BaseModelable;
#[\Attribute]
class Modelable extends BaseModelable
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Renderless.php | src/Attributes/Renderless.php | <?php
namespace Livewire\Attributes;
use Livewire\Mechanisms\HandleComponents\BaseRenderless;
#[\Attribute]
class Renderless extends BaseRenderless
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Defer.php | src/Attributes/Defer.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportLazyLoading\BaseDefer;
#[\Attribute]
class Defer extends BaseDefer
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Url.php | src/Attributes/Url.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportQueryString\BaseUrl;
#[\Attribute]
class Url extends BaseUrl
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Layout.php | src/Attributes/Layout.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportPageComponents\BaseLayout;
#[\Attribute]
class Layout extends BaseLayout
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Title.php | src/Attributes/Title.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportPageComponents\BaseTitle;
#[\Attribute]
class Title extends BaseTitle
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Locked.php | src/Attributes/Locked.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportLockedProperties\BaseLocked;
#[\Attribute]
class Locked extends BaseLocked
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/On.php | src/Attributes/On.php | <?php
namespace Livewire\Attributes;
use Attribute;
use Livewire\Features\SupportEvents\BaseOn;
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class On extends BaseOn
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Validate.php | src/Attributes/Validate.php | <?php
namespace Livewire\Attributes;
use Attribute;
use Livewire\Features\SupportValidation\BaseValidate;
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_ALL)]
class Validate extends BaseValidate
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Async.php | src/Attributes/Async.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportAsync\BaseAsync;
#[\Attribute]
class Async extends BaseAsync
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Js.php | src/Attributes/Js.php | <?php
namespace Livewire\Attributes;
use Livewire\Features\SupportJsEvaluation\BaseJs;
#[\Attribute]
class Js extends BaseJs
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Session.php | src/Attributes/Session.php | <?php
namespace Livewire\Attributes;
use Attribute;
use Livewire\Features\SupportSession\BaseSession;
#[Attribute(Attribute::TARGET_PROPERTY)]
class Session extends BaseSession
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Attributes/Rule.php | src/Attributes/Rule.php | <?php
namespace Livewire\Attributes;
use Attribute;
use Livewire\Features\SupportValidation\BaseRule;
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_ALL)]
class Rule extends BaseRule
{
//
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Factory/UnitTest.php | src/Factory/UnitTest.php | <?php
namespace Livewire\Factory;
use Livewire\Factory\Fixtures\SimpleComponent;
use Illuminate\Support\Facades\File;
use Livewire\Compiler\CacheManager;
use Livewire\Compiler\Compiler;
use Livewire\Finder\Finder;
use Livewire\Component;
class UnitTest extends \Tests\TestCase
{
protected $tempPath;
protected $cacheDir;
public function setUp(): void
{
parent::setUp();
$this->tempPath = sys_get_temp_dir() . '/livewire_compiler_test_' . uniqid();
$this->cacheDir = $this->tempPath . '/cache';
File::makeDirectory($this->tempPath, 0755, true);
File::makeDirectory($this->cacheDir, 0755, true);
}
protected function tearDown(): void
{
if (File::exists($this->tempPath)) {
File::deleteDirectory($this->tempPath);
}
parent::tearDown();
}
public function test_can_create_simple_class_based_component()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addLocation(classNamespace: 'Livewire\Factory\Fixtures');
$component = $factory->create('simple-component');
$this->assertInstanceOf(SimpleComponent::class, $component);
$this->assertEquals('simple-component', $component->getName());
$this->assertNotNull($component->getId());
}
public function test_can_create_simple_class_based_component_with_custom_id()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addLocation(classNamespace: 'Livewire\Factory\Fixtures');
$customId = 'custom-component-id';
$component = $factory->create('simple-component', $customId);
$this->assertInstanceOf(SimpleComponent::class, $component);
$this->assertEquals('simple-component', $component->getName());
$this->assertEquals($customId, $component->getId());
}
public function test_can_create_component_from_class_name()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addComponent(SimpleComponent::class);
$component = $factory->create(SimpleComponent::class);
$this->assertInstanceOf(SimpleComponent::class, $component);
}
public function test_can_create_component_from_class_instance()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addComponent(SimpleComponent::class);
$existingComponent = new SimpleComponent();
$component = $factory->create($existingComponent);
$this->assertInstanceOf(SimpleComponent::class, $component);
$this->assertNotSame($existingComponent, $component); // Should be a new instance
}
public function test_can_create_and_render_single_file_component()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addLocation(viewPath: __DIR__ . '/Fixtures');
$component = $factory->create('simple-single-file-component');
$this->assertInstanceOf(Component::class, $component);
$this->assertEquals('simple-single-file-component', $component->getName());
$this->assertNotNull($component->getId());
}
public function test_can_create_multi_file_component()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addLocation(viewPath: __DIR__ . '/Fixtures');
$component = $factory->create('simple-multi-file-component');
$this->assertInstanceOf(Component::class, $component);
$this->assertEquals('simple-multi-file-component', $component->getName());
$this->assertNotNull($component->getId());
}
public function test_can_resolve_missing_component()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addComponent(SimpleComponent::class);
$factory->resolveMissingComponent(function ($name) {
if ($name === 'missing-component') {
return SimpleComponent::class;
}
return null;
});
$existingComponent = new SimpleComponent();
$component = $factory->create('missing-component');
$this->assertInstanceOf(SimpleComponent::class, $component);
$this->assertNotSame($existingComponent, $component); // Should be a new instance
}
public function test_can_determine_if_component_exists()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addLocation(classNamespace: 'Livewire\Factory\Fixtures');
$this->assertTrue($factory->exists('simple-component'));
$this->assertFalse($factory->exists('missing-component'));
}
public function test_can_resolve_component_class()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addLocation(classNamespace: 'Livewire\Factory\Fixtures');
$component = $factory->create('simple-component');
$this->assertEquals(SimpleComponent::class, $factory->resolveComponentClass('simple-component'));
// $this->assertEquals(SimpleComponent::class, $factory->resolveComponentClass(SimpleComponent::class));
// $this->assertEquals(SimpleComponent::class, $factory->resolveComponentClass($component));
}
public function test_can_resolve_component_name()
{
$finder = new Finder();
$compiler = new Compiler(new CacheManager($this->cacheDir));
$factory = new Factory($finder, $compiler);
$finder->addLocation(classNamespace: 'Livewire\Factory\Fixtures');
$component = $factory->create('simple-component');
$this->assertEquals('simple-component', $factory->resolveComponentName('simple-component'));
$this->assertEquals('simple-component', $factory->resolveComponentName(SimpleComponent::class));
$this->assertEquals('simple-component', $factory->resolveComponentName($component));
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Factory/Factory.php | src/Factory/Factory.php | <?php
namespace Livewire\Factory;
use Livewire\Exceptions\ComponentNotFoundException;
use Livewire\Compiler\Compiler;
use Livewire\Finder\Finder;
use Livewire\Component;
class Factory
{
protected $missingComponentResolvers = [];
protected $resolvedComponentCache = [];
public function __construct(
protected Finder $finder,
protected Compiler $compiler,
) {}
public function create($name, $id = null): Component
{
[$name, $class] = $this->resolveComponentNameAndClass($name);
$component = new $class;
$component->setId($id ?: str()->random(20));
$component->setName($name);
return $component;
}
public function resolveMissingComponent($resolver): void
{
$this->missingComponentResolvers[] = $resolver;
}
public function resolveComponentNameAndClass($name): array
{
$name = $this->finder->normalizeName($name);
$class = null;
if (isset($this->resolvedComponentCache[$name])) {
return [$name, $this->resolvedComponentCache[$name]];
}
if ($name) {
$class = $this->finder->resolveClassComponentClassName($name);
if (! $class) {
$path = $this->finder->resolveMultiFileComponentPath($name);
if (! $path) {
$path = $this->finder->resolveSingleFileComponentPath($name);
}
if ($path) {
$class = $this->compiler->compile($path);
}
}
}
if (! $class || ! class_exists($class) || ! is_subclass_of($class, Component::class)) {
foreach ($this->missingComponentResolvers as $resolver) {
if ($class = $resolver($name)) {
$this->finder->addComponent($name, $class);
break;
}
}
}
if (! $class || ! class_exists($class) || ! is_subclass_of($class, Component::class)) {
throw new ComponentNotFoundException(
"Unable to find component: [{$name}]"
);
}
$this->resolvedComponentCache[$name] = $class;
return [$name, $class];
}
public function resolveComponentClass($name): string
{
[$name, $class] = $this->resolveComponentNameAndClass($name);
return $class;
}
public function resolveComponentName($name): string
{
$component = $this->create($name);
return $component->getName();
}
public function exists($name): bool
{
try {
$this->create($name);
return true;
} catch (ComponentNotFoundException $e) {
return false;
}
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Factory/Fixtures/simple-single-file-component.blade.php | src/Factory/Fixtures/simple-single-file-component.blade.php | <?php
use Livewire\Component;
new class extends Component
{
public $message = 'Hello from Single File Component';
};
?>
<div>Single File Component View</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Factory/Fixtures/SimpleComponent.php | src/Factory/Fixtures/SimpleComponent.php | <?php
namespace Livewire\Factory\Fixtures;
use Livewire\Component;
class SimpleComponent extends Component
{
public $message = 'Hello World';
public function render()
{
return '<div>{{ $message }}</div>';
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Factory/Fixtures/simple-multi-file-component/simple-multi-file-component.blade.php | src/Factory/Fixtures/simple-multi-file-component/simple-multi-file-component.blade.php | <div>Multi File Component View: {{ $title }}</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Factory/Fixtures/simple-multi-file-component/simple-multi-file-component.php | src/Factory/Fixtures/simple-multi-file-component/simple-multi-file-component.php | <?php
use Livewire\Component;
new class extends Component
{
public $title = 'Hello from Multi File Component';
};
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/TestCase.php | tests/TestCase.php | <?php
namespace Tests;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\RateLimiter;
use Orchestra\Testbench\Dusk\Options;
class TestCase extends \Orchestra\Testbench\Dusk\TestCase
{
public function setUp(): void
{
$this->afterApplicationCreated(function () {
$this->makeACleanSlate();
if (env('DUSK_HEADLESS_DISABLED', true) == false) {
Options::withoutUI();
}
});
$this->beforeApplicationDestroyed(function () {
$this->makeACleanSlate();
});
parent::setUp();
}
public function makeACleanSlate()
{
Artisan::call('view:clear');
app()->forgetInstance('livewire.factory');
// Clear checksum failure rate limits
RateLimiter::clear('livewire-checksum-failures:127.0.0.1');
File::deleteDirectory($this->livewireViewsPath());
File::deleteDirectory($this->livewireClassesPath());
File::deleteDirectory($this->livewireComponentsPath());
File::deleteDirectory($this->livewireTestsPath());
File::delete(app()->bootstrapPath('cache/livewire-components.php'));
}
protected function getPackageProviders($app)
{
return [
\Livewire\LivewireServiceProvider::class,
];
}
protected function defineEnvironment($app)
{
$app['config']->set('view.paths', [
__DIR__.'/views',
resource_path('views'),
]);
// Override layout and page namespaces to use the test views instead of testbench's...
$app['view']->addNamespace('layouts', __DIR__.'/views/layouts');
$app['view']->addNamespace('pages', __DIR__.'/views/pages');
$app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8=');
$app['config']->set('database.default', 'testbench');
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
$app['config']->set('filesystems.disks.unit-downloads', [
'driver' => 'local',
'root' => __DIR__.'/fixtures',
]);
}
protected function livewireClassesPath($path = '')
{
return app_path('Livewire'.($path ? '/'.$path : ''));
}
protected function livewireViewsPath($path = '')
{
return resource_path('views').'/livewire'.($path ? '/'.$path : '');
}
protected function livewireComponentsPath($path = '')
{
return resource_path('views').'/components'.($path ? '/'.$path : '');
}
protected function livewireTestsPath($path = '')
{
return base_path('tests/Feature/Livewire'.($path ? '/'.$path : ''));
}
protected function resolveApplication()
{
return parent::resolveApplication()->useEnvironmentPath(__DIR__.'/..');
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/TestComponent.php | tests/TestComponent.php | <?php
namespace Tests;
use Livewire\Component;
class TestComponent extends Component
{
function render()
{
return '<div></div>';
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/BrowserTestCase.php | tests/BrowserTestCase.php | <?php
namespace Tests;
use function Livewire\trigger;
class BrowserTestCase extends TestCase
{
public static function tweakApplicationHook() {
return function () {};
}
public function setUp(): void
{
parent::setUp();
trigger('browser.testCase.setUp', $this);
}
public function tearDown(): void
{
trigger('browser.testCase.tearDown', $this);
parent::tearDown();
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/show-children.blade.php | tests/views/show-children.blade.php | <div>
@foreach ($children as $child)
@livewire('child', ['name' => $child], key($child))
@endforeach
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/show-double-header-slot.blade.php | tests/views/show-double-header-slot.blade.php | <x-component-with-slot>
<x-slot name="header">
The component header
</x-slot>
</x-component-with-slot>
<div>
Hello World
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/dump-errors.blade.php | tests/views/dump-errors.blade.php | <div>
@json($errors->toArray())
@error('test') @enderror
@component('components.dump-errors-nested-component')@endcomponent
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/null-view.blade.php | tests/views/null-view.blade.php | <div></div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/execute-callback.blade.php | tests/views/execute-callback.blade.php | <div>
<?php $callback(); ?>
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/assets-directive.blade.php | tests/views/assets-directive.blade.php | @livewireStyles
@livewireScripts($options)
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/show-property-value.blade.php | tests/views/show-property-value.blade.php | <span>{{ $message }}</span>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/custom-pagination-theme.blade.php | tests/views/custom-pagination-theme.blade.php | <div>
<span>Custom pagination theme</span>
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/uses-component.blade.php | tests/views/uses-component.blade.php | <html>
<div>
{{ $variable }} -- <livewire:foo />
</div>
</html>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/load-balancer-parent.blade.php | tests/views/load-balancer-parent.blade.php | <div>
Parent
@livewire('child', ['number' => 1])
@livewire('child', ['number' => 2])
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/show-name.blade.php | tests/views/show-name.blade.php | <!-- Test comment <div>Commented out code</div> -->
<span>{{ $name ?? '' }}</span>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/show-errors.blade.php | tests/views/show-errors.blade.php | <div>
<h1>Errors test</h1>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/custom-simple-pagination-theme.blade.php | tests/views/custom-simple-pagination-theme.blade.php | <div>
<span>Custom simple pagination theme</span>
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/show-child.blade.php | tests/views/show-child.blade.php | <div>
@livewire('child', $child)
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/show-name-with-this.blade.php | tests/views/show-name-with-this.blade.php | <span>{{ $this->name }}</span>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/placeholder.blade.php | tests/views/placeholder.blade.php | <div id="loading">
Loading...
<div>{{ $myParameter }}</div>
</div> | php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/load-balancer-child.blade.php | tests/views/load-balancer-child.blade.php | <div>
child-content-{{ $number }}
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/render-component.blade.php | tests/views/render-component.blade.php | <div>
@isset($params)
@livewire($component, $params)
@else
@livewire($component)
@endisset
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/show-layout-slots.blade.php | tests/views/show-layout-slots.blade.php | <x-slot name="header">
<h2>I am a header - {{ $bar }}</h2>
</x-slot>
<div>
Hello World
</div>
<x-slot name="footer">
<div>
I am a footer - {{ $bar }}
</div>
</x-slot>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/components/component-with-slot.blade.php | tests/views/components/component-with-slot.blade.php | <div>
{{ $header ?? 'Default component title' }}
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/components/input.blade.php | tests/views/components/input.blade.php |
<div x-data="{ foo: @entangle($attributes->wire('model')) }"></div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/components/dump-errors-nested-component.blade.php | tests/views/components/dump-errors-nested-component.blade.php | <div>
@if (isset($errors) && $errors->has('bar')) sharedError:{{ $errors->first('bar') }} @endif
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/components/this-directive.blade.php | tests/views/components/this-directive.blade.php | <div>
@this
</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/components/basic-component.blade.php | tests/views/components/basic-component.blade.php | <div {{ $attributes }}>{{ $slot }}</div>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/components/layouts/custom.blade.php | tests/views/components/layouts/custom.blade.php | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<h1>This is a custom layout</h1>
{{ $slot }}
@stack('scripts')
</body>
</html>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/components/layouts/app.blade.php | tests/views/components/layouts/app.blade.php | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
@if (app('livewire')->isCspSafe())
<meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self';
style-src 'self' 'unsafe-inline';
object-src 'none';
">
@endif
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-extends.blade.php | tests/views/layouts/app-extends.blade.php | @yield('content')
{{ $bar }}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/data-test.blade.php | tests/views/layouts/data-test.blade.php | {{ $title }}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-custom-slot.blade.php | tests/views/layouts/app-custom-slot.blade.php | {{ $main }}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-anonymous-component.blade.php | tests/views/layouts/app-anonymous-component.blade.php | @props([
'foo' => 'bar',
])
<div {{ $attributes->merge(['id' => 'foo']) }}>
{{ $foo }}
</div>
{{ $slot }}
@isset($bar)
{{ $bar }}
@endisset
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-anonymous-component-with-required-prop.blade.php | tests/views/layouts/app-anonymous-component-with-required-prop.blade.php | @props([
'foo' => 'bar',
'bar',
])
<div {{$attributes}}>
{{ $foo }}
</div>
{{ $slot }}
{{ $bar }}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-with-bar.blade.php | tests/views/layouts/app-with-bar.blade.php | {{ $bar }}
{{ $slot }}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-with-title.blade.php | tests/views/layouts/app-with-title.blade.php | {{ $title }}
{{ $slot }}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-layout-with-slots.blade.php | tests/views/layouts/app-layout-with-slots.blade.php | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
{{ $header ?? 'No Header' }}
{{ $slot }}
{{ $footer ?? 'No Footer' }}
</body>
</html>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/old-app.blade.php | tests/views/layouts/old-app.blade.php | @yield('content')
{{ $slot }}{{ $customParam ?? '' }}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-custom-section.blade.php | tests/views/layouts/app-custom-section.blade.php | @yield('body')
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-from-class-component.blade.php | tests/views/layouts/app-from-class-component.blade.php | @yield('content')
{{ $slot }}
<div {{ $attributes->merge(['id' => 'foo']) }}>
{{ $foo }}
</div>
@isset($bar)
{{ $bar }}
@endisset
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-layout-with-stacks.blade.php | tests/views/layouts/app-layout-with-stacks.blade.php | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
@stack('styles')
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-from-class-component-with-properties.blade.php | tests/views/layouts/app-from-class-component-with-properties.blade.php | {{ $slot }}
{{ $foo }}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-with-baz-hardcoded.blade.php | tests/views/layouts/app-with-baz-hardcoded.blade.php | baz
{{ $slot }}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app-with-styles.blade.php | tests/views/layouts/app-with-styles.blade.php | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<style>
.show {
display: block;
}
</style>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/views/layouts/app.blade.php | tests/views/layouts/app.blade.php | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
@if (app('livewire')->isCspSafe())
<meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self';
style-src 'self' 'unsafe-inline';
object-src 'none';
">
@endif
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/Unit/Mechanisms/HandleComponents/ChecksumRateLimitTest.php | tests/Unit/Mechanisms/HandleComponents/ChecksumRateLimitTest.php | <?php
namespace Tests\Unit\Mechanisms\HandleComponents;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Mechanisms\HandleComponents\Checksum;
use Livewire\Mechanisms\HandleComponents\CorruptComponentPayloadException;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
use Tests\TestCase;
class ChecksumRateLimitTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
// Clear any existing rate limits before each test
RateLimiter::clear('livewire-checksum-failures:127.0.0.1');
}
public function test_checksum_failure_is_recorded()
{
$snapshot = [
'memo' => ['name' => 'test-component'],
'data' => ['foo' => 'bar'],
'checksum' => 'invalid-checksum',
];
try {
Checksum::verify($snapshot);
} catch (CorruptComponentPayloadException $e) {
// Expected
}
// Verify a hit was recorded
$this->assertEquals(1, RateLimiter::attempts('livewire-checksum-failures:127.0.0.1'));
}
public function test_multiple_failures_are_tracked()
{
$snapshot = [
'memo' => ['name' => 'test-component'],
'data' => ['foo' => 'bar'],
'checksum' => 'invalid-checksum',
];
for ($i = 0; $i < 5; $i++) {
try {
Checksum::verify($snapshot);
} catch (CorruptComponentPayloadException $e) {
// Expected
}
}
$this->assertEquals(5, RateLimiter::attempts('livewire-checksum-failures:127.0.0.1'));
}
public function test_blocks_after_max_failures()
{
$snapshot = [
'memo' => ['name' => 'test-component'],
'data' => ['foo' => 'bar'],
'checksum' => 'invalid-checksum',
];
// Hit the rate limit (10 failures)
for ($i = 0; $i < 10; $i++) {
try {
Checksum::verify($snapshot);
} catch (CorruptComponentPayloadException $e) {
// Expected
}
}
// Next attempt should throw TooManyRequestsHttpException
$this->expectException(TooManyRequestsHttpException::class);
$this->expectExceptionMessage('Too many invalid Livewire requests');
Checksum::verify($snapshot);
}
public function test_valid_checksum_does_not_record_failure()
{
$snapshot = [
'memo' => ['name' => 'test-component'],
'data' => ['foo' => 'bar'],
];
// Generate valid checksum
$snapshot['checksum'] = Checksum::generate($snapshot);
// This should not throw
Checksum::verify($snapshot);
// No failures should be recorded
$this->assertEquals(0, RateLimiter::attempts('livewire-checksum-failures:127.0.0.1'));
}
public function test_rate_limit_blocks_even_valid_requests_when_limit_exceeded()
{
// First, exceed the rate limit with invalid requests
$invalidSnapshot = [
'memo' => ['name' => 'test-component'],
'data' => ['foo' => 'bar'],
'checksum' => 'invalid-checksum',
];
for ($i = 0; $i < 10; $i++) {
try {
Checksum::verify($invalidSnapshot);
} catch (CorruptComponentPayloadException $e) {
// Expected
}
}
// Now try with a valid checksum - should still be blocked
$validSnapshot = [
'memo' => ['name' => 'test-component'],
'data' => ['foo' => 'bar'],
];
$validSnapshot['checksum'] = Checksum::generate($validSnapshot);
$this->expectException(TooManyRequestsHttpException::class);
Checksum::verify($validSnapshot);
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/Unit/Mechanisms/HandleComponents/NestingDepthTest.php | tests/Unit/Mechanisms/HandleComponents/NestingDepthTest.php | <?php
namespace Tests\Unit\Mechanisms\HandleComponents;
use Livewire\Component;
use Livewire\Livewire;
use Livewire\Exceptions\MaxNestingDepthExceededException;
use Tests\TestCase;
class NestingDepthTest extends TestCase
{
public function test_rejects_property_paths_exceeding_max_depth()
{
config()->set('livewire.payload.max_nesting_depth', 10);
$this->expectException(MaxNestingDepthExceededException::class);
$this->expectExceptionMessage('max_nesting_depth');
Livewire::test(NestingDepthComponent::class)
->set('data' . str_repeat('.a', 15), 'value'); // 16 levels
}
public function test_allows_property_paths_within_max_depth()
{
config()->set('livewire.payload.max_nesting_depth', 10);
$component = Livewire::test(NestingDepthComponent::class)
->set('data.level1.level2.level3', 'nested value'); // 4 levels
$this->assertEquals(
'nested value',
$component->get('data.level1.level2.level3')
);
}
public function test_allows_exactly_max_depth()
{
config()->set('livewire.payload.max_nesting_depth', 5);
$component = Livewire::test(NestingDepthComponent::class)
->set('data.a.b.c.d', 'value'); // Exactly 5 levels
$this->assertEquals('value', $component->get('data.a.b.c.d'));
}
public function test_rejects_one_over_max_depth()
{
config()->set('livewire.payload.max_nesting_depth', 5);
$this->expectException(MaxNestingDepthExceededException::class);
$this->expectExceptionMessage('max_nesting_depth');
Livewire::test(NestingDepthComponent::class)
->set('data.a.b.c.d.e', 'value'); // 6 levels
}
public function test_depth_limit_can_be_disabled()
{
config()->set('livewire.payload.max_nesting_depth', null);
// Should not throw even with very deep path
$component = Livewire::test(NestingDepthComponent::class)
->set('data' . str_repeat('.x', 20), 'deep value'); // 21 levels
// Just verify it didn't throw
$this->assertTrue(true);
}
public function test_depth_limit_can_be_customized()
{
config()->set('livewire.payload.max_nesting_depth', 3);
$this->expectException(MaxNestingDepthExceededException::class);
$this->expectExceptionMessage('max_nesting_depth');
Livewire::test(NestingDepthComponent::class)
->set('data.a.b.c', 'value'); // 4 levels, exceeds 3
}
public function test_single_level_property_always_works()
{
config()->set('livewire.payload.max_nesting_depth', 1);
$component = Livewire::test(NestingDepthComponent::class)
->set('data', ['foo' => 'bar']); // 1 level
$this->assertEquals(['foo' => 'bar'], $component->get('data'));
}
public function test_deep_nesting_attack_is_blocked_quickly()
{
config()->set('livewire.payload.max_nesting_depth', 10);
$start = microtime(true);
$exceptions = 0;
$component = Livewire::test(NestingDepthComponent::class);
// Attempt the attack from the vulnerability report
$prefix = 'data' . str_repeat('.a', 100); // 101 levels deep
for ($i = 0; $i < 100; $i++) {
try {
$component->set($prefix . $i, 1);
} catch (\Exception $e) {
$exceptions++;
}
}
$elapsed = microtime(true) - $start;
// All should have been rejected
$this->assertEquals(100, $exceptions);
// Should fail fast (< 1 second), not hang for 20 seconds
$this->assertLessThan(1, $elapsed, "Attack took {$elapsed} seconds - should be blocked instantly");
}
}
class NestingDepthComponent extends Component
{
public $data = [];
public function render()
{
return '<div></div>';
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/Unit/Mechanisms/HandleComponents/SecurityPolicyTest.php | tests/Unit/Mechanisms/HandleComponents/SecurityPolicyTest.php | <?php
namespace Tests\Unit\Mechanisms\HandleComponents;
use Illuminate\Console\Command;
use Livewire\Mechanisms\HandleComponents\SecurityPolicy;
class SecurityPolicyTest extends \Tests\TestCase
{
public function test_validates_safe_classes()
{
// Should not throw for regular classes
SecurityPolicy::validateClass(\stdClass::class);
SecurityPolicy::validateClass(\DateTime::class);
$this->assertTrue(true);
}
public function test_rejects_console_command_classes()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('is not allowed to be instantiated');
SecurityPolicy::validateClass(Command::class);
}
public function test_rejects_subclasses_of_denied_classes()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('is not allowed to be instantiated');
// Create an anonymous subclass of Command
$subclass = get_class(new class extends Command {
protected $signature = 'test';
});
SecurityPolicy::validateClass($subclass);
}
public function test_rejects_process_class()
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('is not allowed to be instantiated');
SecurityPolicy::validateClass(\Symfony\Component\Process\Process::class);
}
public function test_can_add_classes_to_denylist()
{
SecurityPolicy::denyClasses([\DateTimeImmutable::class]);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('is not allowed to be instantiated');
SecurityPolicy::validateClass(\DateTimeImmutable::class);
}
public function test_get_denied_classes_returns_list()
{
$denied = SecurityPolicy::getDeniedClasses();
$this->assertIsArray($denied);
$this->assertContains('Illuminate\Console\Command', $denied);
$this->assertContains('Symfony\Component\Process\Process', $denied);
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/Unit/Mechanisms/FrontendAssets/EndpointResolverIntegrationTest.php | tests/Unit/Mechanisms/FrontendAssets/EndpointResolverIntegrationTest.php | <?php
namespace Tests\Unit\Mechanisms\FrontendAssets;
use Livewire\Mechanisms\FrontendAssets\FrontendAssets;
use Livewire\Mechanisms\HandleRequests\EndpointResolver;
use Tests\TestCase;
class EndpointResolverIntegrationTest extends TestCase
{
public function test_script_route_uses_endpoint_resolver_path()
{
$expectedPath = EndpointResolver::scriptPath(minified: !config('app.debug'));
$frontendAssets = app(FrontendAssets::class);
$actualPath = '/' . ltrim($frontendAssets->javaScriptRoute->uri, '/');
$this->assertEquals($expectedPath, $actualPath);
}
public function test_script_url_in_html_matches_registered_route()
{
$frontendAssets = app(FrontendAssets::class);
$routeUri = '/' . ltrim($frontendAssets->javaScriptRoute->uri, '/');
$html = FrontendAssets::scripts();
// Extract src from script tag
preg_match('/src="([^"?]+)/', $html, $matches);
$srcPath = $matches[1] ?? '';
$this->assertEquals($routeUri, $srcPath);
}
public function test_update_uri_uses_endpoint_resolver_path()
{
$expectedPath = EndpointResolver::updatePath();
$actualPath = app('livewire')->getUpdateUri();
$this->assertEquals($expectedPath, $actualPath);
}
public function test_all_endpoints_use_same_prefix()
{
$prefix = EndpointResolver::prefix();
$this->assertStringStartsWith($prefix, EndpointResolver::updatePath());
$this->assertStringStartsWith($prefix, EndpointResolver::scriptPath());
$this->assertStringStartsWith($prefix, EndpointResolver::uploadPath());
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/Unit/Mechanisms/HandleRequests/EndpointResolverTest.php | tests/Unit/Mechanisms/HandleRequests/EndpointResolverTest.php | <?php
namespace Tests\Unit\Mechanisms\HandleRequests;
use Livewire\Mechanisms\HandleRequests\EndpointResolver;
use Tests\TestCase;
class EndpointResolverTest extends TestCase
{
public function test_generates_unique_prefix_from_app_key()
{
$prefix = EndpointResolver::prefix();
// Should start with /livewire-
$this->assertStringStartsWith('/livewire-', $prefix);
// Should have 8 character hash suffix
$this->assertMatchesRegularExpression('/^\/livewire-[a-f0-9]{8}$/', $prefix);
}
public function test_same_app_key_generates_same_prefix()
{
$prefix1 = EndpointResolver::prefix();
$prefix2 = EndpointResolver::prefix();
$this->assertEquals($prefix1, $prefix2);
}
public function test_different_app_keys_generate_different_prefixes()
{
$originalKey = config('app.key');
$prefix1 = EndpointResolver::prefix();
config()->set('app.key', 'base64:' . base64_encode('different-key-for-testing'));
$prefix2 = EndpointResolver::prefix();
// Restore original key
config()->set('app.key', $originalKey);
$this->assertNotEquals($prefix1, $prefix2);
}
public function test_update_path_uses_prefix()
{
$prefix = EndpointResolver::prefix();
$path = EndpointResolver::updatePath();
$this->assertEquals($prefix . '/update', $path);
}
public function test_script_path_uses_prefix()
{
$prefix = EndpointResolver::prefix();
$this->assertEquals($prefix . '/livewire.js', EndpointResolver::scriptPath(minified: false));
$this->assertEquals($prefix . '/livewire.min.js', EndpointResolver::scriptPath(minified: true));
}
public function test_map_path_uses_prefix()
{
$prefix = EndpointResolver::prefix();
$this->assertEquals($prefix . '/livewire.min.js.map', EndpointResolver::mapPath(csp: false));
$this->assertEquals($prefix . '/livewire.csp.min.js.map', EndpointResolver::mapPath(csp: true));
}
public function test_upload_path_uses_prefix()
{
$prefix = EndpointResolver::prefix();
$path = EndpointResolver::uploadPath();
$this->assertEquals($prefix . '/upload-file', $path);
}
public function test_preview_path_uses_prefix()
{
$prefix = EndpointResolver::prefix();
$path = EndpointResolver::previewPath();
$this->assertEquals($prefix . '/preview-file/{filename}', $path);
}
public function test_component_js_path_uses_prefix()
{
$prefix = EndpointResolver::prefix();
$path = EndpointResolver::componentJsPath();
$this->assertEquals($prefix . '/js/{component}.js', $path);
}
public function test_all_paths_share_same_prefix()
{
$prefix = EndpointResolver::prefix();
$this->assertStringStartsWith($prefix, EndpointResolver::updatePath());
$this->assertStringStartsWith($prefix, EndpointResolver::scriptPath());
$this->assertStringStartsWith($prefix, EndpointResolver::uploadPath());
$this->assertStringStartsWith($prefix, EndpointResolver::previewPath());
$this->assertStringStartsWith($prefix, EndpointResolver::componentJsPath());
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/tests/Unit/Mechanisms/HandleRequests/PayloadGuardsTest.php | tests/Unit/Mechanisms/HandleRequests/PayloadGuardsTest.php | <?php
namespace Tests\Unit\Mechanisms\HandleRequests;
use Livewire\Component;
use Livewire\Livewire;
use Livewire\Exceptions\PayloadTooLargeException;
use Livewire\Exceptions\TooManyComponentsException;
use Livewire\Exceptions\TooManyCallsException;
use Tests\TestCase;
class PayloadGuardsTest extends TestCase
{
public function test_rejects_payload_exceeding_max_size()
{
config()->set('livewire.payload.max_size', 100); // 100 bytes
$this->expectException(PayloadTooLargeException::class);
$this->expectExceptionMessage('payload.max_size');
// Simulate a request with a large Content-Length header
$this->withoutExceptionHandling()
->withHeaders(['Content-Length' => 1000, 'X-Livewire' => 'true'])
->post(route('livewire.update'), [
'components' => [
[
'snapshot' => json_encode([
'data' => [],
'memo' => ['id' => 'test', 'name' => 'test'],
'checksum' => 'test',
]),
'updates' => [],
'calls' => [],
],
],
]);
}
public function test_allows_payload_within_max_size()
{
config()->set('livewire.payload.max_size', 1024 * 1024); // 1MB
$component = Livewire::test(PayloadGuardComponent::class);
// Should not throw
$component->call('increment');
$this->assertEquals(1, $component->get('count'));
}
public function test_payload_size_limit_can_be_disabled()
{
config()->set('livewire.payload.max_size', null);
$component = Livewire::test(PayloadGuardComponent::class);
// Should not throw even with default null limit
$component->call('increment');
$this->assertEquals(1, $component->get('count'));
}
public function test_rejects_too_many_components()
{
config()->set('livewire.payload.max_components', 2);
$this->expectException(TooManyComponentsException::class);
$this->expectExceptionMessage('payload.max_components');
// Create a request with 3 components (exceeds limit of 2)
$this->withoutExceptionHandling()
->withHeaders(['X-Livewire' => 'true'])
->post(route('livewire.update'), [
'components' => [
['snapshot' => '{}', 'updates' => [], 'calls' => []],
['snapshot' => '{}', 'updates' => [], 'calls' => []],
['snapshot' => '{}', 'updates' => [], 'calls' => []],
],
]);
}
public function test_allows_components_within_limit()
{
config()->set('livewire.payload.max_components', 10);
$component = Livewire::test(PayloadGuardComponent::class);
// Single component should be fine
$component->call('increment');
$this->assertEquals(1, $component->get('count'));
}
public function test_max_components_limit_can_be_disabled()
{
config()->set('livewire.payload.max_components', null);
$component = Livewire::test(PayloadGuardComponent::class);
// Should work with null limit
$component->call('increment');
$this->assertEquals(1, $component->get('count'));
}
public function test_rejects_too_many_calls()
{
config()->set('livewire.payload.max_calls', 3);
// First mount the component to get a valid snapshot
$component = Livewire::test(PayloadGuardComponent::class);
$snapshot = $component->snapshot;
$this->expectException(TooManyCallsException::class);
$this->expectExceptionMessage('payload.max_calls');
// Send a request with 4 calls (exceeds limit of 3)
$this->withoutExceptionHandling()
->withHeaders(['X-Livewire' => 'true'])
->post(route('livewire.update'), [
'components' => [
[
'snapshot' => json_encode($snapshot),
'updates' => [],
'calls' => [
['method' => 'increment', 'params' => [], 'metadata' => []],
['method' => 'increment', 'params' => [], 'metadata' => []],
['method' => 'increment', 'params' => [], 'metadata' => []],
['method' => 'increment', 'params' => [], 'metadata' => []],
],
],
],
]);
}
public function test_allows_calls_within_limit()
{
config()->set('livewire.payload.max_calls', 5);
$component = Livewire::test(PayloadGuardComponent::class);
// Make 3 calls (within limit of 5)
$component->call('increment')
->call('increment')
->call('increment');
$this->assertEquals(3, $component->get('count'));
}
public function test_max_calls_limit_can_be_disabled()
{
config()->set('livewire.payload.max_calls', null);
$component = Livewire::test(PayloadGuardComponent::class);
// Should work with null limit
$component->call('increment')
->call('increment')
->call('increment')
->call('increment')
->call('increment');
$this->assertEquals(5, $component->get('count'));
}
public function test_allows_exactly_max_calls()
{
config()->set('livewire.payload.max_calls', 3);
$component = Livewire::test(PayloadGuardComponent::class);
// Exactly 3 calls should be allowed
$component->call('increment')
->call('increment')
->call('increment');
$this->assertEquals(3, $component->get('count'));
}
public function test_exception_messages_include_config_keys()
{
$payloadException = new PayloadTooLargeException(2048, 1024);
$this->assertStringContainsString('payload.max_size', $payloadException->getMessage());
$this->assertStringContainsString('2KB', $payloadException->getMessage());
$this->assertStringContainsString('1KB', $payloadException->getMessage());
$componentsException = new TooManyComponentsException(30, 20);
$this->assertStringContainsString('payload.max_components', $componentsException->getMessage());
$this->assertStringContainsString('30', $componentsException->getMessage());
$this->assertStringContainsString('20', $componentsException->getMessage());
$callsException = new TooManyCallsException(60, 50);
$this->assertStringContainsString('payload.max_calls', $callsException->getMessage());
$this->assertStringContainsString('60', $callsException->getMessage());
$this->assertStringContainsString('50', $callsException->getMessage());
}
}
class PayloadGuardComponent extends Component
{
public $count = 0;
public function increment()
{
$this->count++;
}
public function render()
{
return '<div>{{ $count }}</div>';
}
}
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
livewire/livewire | https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/config/livewire.php | config/livewire.php | <?php
return [
/*
|---------------------------------------------------------------------------
| Component Locations
|---------------------------------------------------------------------------
|
| This value sets the root directories that'll be used to resolve view-based
| components like single and multi-file components. The make command will
| use the first directory in this array to add new component files to.
|
*/
'component_locations' => [
resource_path('views/components'),
resource_path('views/livewire'),
],
/*
|---------------------------------------------------------------------------
| Component Namespaces
|---------------------------------------------------------------------------
|
| This value sets default namespaces that will be used to resolve view-based
| components like single-file and multi-file components. These folders'll
| also be referenced when creating new components via the make command.
|
*/
'component_namespaces' => [
'layouts' => resource_path('views/layouts'),
'pages' => resource_path('views/pages'),
],
/*
|---------------------------------------------------------------------------
| Page Layout
|---------------------------------------------------------------------------
| The view that will be used as the layout when rendering a single component as
| an entire page via `Route::livewire('/post/create', 'pages::create-post')`.
| In this case, the content of pages::create-post will render into $slot.
|
*/
'component_layout' => 'layouts::app',
/*
|---------------------------------------------------------------------------
| Lazy Loading Placeholder
|---------------------------------------------------------------------------
| Livewire allows you to lazy load components that would otherwise slow down
| the initial page load. Every component can have a custom placeholder or
| you can define the default placeholder view for all components below.
|
*/
'component_placeholder' => null, // Example: 'placeholders::skeleton'
/*
|---------------------------------------------------------------------------
| Make Command
|---------------------------------------------------------------------------
| This value determines the default configuration for the artisan make command
| You can configure the component type (sfc, mfc, class) and whether to use
| the high-voltage (⚡) emoji as a prefix in the sfc|mfc component names.
|
*/
'make_command' => [
'type' => 'sfc', // Options: 'sfc', 'mfc', 'class'
'emoji' => true, // Options: true, false
],
/*
|---------------------------------------------------------------------------
| Class Namespace
|---------------------------------------------------------------------------
|
| This value sets the root class namespace for Livewire component classes in
| your application. This value will change where component auto-discovery
| finds components. It's also referenced by the file creation commands.
|
*/
'class_namespace' => 'App\\Livewire',
/*
|---------------------------------------------------------------------------
| Class Path
|---------------------------------------------------------------------------
|
| This value is used to specify the path where Livewire component class files
| are created when running creation commands like `artisan make:livewire`.
| This path is customizable to match your projects directory structure.
|
*/
'class_path' => app_path('Livewire'),
/*
|---------------------------------------------------------------------------
| View Path
|---------------------------------------------------------------------------
|
| This value is used to specify where Livewire component Blade templates are
| stored when running file creation commands like `artisan make:livewire`.
| It is also used if you choose to omit a component's render() method.
|
*/
'view_path' => resource_path('views/livewire'),
/*
|---------------------------------------------------------------------------
| Temporary File Uploads
|---------------------------------------------------------------------------
|
| Livewire handles file uploads by storing uploads in a temporary directory
| before the file is stored permanently. All file uploads are directed to
| a global endpoint for temporary storage. You may configure this below:
|
*/
'temporary_file_upload' => [
'disk' => null, // Example: 'local', 's3' | Default: 'default'
'rules' => null, // Example: ['file', 'mimes:png,jpg'] | Default: ['required', 'file', 'max:12288'] (12MB)
'directory' => null, // Example: 'tmp' | Default: 'livewire-tmp'
'middleware' => null, // Example: 'throttle:5,1' | Default: 'throttle:60,1'
'preview_mimes' => [ // Supported file types for temporary pre-signed file URLs...
'png', 'gif', 'bmp', 'svg', 'wav', 'mp4',
'mov', 'avi', 'wmv', 'mp3', 'm4a',
'jpg', 'jpeg', 'mpga', 'webp', 'wma',
],
'max_upload_time' => 5, // Max duration (in minutes) before an upload is invalidated...
'cleanup' => true, // Should cleanup temporary uploads older than 24 hrs...
],
/*
|---------------------------------------------------------------------------
| Render On Redirect
|---------------------------------------------------------------------------
|
| This value determines if Livewire will run a component's `render()` method
| after a redirect has been triggered using something like `redirect(...)`
| Setting this to true will render the view once more before redirecting
|
*/
'render_on_redirect' => false,
/*
|---------------------------------------------------------------------------
| Eloquent Model Binding
|---------------------------------------------------------------------------
|
| Previous versions of Livewire supported binding directly to eloquent model
| properties using wire:model by default. However, this behavior has been
| deemed too "magical" and has therefore been put under a feature flag.
|
*/
'legacy_model_binding' => false,
/*
|---------------------------------------------------------------------------
| Auto-inject Frontend Assets
|---------------------------------------------------------------------------
|
| By default, Livewire automatically injects its JavaScript and CSS into the
| <head> and <body> of pages containing Livewire components. By disabling
| this behavior, you need to use @livewireStyles and @livewireScripts.
|
*/
'inject_assets' => true,
/*
|---------------------------------------------------------------------------
| Navigate (SPA mode)
|---------------------------------------------------------------------------
|
| By adding `wire:navigate` to links in your Livewire application, Livewire
| will prevent the default link handling and instead request those pages
| via AJAX, creating an SPA-like effect. Configure this behavior here.
|
*/
'navigate' => [
'show_progress_bar' => true,
'progress_bar_color' => '#2299dd',
],
/*
|---------------------------------------------------------------------------
| HTML Morph Markers
|---------------------------------------------------------------------------
|
| Livewire intelligently "morphs" existing HTML into the newly rendered HTML
| after each update. To make this process more reliable, Livewire injects
| "markers" into the rendered Blade surrounding @if, @class & @foreach.
|
*/
'inject_morph_markers' => true,
/*
|---------------------------------------------------------------------------
| Smart Wire Keys
|---------------------------------------------------------------------------
|
| Livewire uses loops and keys used within loops to generate smart keys that
| are applied to nested components that don't have them. This makes using
| nested components more reliable by ensuring that they all have keys.
|
*/
'smart_wire_keys' => true,
/*
|---------------------------------------------------------------------------
| Pagination Theme
|---------------------------------------------------------------------------
|
| When enabling Livewire's pagination feature by using the `WithPagination`
| trait, Livewire will use Tailwind templates to render pagination views
| on the page. If you want Bootstrap CSS, you can specify: "bootstrap"
|
*/
'pagination_theme' => 'tailwind',
/*
|---------------------------------------------------------------------------
| Release Token
|---------------------------------------------------------------------------
|
| This token is stored client-side and sent along with each request to check
| a users session to see if a new release has invalidated it. If there is
| a mismatch it will throw an error and prompt for a browser refresh.
|
*/
'release_token' => 'a',
/*
|---------------------------------------------------------------------------
| CSP Safe
|---------------------------------------------------------------------------
|
| This config is used to determine if Livewire will use the CSP-safe version
| of Alpine in its bundle. This is useful for applications that are using
| strict Content Security Policy (CSP) to protect against XSS attacks.
|
*/
'csp_safe' => false,
/*
|---------------------------------------------------------------------------
| Payload Guards
|---------------------------------------------------------------------------
|
| These settings protect against malicious or oversized payloads that could
| cause denial of service. The default values should feel reasonable for
| most web applications. Each can be set to null to disable the limit.
|
*/
'payload' => [
'max_size' => 1024 * 1024, // 1MB - maximum request payload size in bytes
'max_nesting_depth' => 10, // Maximum depth of dot-notation property paths
'max_calls' => 50, // Maximum method calls per request
'max_components' => 20, // Maximum components per batch request
],
];
| php | MIT | f2f58e728b8e834780be780ee727a85e9513d56b | 2026-01-04T15:02:34.292445Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/WildcardPermission.php | src/WildcardPermission.php | <?php
namespace Spatie\Permission;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Spatie\Permission\Contracts\Wildcard;
use Spatie\Permission\Exceptions\WildcardPermissionNotProperlyFormatted;
class WildcardPermission implements Wildcard
{
/** @var string */
public const WILDCARD_TOKEN = '*';
/** @var non-empty-string */
public const PART_DELIMITER = '.';
/** @var non-empty-string */
public const SUBPART_DELIMITER = ',';
protected Model $record;
public function __construct(Model $record)
{
$this->record = $record;
}
public function getIndex(): array
{
$index = [];
foreach ($this->record->getAllPermissions() as $permission) {
$index[$permission->guard_name] = $this->buildIndex(
$index[$permission->guard_name] ?? [],
explode(static::PART_DELIMITER, $permission->name),
$permission->name,
);
}
return $index;
}
protected function buildIndex(array $index, array $parts, string $permission): array
{
if (empty($parts)) {
$index[''] = true;
return $index;
}
$part = array_shift($parts);
if (blank($part)) {
throw WildcardPermissionNotProperlyFormatted::create($permission);
}
if (! Str::contains($part, static::SUBPART_DELIMITER)) {
$index[$part] = $this->buildIndex(
$index[$part] ?? [],
$parts,
$permission,
);
}
$subParts = explode(static::SUBPART_DELIMITER, $part);
foreach ($subParts as $subPart) {
if (blank($subPart)) {
throw WildcardPermissionNotProperlyFormatted::create($permission);
}
$index[$subPart] = $this->buildIndex(
$index[$subPart] ?? [],
$parts,
$permission,
);
}
return $index;
}
public function implies(string $permission, string $guardName, array $index): bool
{
if (! array_key_exists($guardName, $index)) {
return false;
}
$permission = explode(static::PART_DELIMITER, $permission);
return $this->checkIndex($permission, $index[$guardName]);
}
protected function checkIndex(array $permission, array $index): bool
{
if (array_key_exists(strval(null), $index)) {
return true;
}
if (empty($permission)) {
return false;
}
$firstPermission = array_shift($permission);
if (
array_key_exists($firstPermission, $index) &&
$this->checkIndex($permission, $index[$firstPermission])
) {
return true;
}
if (array_key_exists(static::WILDCARD_TOKEN, $index)) {
return $this->checkIndex($permission, $index[static::WILDCARD_TOKEN]);
}
return false;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/PermissionServiceProvider.php | src/PermissionServiceProvider.php | <?php
namespace Spatie\Permission;
use Composer\InstalledVersions;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\Console\AboutCommand;
use Illuminate\Routing\Route;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Compilers\BladeCompiler;
use Spatie\Permission\Contracts\Permission as PermissionContract;
use Spatie\Permission\Contracts\Role as RoleContract;
class PermissionServiceProvider extends ServiceProvider
{
public function boot()
{
$this->offerPublishing();
$this->registerMacroHelpers();
$this->registerCommands();
$this->registerModelBindings();
$this->registerOctaneListener();
$this->callAfterResolving(Gate::class, function (Gate $gate, Application $app) {
if ($this->app['config']->get('permission.register_permission_check_method')) {
/** @var PermissionRegistrar $permissionLoader */
$permissionLoader = $app->get(PermissionRegistrar::class);
$permissionLoader->clearPermissionsCollection();
$permissionLoader->registerPermissions($gate);
}
});
$this->app->singleton(PermissionRegistrar::class);
$this->registerAbout();
}
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../config/permission.php',
'permission'
);
$this->callAfterResolving('blade.compiler', fn (BladeCompiler $bladeCompiler) => $this->registerBladeExtensions($bladeCompiler));
}
protected function offerPublishing(): void
{
if (! $this->app->runningInConsole()) {
return;
}
if (! function_exists('config_path')) {
// function not available and 'publish' not relevant in Lumen
return;
}
$this->publishes([
__DIR__.'/../config/permission.php' => config_path('permission.php'),
], 'permission-config');
$this->publishes([
__DIR__.'/../database/migrations/create_permission_tables.php.stub' => $this->getMigrationFileName('create_permission_tables.php'),
], 'permission-migrations');
}
protected function registerCommands(): void
{
$this->commands([
Commands\CacheReset::class,
]);
if (! $this->app->runningInConsole()) {
return;
}
$this->commands([
Commands\CreateRole::class,
Commands\CreatePermission::class,
Commands\Show::class,
Commands\UpgradeForTeams::class,
Commands\AssignRole::class,
]);
}
protected function registerOctaneListener(): void
{
if ($this->app->runningInConsole() || ! $this->app['config']->get('octane.listeners')) {
return;
}
$dispatcher = $this->app[Dispatcher::class];
// @phpstan-ignore-next-line
$dispatcher->listen(function (\Laravel\Octane\Contracts\OperationTerminated $event) {
// @phpstan-ignore-next-line
$event->sandbox->make(PermissionRegistrar::class)->setPermissionsTeamId(null);
});
if (! $this->app['config']->get('permission.register_octane_reset_listener')) {
return;
}
// @phpstan-ignore-next-line
$dispatcher->listen(function (\Laravel\Octane\Contracts\OperationTerminated $event) {
// @phpstan-ignore-next-line
$event->sandbox->make(PermissionRegistrar::class)->clearPermissionsCollection();
});
}
protected function registerModelBindings(): void
{
$this->app->bind(PermissionContract::class, fn ($app) => $app->make($app->config['permission.models.permission']));
$this->app->bind(RoleContract::class, fn ($app) => $app->make($app->config['permission.models.role']));
}
public static function bladeMethodWrapper($method, $role, $guard = null): bool
{
return auth($guard)->check() && auth($guard)->user()->{$method}($role);
}
protected function registerBladeExtensions(BladeCompiler $bladeCompiler): void
{
$bladeMethodWrapper = '\\Spatie\\Permission\\PermissionServiceProvider::bladeMethodWrapper';
// permission checks
$bladeCompiler->if('haspermission', fn () => $bladeMethodWrapper('checkPermissionTo', ...func_get_args()));
// role checks
$bladeCompiler->if('role', fn () => $bladeMethodWrapper('hasRole', ...func_get_args()));
$bladeCompiler->if('hasrole', fn () => $bladeMethodWrapper('hasRole', ...func_get_args()));
$bladeCompiler->if('hasanyrole', fn () => $bladeMethodWrapper('hasAnyRole', ...func_get_args()));
$bladeCompiler->if('hasallroles', fn () => $bladeMethodWrapper('hasAllRoles', ...func_get_args()));
$bladeCompiler->if('hasexactroles', fn () => $bladeMethodWrapper('hasExactRoles', ...func_get_args()));
$bladeCompiler->directive('endunlessrole', fn () => '<?php endif; ?>');
}
protected function registerMacroHelpers(): void
{
if (! method_exists(Route::class, 'macro')) { // @phpstan-ignore-line Lumen
return;
}
Route::macro('role', function ($roles = []) {
$roles = Arr::wrap($roles);
$roles = array_map(fn ($role) => $role instanceof \BackedEnum ? $role->value : $role, $roles);
/** @var Route $this */
return $this->middleware('role:'.implode('|', $roles));
});
Route::macro('permission', function ($permissions = []) {
$permissions = Arr::wrap($permissions);
$permissions = array_map(fn ($permission) => $permission instanceof \BackedEnum ? $permission->value : $permission, $permissions);
/** @var Route $this */
return $this->middleware('permission:'.implode('|', $permissions));
});
Route::macro('roleOrPermission', function ($rolesOrPermissions = []) {
$rolesOrPermissions = Arr::wrap($rolesOrPermissions);
$rolesOrPermissions = array_map(fn ($item) => $item instanceof \BackedEnum ? $item->value : $item, $rolesOrPermissions);
/** @var Route $this */
return $this->middleware('role_or_permission:'.implode('|', $rolesOrPermissions));
});
}
/**
* Returns existing migration file if found, else uses the current timestamp.
*/
protected function getMigrationFileName(string $migrationFileName): string
{
$timestamp = date('Y_m_d_His');
$filesystem = $this->app->make(Filesystem::class);
return Collection::make([$this->app->databasePath().DIRECTORY_SEPARATOR.'migrations'.DIRECTORY_SEPARATOR])
->flatMap(fn ($path) => $filesystem->glob($path.'*_'.$migrationFileName))
->push($this->app->databasePath()."/migrations/{$timestamp}_{$migrationFileName}")
->first();
}
protected function registerAbout(): void
{
if (! class_exists(InstalledVersions::class) || ! class_exists(AboutCommand::class)) {
return;
}
// array format: 'Display Text' => 'boolean-config-key name'
$features = [
'Teams' => 'teams',
'Wildcard-Permissions' => 'enable_wildcard_permission',
'Octane-Listener' => 'register_octane_reset_listener',
'Passport' => 'use_passport_client_credentials',
];
$config = $this->app['config'];
AboutCommand::add('Spatie Permissions', static fn () => [
'Features Enabled' => collect($features)
->filter(fn (string $feature, string $name): bool => $config->get("permission.{$feature}"))
->keys()
->whenEmpty(fn (Collection $collection) => $collection->push('Default'))
->join(', '),
'Version' => InstalledVersions::getPrettyVersion('spatie/laravel-permission'),
]);
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/DefaultTeamResolver.php | src/DefaultTeamResolver.php | <?php
namespace Spatie\Permission;
use Spatie\Permission\Contracts\PermissionsTeamResolver;
class DefaultTeamResolver implements PermissionsTeamResolver
{
protected int|string|null $teamId = null;
/**
* Set the team id for teams/groups support, this id is used when querying permissions/roles
*
* @param int|string|\Illuminate\Database\Eloquent\Model|null $id
*/
public function setPermissionsTeamId($id): void
{
if ($id instanceof \Illuminate\Database\Eloquent\Model) {
$id = $id->getKey();
}
$this->teamId = $id;
}
public function getPermissionsTeamId(): int|string|null
{
return $this->teamId;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/helpers.php | src/helpers.php | <?php
if (! function_exists('getModelForGuard')) {
function getModelForGuard(string $guard): ?string
{
return Spatie\Permission\Guard::getModelForGuard($guard);
}
}
if (! function_exists('setPermissionsTeamId')) {
/**
* @param int|string|null|\Illuminate\Database\Eloquent\Model $id
*/
function setPermissionsTeamId($id)
{
app(\Spatie\Permission\PermissionRegistrar::class)->setPermissionsTeamId($id);
}
}
if (! function_exists('getPermissionsTeamId')) {
/**
* @return int|string|null
*/
function getPermissionsTeamId()
{
return app(\Spatie\Permission\PermissionRegistrar::class)->getPermissionsTeamId();
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/PermissionRegistrar.php | src/PermissionRegistrar.php | <?php
namespace Spatie\Permission;
use Illuminate\Cache\CacheManager;
use Illuminate\Contracts\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Access\Gate;
use Illuminate\Contracts\Cache\Repository;
use Illuminate\Contracts\Cache\Store;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Contracts\Permission;
use Spatie\Permission\Contracts\PermissionsTeamResolver;
use Spatie\Permission\Contracts\Role;
class PermissionRegistrar
{
protected Repository $cache;
protected CacheManager $cacheManager;
protected string $permissionClass;
protected string $roleClass;
/** @var Collection|array|null */
protected $permissions;
public string $pivotRole;
public string $pivotPermission;
/** @var \DateInterval|int */
public $cacheExpirationTime;
public bool $teams;
protected PermissionsTeamResolver $teamResolver;
public string $teamsKey;
public string $cacheKey;
private array $cachedRoles = [];
private array $alias = [];
private array $except = [];
private array $wildcardPermissionsIndex = [];
private bool $isLoadingPermissions = false;
/**
* PermissionRegistrar constructor.
*/
public function __construct(CacheManager $cacheManager)
{
$this->permissionClass = config('permission.models.permission');
$this->roleClass = config('permission.models.role');
$this->teamResolver = new (config('permission.team_resolver', DefaultTeamResolver::class));
$this->cacheManager = $cacheManager;
$this->initializeCache();
}
public function initializeCache(): void
{
$this->cacheExpirationTime = config('permission.cache.expiration_time') ?: \DateInterval::createFromDateString('24 hours');
$this->teams = config('permission.teams', false);
$this->teamsKey = config('permission.column_names.team_foreign_key', 'team_id');
$this->cacheKey = config('permission.cache.key');
$this->pivotRole = config('permission.column_names.role_pivot_key') ?: 'role_id';
$this->pivotPermission = config('permission.column_names.permission_pivot_key') ?: 'permission_id';
$this->cache = $this->getCacheStoreFromConfig();
}
protected function getCacheStoreFromConfig(): Repository
{
// the 'default' fallback here is from the permission.php config file,
// where 'default' means to use config(cache.default)
$cacheDriver = config('permission.cache.store', 'default');
// when 'default' is specified, no action is required since we already have the default instance
if ($cacheDriver === 'default') {
return $this->cacheManager->store();
}
// if an undefined cache store is specified, fallback to 'array' which is Laravel's closest equiv to 'none'
if (! \array_key_exists($cacheDriver, config('cache.stores'))) {
$cacheDriver = 'array';
}
return $this->cacheManager->store($cacheDriver);
}
/**
* Set the team id for teams/groups support, this id is used when querying permissions/roles
*
* @param int|string|\Illuminate\Database\Eloquent\Model|null $id
*/
public function setPermissionsTeamId($id): void
{
$this->teamResolver->setPermissionsTeamId($id);
}
/**
* @return int|string|null
*/
public function getPermissionsTeamId()
{
return $this->teamResolver->getPermissionsTeamId();
}
/**
* Register the permission check method on the gate.
* We resolve the Gate fresh here, for benefit of long-running instances.
*/
public function registerPermissions(Gate $gate): bool
{
$gate->before(function (Authorizable $user, string $ability, array &$args = []) {
if (is_string($args[0] ?? null) && ! class_exists($args[0])) {
$guard = array_shift($args);
}
if (method_exists($user, 'checkPermissionTo')) {
return $user->checkPermissionTo($ability, $guard ?? null) ?: null;
}
});
return true;
}
/**
* Flush the cache.
*/
public function forgetCachedPermissions()
{
$this->permissions = null;
$this->forgetWildcardPermissionIndex();
return $this->cache->forget($this->cacheKey);
}
public function forgetWildcardPermissionIndex(?Model $record = null): void
{
if ($record) {
unset($this->wildcardPermissionsIndex[get_class($record)][$record->getKey()]);
return;
}
$this->wildcardPermissionsIndex = [];
}
public function getWildcardPermissionIndex(Model $record): array
{
if (isset($this->wildcardPermissionsIndex[get_class($record)][$record->getKey()])) {
return $this->wildcardPermissionsIndex[get_class($record)][$record->getKey()];
}
return $this->wildcardPermissionsIndex[get_class($record)][$record->getKey()] = app($record->getWildcardClass(), ['record' => $record])->getIndex();
}
/**
* Clear already-loaded permissions collection.
* This is only intended to be called by the PermissionServiceProvider on boot,
* so that long-running instances like Octane or Swoole don't keep old data in memory.
*/
public function clearPermissionsCollection(): void
{
$this->permissions = null;
$this->wildcardPermissionsIndex = [];
$this->isLoadingPermissions = false;
}
/**
* @deprecated
*
* @alias of clearPermissionsCollection()
*/
public function clearClassPermissions()
{
$this->clearPermissionsCollection();
}
/**
* Load permissions from cache
* And turns permissions array into a \Illuminate\Database\Eloquent\Collection
*
* Thread-safe implementation to prevent race conditions in concurrent environments
* (e.g., Laravel Octane, Swoole, parallel requests)
*/
private function loadPermissions(int $retries = 0): void
{
// First check (without lock) - fast path for already loaded permissions
if ($this->permissions) {
return;
}
// Prevent concurrent loading using a flag-based lock
// This protects against cache stampede and duplicate database queries
if ($this->isLoadingPermissions && $retries < 10) {
// Another thread is loading, wait and retry
usleep(10000); // Wait 10ms
$retries++;
// After wait, recursively check again if permissions were loaded
$this->loadPermissions($retries);
return;
}
// Set loading flag to prevent concurrent loads
$this->isLoadingPermissions = true;
try {
$this->permissions = $this->cache->remember(
$this->cacheKey, $this->cacheExpirationTime, fn () => $this->getSerializedPermissionsForCache()
);
$this->alias = $this->permissions['alias'];
$this->hydrateRolesCache();
$this->permissions = $this->getHydratedPermissionCollection();
$this->cachedRoles = $this->alias = $this->except = [];
} finally {
// Always release the loading flag, even if an exception occurs
$this->isLoadingPermissions = false;
}
}
/**
* Get the permissions based on the passed params.
*/
public function getPermissions(array $params = [], bool $onlyOne = false): Collection
{
$this->loadPermissions();
$method = $onlyOne ? 'first' : 'filter';
$permissions = $this->permissions->$method(static function ($permission) use ($params) {
foreach ($params as $attr => $value) {
if ($permission->getAttribute($attr) != $value) {
return false;
}
}
return true;
});
if ($onlyOne) {
$permissions = new Collection($permissions ? [$permissions] : []);
}
return $permissions;
}
public function getPermissionClass(): string
{
return $this->permissionClass;
}
public function setPermissionClass($permissionClass)
{
$this->permissionClass = $permissionClass;
config()->set('permission.models.permission', $permissionClass);
app()->bind(Permission::class, $permissionClass);
return $this;
}
public function getRoleClass(): string
{
return $this->roleClass;
}
public function setRoleClass($roleClass)
{
$this->roleClass = $roleClass;
config()->set('permission.models.role', $roleClass);
app()->bind(Role::class, $roleClass);
return $this;
}
public function getCacheRepository(): Repository
{
return $this->cache;
}
public function getCacheStore(): Store
{
return $this->cache->getStore();
}
protected function getPermissionsWithRoles(): Collection
{
return $this->permissionClass::select()->with('roles')->get();
}
/**
* Changes array keys with alias
*/
private function aliasedArray($model): array
{
return collect(is_array($model) ? $model : $model->getAttributes())->except($this->except)
->keyBy(fn ($value, $key) => $this->alias[$key] ?? $key)
->all();
}
/**
* Array for cache alias
*/
private function aliasModelFields($newKeys = []): void
{
$i = 0;
$alphas = ! count($this->alias) ? range('a', 'h') : range('j', 'p');
foreach (array_keys($newKeys->getAttributes()) as $value) {
if (! isset($this->alias[$value])) {
$this->alias[$value] = $alphas[$i++] ?? $value;
}
}
$this->alias = array_diff_key($this->alias, array_flip($this->except));
}
/*
* Make the cache smaller using an array with only required fields
*/
private function getSerializedPermissionsForCache(): array
{
$this->except = config('permission.cache.column_names_except', ['created_at', 'updated_at', 'deleted_at']);
$permissions = $this->getPermissionsWithRoles()
->map(function ($permission) {
if (! $this->alias) {
$this->aliasModelFields($permission);
}
return $this->aliasedArray($permission) + $this->getSerializedRoleRelation($permission);
})->all();
$roles = array_values($this->cachedRoles);
$this->cachedRoles = [];
return ['alias' => array_flip($this->alias)] + compact('permissions', 'roles');
}
private function getSerializedRoleRelation($permission): array
{
if (! $permission->roles->count()) {
return [];
}
if (! isset($this->alias['roles'])) {
$this->alias['roles'] = 'r';
$this->aliasModelFields($permission->roles[0]);
}
return [
'r' => $permission->roles->map(function ($role) {
if (! isset($this->cachedRoles[$role->getKey()])) {
$this->cachedRoles[$role->getKey()] = $this->aliasedArray($role);
}
return $role->getKey();
})->all(),
];
}
private function getHydratedPermissionCollection(): Collection
{
$permissionInstance = (new ($this->getPermissionClass())())->newInstance([], true);
return Collection::make(array_map(
fn ($item) => (clone $permissionInstance)
->setRawAttributes($this->aliasedArray(array_diff_key($item, ['r' => 0])), true)
->setRelation('roles', $this->getHydratedRoleCollection($item['r'] ?? [])),
$this->permissions['permissions']
));
}
private function getHydratedRoleCollection(array $roles): Collection
{
return Collection::make(array_values(
array_intersect_key($this->cachedRoles, array_flip($roles))
));
}
private function hydrateRolesCache(): void
{
$roleInstance = (new ($this->getRoleClass())())->newInstance([], true);
array_map(function ($item) use ($roleInstance) {
$role = (clone $roleInstance)
->setRawAttributes($this->aliasedArray($item), true);
$this->cachedRoles[$role->getKey()] = $role;
}, $this->permissions['roles']);
$this->permissions['roles'] = [];
}
public static function isUid($value): bool
{
if (! is_string($value) || empty(trim($value))) {
return false;
}
// check if is UUID/GUID
$uid = preg_match('/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iD', $value) > 0;
if ($uid) {
return true;
}
// check if is ULID
$ulid = strlen($value) == 26 && strspn($value, '0123456789ABCDEFGHJKMNPQRSTVWXYZabcdefghjkmnpqrstvwxyz') == 26 && $value[0] <= '7';
if ($ulid) {
return true;
}
return false;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Guard.php | src/Guard.php | <?php
namespace Spatie\Permission;
use Illuminate\Contracts\Auth\Access\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
class Guard
{
/**
* Return a collection of guard names suitable for the $model,
* as indicated by the presence of a $guard_name property or a guardName() method on the model.
*
* @param string|Model $model model class object or name
*/
public static function getNames($model): Collection
{
$class = is_object($model) ? get_class($model) : $model;
if (is_object($model)) {
if (\method_exists($model, 'guardName')) {
$guardName = $model->guardName();
} else {
$guardName = $model->getAttributeValue('guard_name');
}
}
if (! isset($guardName)) {
$guardName = (new \ReflectionClass($class))->getDefaultProperties()['guard_name'] ?? null;
}
if ($guardName) {
return collect($guardName);
}
return self::getConfigAuthGuards($class);
}
/**
* Get the model class associated with a given provider.
*/
protected static function getProviderModel(string $provider): ?string
{
// Get the provider configuration
$providerConfig = config("auth.providers.{$provider}");
// Handle LDAP provider or standard Eloquent provider
if (isset($providerConfig['driver']) && $providerConfig['driver'] === 'ldap') {
return $providerConfig['database']['model'] ?? null;
}
return $providerConfig['model'] ?? null;
}
/**
* Get list of relevant guards for the $class model based on config(auth) settings.
*
* Lookup flow:
* - get names of models for guards defined in auth.guards where a provider is set
* - filter for provider models matching the model $class being checked (important for Lumen)
* - keys() gives just the names of the matched guards
* - return collection of guard names
*/
protected static function getConfigAuthGuards(string $class): Collection
{
return collect(config('auth.guards'))
->map(function ($guard) {
if (! isset($guard['provider'])) {
return null;
}
return static::getProviderModel($guard['provider']);
})
->filter(fn ($model) => $class === $model)
->keys();
}
/**
* Get the model associated with a given guard name.
*/
public static function getModelForGuard(string $guard): ?string
{
// Get the provider configuration for the given guard
$provider = config("auth.guards.{$guard}.provider");
if (! $provider) {
return null;
}
return static::getProviderModel($provider);
}
/**
* Lookup a guard name relevant for the $class model and the current user.
*
* @param string|Model $class model class object or name
* @return string guard name
*/
public static function getDefaultName($class): string
{
$default = config('auth.defaults.guard');
$possible_guards = static::getNames($class);
// return current-detected auth.defaults.guard if it matches one of those that have been checked
if ($possible_guards->contains($default)) {
return $default;
}
return $possible_guards->first() ?: $default;
}
/**
* Lookup a passport guard
*/
public static function getPassportClient($guard): ?Authorizable
{
$guards = collect(config('auth.guards'))->where('driver', 'passport');
if (! $guards->count()) {
return null;
}
$authGuard = Auth::guard($guards->keys()[0]);
if (! \method_exists($authGuard, 'client')) {
return null;
}
$client = $authGuard->client();
if (! $guard || ! $client) {
return $client;
}
if (self::getNames($client)->contains($guard)) {
return $client;
}
return null;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Exceptions/RoleDoesNotExist.php | src/Exceptions/RoleDoesNotExist.php | <?php
namespace Spatie\Permission\Exceptions;
use InvalidArgumentException;
class RoleDoesNotExist extends InvalidArgumentException
{
public static function named(string $roleName, ?string $guardName)
{
return new static(__('There is no role named `:role` for guard `:guard`.', [
'role' => $roleName,
'guard' => $guardName,
]));
}
/**
* @param int|string $roleId
* @return static
*/
public static function withId($roleId, ?string $guardName)
{
return new static(__('There is no role with ID `:id` for guard `:guard`.', [
'id' => $roleId,
'guard' => $guardName,
]));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Exceptions/UnauthorizedException.php | src/Exceptions/UnauthorizedException.php | <?php
namespace Spatie\Permission\Exceptions;
use Illuminate\Contracts\Auth\Access\Authorizable;
use Symfony\Component\HttpKernel\Exception\HttpException;
class UnauthorizedException extends HttpException
{
private $requiredRoles = [];
private $requiredPermissions = [];
public static function forRoles(array $roles): self
{
$message = __('User does not have the right roles.');
if (config('permission.display_role_in_exception')) {
$message .= ' '.__('Necessary roles are :roles', ['roles' => implode(', ', $roles)]);
}
$exception = new static(403, $message, null, []);
$exception->requiredRoles = $roles;
return $exception;
}
public static function forPermissions(array $permissions): self
{
$message = __('User does not have the right permissions.');
if (config('permission.display_permission_in_exception')) {
$message .= ' '.__('Necessary permissions are :permissions', ['permissions' => implode(', ', $permissions)]);
}
$exception = new static(403, $message, null, []);
$exception->requiredPermissions = $permissions;
return $exception;
}
public static function forRolesOrPermissions(array $rolesOrPermissions): self
{
$message = __('User does not have any of the necessary access rights.');
if (config('permission.display_permission_in_exception') && config('permission.display_role_in_exception')) {
$message .= ' '.__('Necessary roles or permissions are :values', ['values' => implode(', ', $rolesOrPermissions)]);
}
$exception = new static(403, $message, null, []);
$exception->requiredPermissions = $rolesOrPermissions;
return $exception;
}
public static function missingTraitHasRoles(Authorizable $user): self
{
$class = get_class($user);
return new static(403, __('Authorizable class `:class` must use Spatie\\Permission\\Traits\\HasRoles trait.', [
'class' => $class,
]), null, []);
}
public static function notLoggedIn(): self
{
return new static(403, __('User is not logged in.'), null, []);
}
public function getRequiredRoles(): array
{
return $this->requiredRoles;
}
public function getRequiredPermissions(): array
{
return $this->requiredPermissions;
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Exceptions/GuardDoesNotMatch.php | src/Exceptions/GuardDoesNotMatch.php | <?php
namespace Spatie\Permission\Exceptions;
use Illuminate\Support\Collection;
use InvalidArgumentException;
class GuardDoesNotMatch extends InvalidArgumentException
{
public static function create(string $givenGuard, Collection $expectedGuards)
{
return new static(__('The given role or permission should use guard `:expected` instead of `:given`.', [
'expected' => $expectedGuards->implode(', '),
'given' => $givenGuard,
]));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Exceptions/PermissionDoesNotExist.php | src/Exceptions/PermissionDoesNotExist.php | <?php
namespace Spatie\Permission\Exceptions;
use InvalidArgumentException;
class PermissionDoesNotExist extends InvalidArgumentException
{
public static function create(string $permissionName, ?string $guardName)
{
return new static(__('There is no permission named `:permission` for guard `:guard`.', [
'permission' => $permissionName,
'guard' => $guardName,
]));
}
/**
* @param int|string $permissionId
* @return static
*/
public static function withId($permissionId, ?string $guardName)
{
return new static(__('There is no [permission] with ID `:id` for guard `:guard`.', [
'id' => $permissionId,
'guard' => $guardName,
]));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Exceptions/WildcardPermissionInvalidArgument.php | src/Exceptions/WildcardPermissionInvalidArgument.php | <?php
namespace Spatie\Permission\Exceptions;
use InvalidArgumentException;
class WildcardPermissionInvalidArgument extends InvalidArgumentException
{
public static function create()
{
return new static(__('Wildcard permission must be string, permission id or permission instance'));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
spatie/laravel-permission | https://github.com/spatie/laravel-permission/blob/c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044/src/Exceptions/WildcardPermissionNotImplementsContract.php | src/Exceptions/WildcardPermissionNotImplementsContract.php | <?php
namespace Spatie\Permission\Exceptions;
use InvalidArgumentException;
class WildcardPermissionNotImplementsContract extends InvalidArgumentException
{
public static function create()
{
return new static(__('Wildcard permission class must implement Spatie\\Permission\\Contracts\\Wildcard contract'));
}
}
| php | MIT | c9a58b20c656ea6e22b25e6e1b4d3bab0e0ca044 | 2026-01-04T15:03:01.280769Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.