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/SupportMorphAwareBladeCompilation/BrowserTest.php
src/Features/SupportMorphAwareBladeCompilation/BrowserTest.php
<?php namespace Livewire\Features\SupportMorphAwareBladeCompilation; use Livewire\Livewire; use Livewire\Component; class BrowserTest extends \Tests\BrowserTestCase { public function test_blade_conditionals_are_handled_properly_by_morphdom() { Livewire::visit(new class extends Component { public $show = true; function toggle() { $this->show = ! $this->show; } function render() { return <<<'HTML' <div> <button wire:click="toggle" dusk="toggle">Toggle</button> <div> @if ($show) <div dusk="foo">foo</div> @endif <div>bar<input dusk="bar"></div> </div> </div> HTML; } }) ->type('@bar', 'Hey!') ->waitForLivewire()->click('@toggle') ->assertInputValue('@bar', 'Hey!') ->assertNotPresent('@foo') ->waitForLivewire()->click('@toggle') ->assertInputValue('@bar', 'Hey!') ->assertVisible('@foo') ; } public function test_blade_conditional_actions_are_handled_properly_by_morphdom() { Livewire::visit(new class extends Component { public $enabled = true; function enable() { $this->enabled = true; } function disable() { $this->enabled = false; } function render() { return <<<'HTML' <div> <div> @if ($enabled) <button wire:click="disable" dusk="disable">Disable</button> @else <button wire:click="enable" dusk="enable">Enable</button> @endif </div> </div> HTML; } }) ->waitForLivewire()->click('@disable') ->assertNotPresent('@disable') ->assertVisible('@enable') ->waitForLivewire()->click('@enable') ->assertNotPresent('@enable') ->assertVisible('@disable') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportMorphAwareBladeCompilation/UnitTest.php
src/Features/SupportMorphAwareBladeCompilation/UnitTest.php
<?php namespace Livewire\Features\SupportMorphAwareBladeCompilation; use Illuminate\Support\Facades\Blade; use Livewire\ComponentHookRegistry; use Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys; use Livewire\Livewire; use PHPUnit\Framework\Attributes\DataProvider; class UnitTest extends \Tests\TestCase { public function setUp(): void { parent::setUp(); Livewire::flushState(); config()->set('livewire.smart_wire_keys', true); // Reload the features so the config is loaded and the precompilers are registered if required... $this->reloadFeatures(); } public function test_loop_markers_are_not_output_when_smart_wire_keys_are_disabled() { Livewire::flushState(); config()->set('livewire.smart_wire_keys', false); // Reload the features so the config is loaded and the precompilers are registered if required... $this->reloadFeatures(); $compiled = $this->compile(<<< 'HTML' <div> @foreach([1, 2, 3] as $item) <div wire:key="{{ $item }}"> {{ $item }} </div> @endforeach </div> HTML); $this->assertStringNotContainsString('SupportCompiledWireKeys::openLoop(', $compiled); $this->assertStringNotContainsString('SupportCompiledWireKeys::startLoop(', $compiled); $this->assertStringNotContainsString('SupportCompiledWireKeys::endLoop(', $compiled); $this->assertStringNotContainsString('SupportCompiledWireKeys::closeLoop(', $compiled); } public function test_conditional_markers_are_still_output_when_smart_wire_keys_are_disabled() { Livewire::flushState(); config()->set('livewire.smart_wire_keys', false); // Reload the features so the config is loaded and the precompilers are registered if required... $this->reloadFeatures(); $compiled = $this->compile(<<<'HTML' <div> @if(true) foo @endif </div> HTML); $this->assertStringContainsString('<!--[if BLOCK]><![endif]-->', $compiled); $this->assertStringContainsString('<!--[if ENDBLOCK]><![endif]-->', $compiled); } public function test_conditional_markers_are_not_output_when_inject_morph_markers_is_disabled() { Livewire::flushState(); config()->set('livewire.inject_morph_markers', false); // Reload the features so the config is loaded and the precompilers are registered if required... $this->reloadFeatures(); $compiled = $this->compile(<<< 'HTML' <div> @if (true) <div @if (true) @endif></div> @endif </div> HTML); $this->assertStringNotContainsString('<!--[if BLOCK]><![endif]-->', $compiled); $this->assertStringNotContainsString('<!--[if ENDBLOCK]><![endif]-->', $compiled); } public function test_loop_markers_are_still_output_when_inject_morph_markers_is_disabled() { Livewire::flushState(); config()->set('livewire.inject_morph_markers', false); // Reload the features so the config is loaded and the precompilers are registered if required... $this->reloadFeatures(); $compiled = $this->compile(<<<'HTML' <div> @foreach([1, 2, 3] as $item) <div wire:key="{{ $item }}"> {{ $item }} </div> @endforeach </div> HTML); $this->assertStringContainsString('SupportCompiledWireKeys::openLoop(', $compiled); $this->assertStringContainsString('SupportCompiledWireKeys::startLoop(', $compiled); $this->assertStringContainsString('SupportCompiledWireKeys::endLoop(', $compiled); $this->assertStringContainsString('SupportCompiledWireKeys::closeLoop(', $compiled); } public function test_conditional_markers_are_only_added_to_if_statements_wrapping_elements() { Livewire::component('foo', new class extends \Livewire\Component { public function render() { return '<div>@if (true) <div @if (true) @endif></div> @endif</div>'; } }); $output = Blade::render(' <div>@if (true) <div></div> @endif</div> <livewire:foo /> '); $this->assertCount(2, explode('<!--[if BLOCK]><![endif]-->', $output)); $this->assertCount(2, explode('<!--[if ENDBLOCK]><![endif]-->', $output)); } public function test_handles_custom_blade_conditional_directives() { Blade::if('foo', function () { return '...'; }); $output = $this->compile(<<<'HTML' <div> @foo (true) ... @endfoo </div> HTML); $this->assertOccurrences(1, '<!--[if BLOCK]><![endif]-->', $output); $this->assertOccurrences(1, '<!--[if ENDBLOCK]><![endif]-->', $output); } public function test_handles_if_statements_with_calculation_inside() { $template = '<div> @if (($someProperty) > 0) <span> {{ $someProperty }} </span> @endif </div>'; $output = $this->compile($template); $this->assertOccurrences(1, '<!--[if BLOCK]><![endif]-->', $output); $this->assertOccurrences(1, '<!--[if ENDBLOCK]><![endif]-->', $output); } public function test_morph_markers_are_not_output_when_not_used_within_a_livewire_context() { $template = <<<'HTML' <div> @if (true) <span>Test</span> @endif </div> HTML; $output = $this->render($template); $this->assertStringContainsString('Test', $output); $this->assertOccurrences(0, '<!--[if BLOCK]><![endif]-->', $output); $this->assertOccurrences(0, '<!--[if ENDBLOCK]><![endif]-->', $output); } public function test_morph_markers_are_output_when_used_within_a_livewire_context() { Livewire::component('foo', new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> @if (true) <span>Test</span> @endif </div> HTML; } }); $output = $this->render('<livewire:foo />'); $this->assertStringContainsString('Test', $output); $this->assertOccurrences(1, '<!--[if BLOCK]><![endif]-->', $output); $this->assertOccurrences(1, '<!--[if ENDBLOCK]><![endif]-->', $output); } public function test_loop_trackers_are_not_used_when_not_within_a_livewire_context() { $template = <<<'HTML' <div> @foreach ([1, 2, 3] as $item) <span>Test</span> @endforeach </div> HTML; $output = $this->render($template); $this->assertStringContainsString('Test', $output); // When the template is rendered, there should be no loop trackers in the stack... $this->assertEmpty(SupportCompiledWireKeys::$loopStack); } public function test_loop_trackers_are_used_when_used_within_a_livewire_context() { Livewire::component('foo', new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> @foreach ([1, 2, 3] as $item) <span>Test</span> @endforeach </div> HTML; } }); $output = $this->render('<livewire:foo />'); $this->assertStringContainsString('Test', $output); // When the template is rendered, there should be 1 loop in the stack, which will be a count of 0 so we don't have an offset compared to the loop indexes... $this->assertEquals(0, SupportCompiledWireKeys::$currentLoop['count']); } public function test_for_loop_trackers_are_used_when_used_within_a_livewire_context() { $this->markTestSkipped('For loops are not supported yet as there is no loop index available...'); Livewire::component('foo', new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> @for ($i = 0; $i < 3; $i++) <span>Test</span> @endfor </div> HTML; } }); $output = $this->render('<livewire:foo />'); $this->assertStringContainsString('Test', $output); // When the template is rendered, there should be 1 loop in the stack, which will be a count of 0 so we don't have an offset compared to the loop indexes... $this->assertEquals(0, SupportCompiledWireKeys::$currentLoop['count']); } #[DataProvider('templatesProvider')] public function test_foo($occurrences, $template, $expectedCompiled = null) { $compiled = $this->compile($template); $this->assertOccurrences($occurrences, '<!--[if BLOCK]><![endif]-->', $compiled); $this->assertOccurrences($occurrences, '<!--[if ENDBLOCK]><![endif]-->', $compiled); $expectedCompiled && $this->assertEquals($expectedCompiled, $compiled); } public static function templatesProvider() { return [ 0 => [ 2, <<<'HTML' <div @if (true) other @endif> @if (true) foo @endif @if (true) bar @endif </div> HTML ], 1 => [ 0, <<<'HTML' <div @if ($foo->bar) @click="baz" @endif > </div> HTML ], 2 => [ 1, <<<'HTML' <div> <div @class(['foo(bar)'])></div> <div> @if (true) <div foo="{ 'bar': 'baz', }"></div> @endif </div> </div> HTML ], 3 => [ 1, <<<'HTML' <div> <div @class(['foo[bar]'])></div> <div> @if (true) <div foo="{ 'bar': 'baz', }"></div> @endif </div> </div> HTML ], 4 => [ 2, <<<'HTML' <div @foreach(range(1,4) as $key => $value) {{ $key }}="{{ $value }}" @endforeach> @foreach(range(1,4) as $key => $value) {{ $key }}="{{ $value }}" @endforeach @foreach(range(1,4) as $key => $value) {{ $key }}="{{ $value }}" @endforeach </div> HTML ], 5 => [ 0, <<<'HTML' <div @if ($foo) {{ $foo->bar }} @endif @if ($foo) {{ $foo=>bar }}="bar" @endif > </div> HTML ], 6 => [ 0, <<<'HTML' <div @if ($foo) foo="{{ $foo->bar }}" @endif @if ($foo) foo="{{ $foo=>bar }}" @endif > </div> HTML ], 7 => [ 0, <<<'HTML' <div @if ($foo->bar) foo="bar" @endif @if ($foo=>bar) foo="bar" @endif > </div> HTML ], 8 => [ 2, <<<'HTML' <div> {{ 1 < 5 ? "true" : "false" }} @foreach(range(1,4) as $key => $value) {{ $key }}="{{ $value }}" @endforeach @foreach(range(1,4) as $key => $value) {{ $key }}="{{ $value }}" @endforeach </div> HTML ], 9 => [ 2, <<<'HTML' <div> @if (true) @if (true) <div></div> @endif @endif </div> HTML ], 10 => [ 1, <<<'HTML' <div @class([ 'flex', ]) @if(true) data-no-block @endif > @if(true) <span>foo</span> @endif </div> HTML ], 11 => [ 1, <<<'HTML' <div @class([ 'flex' => true, ]) @if(true) data-no-block @endif > @if(true) <span>foo</span> @endif </div> HTML ], 12 => [ 2, <<<'HTML' <div> @if (true) Dispatch up worked! @endif @if (true) Dispatch to worked! @endif </div> HTML ], 13 => [ 0, <<<'HTML' <div {{ $object->method("test {$foo}") }} @if (true) bar="bob" @endif></div> HTML ], 14 => [ 0, <<<'HTML' <div {{ $object->method("test {$foo}") }} @if (true) bar="bob" @endif></div> HTML ], 15 => [ 0, <<<'HTML' <div @if ($object->method() && $object->property) foo="bar" @endif something="here"></div> HTML ], 16 => [ 0, <<<'HTML' <div something="here" @if ($object->method() && $object->property) foo="bar" @endif something="here"></div> HTML ], 17 => [ 0, <<<'HTML' <div @if ($object->method() && $object->method()) foo="bar" @endif something="here"></div> HTML ], 18 => [ 0, <<<'HTML' <div something="here" @if ($object->method() && $object->method()) foo="bar" @endif something="here"></div> HTML ], 19 => [ 1, <<<'HTML' <div> @forelse($posts as $post) ... @empty ... @endforelse </div> HTML ], 20 => [ 0, <<<'HTML' <div> @unlessfoo(true) <div class="col-span-3 text-right"> toots </div> @endunlessfoo </div> HTML, <<<'HTML' <div> @unlessfoo(true) <div class="col-span-3 text-right"> toots </div> @endunlessfoo </div> HTML ], 21 => [ 0, <<<'HTML' <div @if (0 < 1) bar="bob" @endif></div> HTML ], 22 => [ 0, <<<'HTML' <div @if (1 > 0 && 0 < 1) bar="bob" @endif></div> HTML ], 23 => [ 0, <<<'HTML' <div @if (1 > 0) bar="bob" @endif></div> HTML ], 24 => [ 1, <<<'HTML' <div> @empty($foo) ... @endempty </div> HTML ], 25 => [ 1, <<<'HTML' @IF(true) ... @ENDIF HTML ], 26 => [ 1, <<<'HTML' <div> @if ($someProperty > 0) <span> {{ $someProperty }} </span> @endif </div> HTML ], 27 => [ 1, <<<'HTML' <div> @if (preg_replace('/[^a-zA-Z]+/', '', $spinner)) <span> {{ $someProperty }} </span> @endif </div> HTML ], 28 => [ 2, <<<'HTML' <div> @forelse([1, 2] as $post) @foreach(range(0, 10) as $i) <span> {{ $i }} </span> @endforeach @empty <span> {{ $someProperty }} </span> @endforelse </div> HTML, <<<'HTML' <div> <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__empty_1 = true; $__currentLoopData = [1, 2]; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $post): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?> <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = range(0, 10); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $i): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?> <span> <?php echo e($i); ?> </span> <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?> <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?> <span> <?php echo e($someProperty); ?> </span> <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?> </div> HTML, ], 29 => [ 1, <<<'HTML' @if ($item > 2 && request()->is(str(url('/'))->replace('\\', '/'))) foo @endif HTML, <<<'HTML' <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($item > 2 && request()->is(str(url('/'))->replace('\\', '/'))): ?> foo <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?> HTML, ], 30 => [ 1, <<<'HTML' <div> @if (preg_replace('/[^a-zA-Z]+/', '', $spinner))<span> {{ $someProperty }} </span> @endif Else</div> HTML ], 31 => [ 1, <<<'HTML' <div> @for ($i=0; $i<3; $i++)<span> {{ $someProperty }} </span> @endfor Else</div> HTML ], 32 => [ 0, <<<'HTML' <style> @supports (filter: drop-shadow(0 0 0 #ccc)) { background-color: blue; } </style> HTML ], 33 => [ 0, <<<'HTML' <div> @@if (true) </div> HTML ], 34 => [ 0, <<<'HTML' <div> <script> @if (app()->environment('production')) console.debug('tracking enabled'); @else console.debug('tracking disabled'); @endif </script> </div> HTML ], 35 => [ 0, <<<'HTML' <div> <style> @if (app()->environment('local')) body { background-color: red; } @endif </style> </div> HTML ], 36 => [ 1, <<<'HTML' <div> <div id="label"> @if (now()->dayName === 'Friday') Friday @endif </div> <script type="text/javascript"> @if (now()->dayName === 'Friday') document.getElementById('label').style.color = 'red'; @endif </script> </div> HTML ], 37 => [ 2, <<<'HTML' <div> <div id="label"> @if (now()->dayName === 'Friday') Friday @endif </div> <script type="text/javascript"> @if (now()->dayName === 'Friday') document.getElementById('label').style.color = 'red'; @endif </script> <div id="label"> @if (now()->dayName === 'Friday') Friday @endif </div> </div> HTML ], ]; } protected function reloadFeatures() { // We need to remove these two precompilers so we can test if the // feature is disabled and whether they get registered again... $precompilers = \Livewire\invade(app('blade.compiler'))->precompilers; \Livewire\invade(app('blade.compiler'))->precompilers = array_filter($precompilers, function ($precompiler) { if (! $precompiler instanceof \Closure) return true; $closureClass = (new \ReflectionFunction($precompiler))->getClosureScopeClass()->getName(); return $closureClass !== SupportCompiledWireKeys::class && $closureClass !== SupportMorphAwareBladeCompilation::class; }); // We need to call these so provide gets called again to load the // new config and register the precompilers if required... ComponentHookRegistry::register(SupportMorphAwareBladeCompilation::class); ComponentHookRegistry::register(SupportCompiledWireKeys::class); } protected function compile($string) { $html = Blade::compileString($string); return $html; } protected function render($string, $data = []) { $html = Blade::render($string, $data); return $html; } protected function compileStatements($template) { $bladeCompiler = app('blade.compiler'); return $bladeCompiler->compileStatements($template); } protected function assertOccurrences($expected, $needle, $haystack) { $this->assertEquals($expected, count(explode($needle, $haystack)) - 1); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportMorphAwareBladeCompilation/SupportMorphAwareBladeCompilation.php
src/Features/SupportMorphAwareBladeCompilation/SupportMorphAwareBladeCompilation.php
<?php namespace Livewire\Features\SupportMorphAwareBladeCompilation; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Blade; use Livewire\ComponentHook; use Livewire\Livewire; use function Livewire\on; class SupportMorphAwareBladeCompilation extends ComponentHook { protected static $shouldInjectConditionalMarkers = false; protected static $shouldInjectLoopMarkers = false; public static function provide() { on('flush-state', function () { static::$shouldInjectConditionalMarkers = config('livewire.inject_morph_markers', true); static::$shouldInjectLoopMarkers = config('livewire.smart_wire_keys', true); }); static::$shouldInjectConditionalMarkers = config('livewire.inject_morph_markers', true); static::$shouldInjectLoopMarkers = config('livewire.smart_wire_keys', true); if (! static::$shouldInjectConditionalMarkers && ! static::$shouldInjectLoopMarkers) { return; } static::registerPrecompilers(); } public static function registerPrecompilers() { $directives = [ '@if' => '@endif', '@unless' => '@endunless', '@error' => '@enderror', '@isset' => '@endisset', '@empty' => '@endempty', '@auth' => '@endauth', '@guest' => '@endguest', '@switch' => '@endswitch', '@foreach' => '@endforeach', '@forelse' => '@endforelse', '@while' => '@endwhile', '@for' => '@endfor', ]; Blade::precompiler(function ($entire) use ($directives) { $conditions = \Livewire\invade(app('blade.compiler'))->conditions; foreach (array_keys($conditions) as $conditionalDirective) { $directives['@'.$conditionalDirective] = '@end'.$conditionalDirective; } $entire = static::compileDirectives($entire, $directives); return $entire; }); } /* * This method is a modified version of the Blade compiler's `compileStatements` method. * It finds all directives in the template, gets the expression if it has parentheses * and prefixes the opening directives and suffixes the closing directives. */ public static function compileDirectives($template, $directives) { $openings = array_keys($directives); $closings = array_values($directives); $openingDirectivesPattern = static::directivesPattern($openings); $closingDirectivesPattern = static::directivesPattern($closings); // This is for an `@empty` inside a `@forelse` loop, not `@empty()` conditional directive... $loopEmptyDirectivePattern = '/@empty(?!\s*\()/mUxi'; // First, let's match ALL blade directives on the page, not just conditionals... preg_match_all( '/\B@(@?\w+(?:::\w+)?)([ \t]*)(\( ( [\S\s]*? ) \))?/x', $template, $matches, PREG_OFFSET_CAPTURE ); if (empty($matches[0])) { return $template; } // Find all tags which shouldn't have directives processed inside them... $ignoredTags = ['script', 'style']; $excludedRanges = static::findIgnoredTagRanges($template, $ignoredTags); for ($i = count($matches[0]) - 1; $i >= 0; $i--) { $match = [ $matches[0][$i][0], $matches[1][$i][0], $matches[2][$i][0], $matches[3][$i][0] ?: null, $matches[4][$i][0] ?: null, ]; $matchPosition = $matches[0][$i][1]; // If the blade directive is escaped with an extra `@` then we don't want to process it... if (str($match[1])->startsWith('@')) { continue; } // Skip directives inside ignored tags... if (static::isInExcludedRange($matchPosition, $excludedRanges)) { continue; } // Here we check to see if we have properly found the closing parenthesis by // regex pattern or not, and will recursively continue on to the next ")" // then check again until the tokenizer confirms we find the right one. while ( isset($match[4]) && str($match[0])->endsWith(')') && ! static::hasEvenNumberOfParentheses($match[0]) ) { if (($after = str($template)->after($match[0])->toString()) === $template) { break; } $rest = str($after)->before(')'); if ( isset($matches[0][$i - 1]) && str($rest.')')->contains($matches[0][$i - 1][0]) ) { unset($matches[0][$i - 1]); $i--; } $match[0] = $match[0].$rest.')'; $match[3] = $match[3].$rest.')'; $match[4] = $match[4].$rest; } // Now we can check to see if the current Blade directive is a conditional, // and if so, prefix/suffix it with HTML comment morph markers... if (preg_match($openingDirectivesPattern, $match[0])) { $template = static::prefixOpeningDirective($match[0], $template, $matchPosition); } elseif (preg_match($closingDirectivesPattern, $match[0])) { $template = static::suffixClosingDirective($match[0], $template, $matchPosition); } elseif (preg_match($loopEmptyDirectivePattern, $match[0])) { $template = static::suffixLoopEmptyDirective($match[0], $template, $matchPosition); } } return $template; } protected static function prefixOpeningDirective($found, $template, $position) { $foundEscaped = preg_quote($found, '/'); $livewireCheckOpeningTag = '<?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?>'; $livewireCheckClosingTag = '<?php endif; ?>'; $prefix = ''; $suffix = ''; if (static::$shouldInjectConditionalMarkers) { $prefix = '<!--[if BLOCK]><![endif]-->'; } if (static::$shouldInjectLoopMarkers && static::isLoop($found)) { $prefix .= '<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?>'; $suffix .= '<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?>'; } if ($prefix === '' && $suffix === '') { return $template; } if ($prefix !== '') { $prefix = $livewireCheckOpeningTag.$prefix.$livewireCheckClosingTag; } if ($suffix !== '') { $suffix = $livewireCheckOpeningTag.$suffix.$livewireCheckClosingTag; } $prefixEscaped = preg_quote($prefix); $suffixEscaped = preg_quote($suffix); $pattern = "/(?<!{$prefixEscaped}){$foundEscaped}"; // If the suffix is not empty, then add it to the pattern... if ($suffixEscaped !== '') { $pattern .= "(?!{$suffixEscaped})"; } $pattern .= "(?![^<]*(?<![?=-])>)/mUi"; return static::replaceMatchIfNotInsideAHtmlTag($template, $position, $pattern, $found, $prefix, $suffix); } protected static function suffixClosingDirective($found, $template, $position) { // Opening directives can contain a space before the parens, but that causes issues with closing // directives. So we will just remove the trailing space if it exists... $found = rtrim($found); $foundEscaped = preg_quote($found, '/'); $livewireCheckOpeningTag = '<?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?>'; $livewireCheckClosingTag = '<?php endif; ?>'; $prefix = ''; $suffix = ''; if (static::$shouldInjectConditionalMarkers) { $suffix = '<!--[if ENDBLOCK]><![endif]-->'; } if (static::$shouldInjectLoopMarkers && static::isEndLoop($found)) { $prefix .= '<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?>'; $suffix .= '<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?>'; } if ($prefix === '' && $suffix === '') { return $template; } if ($prefix !== '') { $prefix = $livewireCheckOpeningTag.$prefix.$livewireCheckClosingTag; } if ($suffix !== '') { $suffix = $livewireCheckOpeningTag.$suffix.$livewireCheckClosingTag; } $prefixEscaped = preg_quote($prefix); $suffixEscaped = preg_quote($suffix); $pattern = "/"; // If the prefix is not empty, then add it to the pattern... if ($prefixEscaped !== '') { $pattern .= "(?<!{$prefixEscaped})"; } $pattern .= "{$foundEscaped}(?!\w)(?!{$suffixEscaped})(?![^<]*(?<![?=-])>)/mUi"; return static::replaceMatchIfNotInsideAHtmlTag($template, $position, $pattern, $found, $prefix, $suffix); } /* * This is for an `@empty` inside a `@forelse` loop, not `@empty()` conditional directive. When inside a `@forelse` loop, * it is the `@empty` directive that actually closes the loop, not the `@endelseif` directive. So we need to ensure we * target the `@empty` directive but not confuse it with the `@empty()` conditional directive... */ protected static function suffixLoopEmptyDirective($found, $template, $position) { // Opening directives can contain a space before the parens, but that causes issues with closing // directives. So we will just remove the trailing space if it exists... $found = rtrim($found); $foundEscaped = preg_quote($found, '/'); $livewireCheckOpeningTag = '<?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?>'; $livewireCheckClosingTag = '<?php endif; ?>'; $prefix = ''; $suffix = ''; if (static::$shouldInjectLoopMarkers) { $prefix = '<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?>'; $suffix = '<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?>'; } if ($prefix === '' && $suffix === '') { return $template; } if ($prefix !== '') { $prefix = $livewireCheckOpeningTag.$prefix.$livewireCheckClosingTag; } if ($suffix !== '') { $suffix = $livewireCheckOpeningTag.$suffix.$livewireCheckClosingTag; } $prefixEscaped = preg_quote($prefix); $suffixEscaped = preg_quote($suffix); $pattern = "/(?<!{$prefixEscaped}){$foundEscaped}(?!\s*\()(?!{$suffixEscaped})(?![^<]*(?<![?=-])>)/mUi"; return static::replaceMatchIfNotInsideAHtmlTag($template, $position, $pattern, $found, $prefix, $suffix); } protected static function isLoop($found) { $loopDirectives = [ 'foreach', 'forelse', // temp disabling because of "missing $loop" error // 'for', 'while', ]; $pattern = '/@(' . implode('|', $loopDirectives) . ')(?![a-zA-Z])/i'; return preg_match($pattern, $found); } protected static function isEndLoop($found) { $loopDirectives = [ 'endforeach', // This `endforelse` should NOT be included here, but it is left here for documentation purposes. The close of a `@forelse` loop is handled by the `@empty` directive... // 'endforelse', // 'endfor', 'endwhile', ]; $pattern = '/@(' . implode('|', $loopDirectives) . ')(?![a-zA-Z])/i'; return preg_match($pattern, $found); } protected static function directivesPattern($directives) { $directivesPattern = '(' .collect($directives) // Ensure longer directives are in the pattern before shorter ones... ->sortBy(fn ($directive) => strlen($directive), descending: true) // Only match directives that are an exact match and not ones that // simply start with the provided directive here... ->map(fn ($directive) => $directive.'(?![a-zA-Z])') // @empty is a special case in that it can be used as a standalone directive // and also within a @forelese statement. We only want to target when it's standalone // by enforcing @empty has an opening parenthesis after it when matching... ->map(fn ($directive) => str($directive)->startsWith('@empty') ? $directive.'[^\S\r\n]*\(' : $directive) ->join('|') .')'; // Blade directives: (@if|@foreach|...) $pattern = '/'.$directivesPattern.'/mUxi'; return $pattern; } protected static function hasEvenNumberOfParentheses(string $expression) { $tokens = token_get_all('<?php '.$expression); if (Arr::last($tokens) !== ')') { return false; } $opening = 0; $closing = 0; foreach ($tokens as $token) { if ($token == ')') { $closing++; } elseif ($token == '(') { $opening++; } } return $opening === $closing; } protected static function findIgnoredTagRanges(string $template, array $tags): array { if (empty($tags)) { return []; } $ranges = []; $escapedTags = array_map('preg_quote', $tags); $tagsPattern = implode('|', $escapedTags); // Match both opening and closing tags. This handles attributes like `<script type="text/javascript">`... preg_match_all( '/<('.$tagsPattern.')(?:\s[^>]*)?>|<\/('.$tagsPattern.')>/i', $template, $tagMatches, PREG_OFFSET_CAPTURE ); $stack = []; foreach ($tagMatches[0] as $tagMatch) { $tag = $tagMatch[0]; $position = $tagMatch[1]; // Check if it's an opening tag... if (preg_match('/<('.$tagsPattern.')/i', $tag, $typeMatch)) { $type = strtolower($typeMatch[1]); $stack[] = ['type' => $type, 'start' => $position]; } // Check if it's a closing tag... elseif (preg_match('/<\/('.$tagsPattern.')>/i', $tag, $typeMatch)) { $type = strtolower($typeMatch[1]); // Find the matching opening tag... for ($i = count($stack) - 1; $i >= 0; $i--) { if ($stack[$i]['type'] === $type) { $start = $stack[$i]['start']; $end = $position + strlen($tag); $ranges[] = [$start, $end]; array_splice($stack, $i, 1); break; } } } } return $ranges; } protected static function isInExcludedRange(int $position, array $ranges): bool { foreach ($ranges as [$start, $end]) { if ($position >= $start && $position < $end) { return true; } } return false; } protected static function replaceMatchIfNotInsideAHtmlTag(string $template, int $position, string $pattern, string $found, string $prefix, string $suffix): string { // Clamp the match position to the template bounds... $templateLength = strlen($template); $position = max(0, min($templateLength, (int) $position)); $before = substr($template, 0, $position); $after = substr($template, $position); if (! preg_match($pattern, $after, $afterMatch, PREG_OFFSET_CAPTURE) || $afterMatch[0][1] !== 0) { return $template; } // Remove the match from the beginning of the after string... $after = substr($after, strlen($afterMatch[0][0])); return $before.$prefix.$found.$suffix.$after; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPreserveScroll/BrowserTest.php
src/Features/SupportPreserveScroll/BrowserTest.php
<?php namespace Livewire\Features\SupportPreserveScroll; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_the_scroll_position_is_preserved_when_a_request_is_triggered() { Livewire::visit([ new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click.preserve-scroll.prepend="$refresh" wire:island="foo" dusk="refresh">Refresh</button> @island(name: 'foo', always: true) @foreach(range(1, 100) as $i) <div>{{ $i }}</div> @endforeach @endisland </div> HTML; } } ]) ->waitForLivewireToLoad() // Assert we can see the refresh button which is above the island which will have data prepended... ->assertInViewPort('@refresh') ->waitForLivewire()->click('@refresh') // Assert we can't see the refresh button as it should have been pushed off the top of the screen if scroll was preserved... ->assertNotInViewPort('@refresh') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/SupportConsoleCommands.php
src/Features/SupportConsoleCommands/SupportConsoleCommands.php
<?php namespace Livewire\Features\SupportConsoleCommands; use Illuminate\Console\Application as Artisan; use Livewire\ComponentHook; class SupportConsoleCommands extends ComponentHook { static function provide() { if (! app()->runningInConsole()) return; static::commands([ Commands\MakeCommand::class, // make:livewire Commands\LivewireMakeCommand::class, // livewire:make (alias) Commands\ConvertCommand::class, // livewire:convert Commands\FormCommand::class, // livewire:form Commands\AttributeCommand::class, // livewire:attribute Commands\LayoutCommand::class, // livewire:layout Commands\StubsCommand::class, // livewire:stubs Commands\S3CleanupCommand::class, // livewire:configure-s3-upload-cleanup Commands\PublishCommand::class, // livewire:publish Commands\ConfigCommand::class, // livewire:config ]); } static function commands($commands) { $commands = is_array($commands) ? $commands : func_get_args(); // Filter out null values $commands = array_filter($commands); Artisan::starting(fn(Artisan $artisan) => $artisan->resolveCommands($commands)); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Tests/AttributeCommandUnitTest.php
src/Features/SupportConsoleCommands/Tests/AttributeCommandUnitTest.php
<?php namespace Livewire\Features\SupportConsoleCommands\Tests; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Artisan; class AttributeCommandUnitTest extends \Tests\TestCase { public function test_attribute_is_created_by_attribute_command() { Artisan::call('livewire:attribute', ['name' => 'SampleAttribute']); $filePath = $this->livewireClassesPath('Attributes/SampleAttribute.php'); $this->assertTrue(File::exists($filePath)); $this->assertTrue(str(File::get($filePath))->contains('namespace App\Livewire\Attributes;')); } public function test_attribute_is_created_in_subdirectory_by_attribute_command() { Artisan::call('livewire:attribute', ['name' => 'Auth/SampleAttribute']); $filePath = $this->livewireClassesPath('Attributes/Auth/SampleAttribute.php'); $this->assertTrue(File::exists($filePath)); $this->assertTrue(str(File::get($filePath))->contains('namespace App\Livewire\Attributes\Auth;')); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Tests/LayoutCommandUnitTest.php
src/Features/SupportConsoleCommands/Tests/LayoutCommandUnitTest.php
<?php namespace Livewire\Features\SupportConsoleCommands\Tests; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Artisan; class LayoutCommandUnitTest extends \Tests\TestCase { public function test_layout_is_created_by_layout_command() { Artisan::call('livewire:layout'); $this->assertTrue(File::exists($this->livewireLayoutsPath('app.blade.php'))); } protected function livewireLayoutsPath($path = '') { return resource_path('views').'/layouts'.($path ? '/'.$path : ''); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Tests/StubCommandUnitTest.php
src/Features/SupportConsoleCommands/Tests/StubCommandUnitTest.php
<?php namespace Livewire\Features\SupportConsoleCommands\Tests; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Artisan; class StubCommandUnitTest extends \Tests\TestCase { public function setUp(): void { \Livewire\LivewireManager::$v4 = false; parent::setUp(); } public function test_default_view_stub_is_created() { Artisan::call('livewire:stubs'); $this->assertTrue(File::exists($this->stubsPath('livewire.stub'))); $this->assertTrue(File::exists($this->stubsPath('livewire.inline.stub'))); $this->assertTrue(File::exists($this->stubsPath('livewire.view.stub'))); $this->assertTrue(File::exists($this->stubsPath('livewire.test.stub'))); $this->assertTrue(File::exists($this->stubsPath('livewire.pest.stub'))); $this->assertTrue(File::exists($this->stubsPath('livewire.form.stub'))); $this->assertTrue(File::exists($this->stubsPath('livewire.attribute.stub'))); } public function test_component_is_created_with_view_and_class_custom_default_stubs() { Artisan::call('livewire:stubs'); File::append($this->stubsPath('livewire.stub'), '// comment default'); File::put($this->stubsPath('livewire.view.stub'), '<div>Default Test</div>'); Artisan::call('livewire:make', ['name' => 'foo', '--type' => 'class']); $this->assertTrue(File::exists($this->livewireClassesPath('Foo.php'))); $this->assertStringContainsString('// comment default', File::get($this->livewireClassesPath('Foo.php'))); $this->assertTrue(File::exists($this->livewireViewsPath('foo.blade.php'))); $this->assertStringContainsString('Default Test', File::get($this->livewireViewsPath('foo.blade.php'))); } public function test_form_is_created_with_class_custom_default_stubs() { Artisan::call('livewire:stubs'); File::append($this->stubsPath('livewire.form.stub'), '// form stub'); Artisan::call('livewire:form', ['name' => 'Foo']); $this->assertTrue(File::exists($this->livewireClassesPath('Forms/Foo.php'))); $this->assertStringContainsString('// form stub', File::get($this->livewireClassesPath('Forms/Foo.php'))); } public function test_attribute_is_created_with_class_custom_default_stubs() { Artisan::call('livewire:stubs'); File::append($this->stubsPath('livewire.attribute.stub'), '// attribute stub'); Artisan::call('livewire:attribute', ['name' => 'Foo']); $this->assertTrue(File::exists($this->livewireClassesPath('Attributes/Foo.php'))); $this->assertStringContainsString('// attribute stub', File::get($this->livewireClassesPath('Attributes/Foo.php'))); } protected function stubsPath($path = '') { return base_path('stubs'.($path ? '/'.$path : '')); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Tests/MakeCommandUnitTest.php
src/Features/SupportConsoleCommands/Tests/MakeCommandUnitTest.php
<?php namespace Livewire\Features\SupportConsoleCommands\Tests; use Illuminate\Contracts\Console\Kernel; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\File; use Livewire\Livewire; class MakeCommandUnitTest extends \Tests\TestCase { public function setUp(): void { parent::setUp(); // Ensure components are cleared before each test... $this->makeACleanSlate(); } public function test_single_file_component_is_created_by_default() { Artisan::call('make:livewire', ['name' => 'foo']); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo.blade.php'))); $this->assertFalse(File::exists($this->livewireClassesPath('Foo.php'))); $this->assertFalse(File::exists($this->livewireViewsPath('foo.blade.php'))); } public function test_single_file_component_without_emoji_when_disabled_in_config() { $this->app['config']->set('livewire.make_command.emoji', false); Artisan::call('make:livewire', ['name' => 'foo']); $this->assertTrue(File::exists($this->livewireComponentsPath('foo.blade.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡foo.blade.php'))); } public function test_single_file_component_with_sfc_flag() { Artisan::call('make:livewire', ['name' => 'foo', '--sfc' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo.blade.php'))); } public function test_multi_file_component_is_created_with_mfc_flag() { Artisan::call('make:livewire', ['name' => 'foo', '--mfc' => true]); $this->assertTrue(File::isDirectory($this->livewireComponentsPath('⚡foo'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo/foo.php'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo/foo.blade.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡foo/foo.test.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡foo/foo.js'))); } public function test_multi_file_component_with_javascript_when_js_flag_provided() { Artisan::call('make:livewire', ['name' => 'foo', '--mfc' => true, '--js' => true]); $this->assertTrue(File::isDirectory($this->livewireComponentsPath('⚡foo'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo/foo.php'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo/foo.blade.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡foo/foo.test.php'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo/foo.js'))); } public function test_class_based_component_is_created_with_class_flag() { Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('Foo.php'))); $this->assertTrue(File::exists($this->livewireViewsPath('foo.blade.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡foo.blade.php'))); } public function test_component_type_can_be_specified_with_type_option() { Artisan::call('make:livewire', ['name' => 'foo', '--type' => 'class']); $this->assertTrue(File::exists($this->livewireClassesPath('Foo.php'))); $this->assertTrue(File::exists($this->livewireViewsPath('foo.blade.php'))); $this->makeACleanSlate(); Artisan::call('make:livewire', ['name' => 'bar', '--type' => 'mfc']); $this->assertTrue(File::isDirectory($this->livewireComponentsPath('⚡bar'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡bar/bar.php'))); } public function test_dot_nested_component_is_created_correctly() { Artisan::call('make:livewire', ['name' => 'foo.bar']); $this->assertTrue(File::exists($this->livewireComponentsPath('foo/⚡bar.blade.php'))); $this->makeACleanSlate(); Artisan::call('make:livewire', ['name' => 'foo.bar', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('Foo/Bar.php'))); $this->assertTrue(File::exists($this->livewireViewsPath('foo/bar.blade.php'))); } public function test_forward_slash_nested_component_is_created_correctly() { Artisan::call('make:livewire', ['name' => 'foo/bar']); $this->assertTrue(File::exists($this->livewireComponentsPath('foo/⚡bar.blade.php'))); $this->makeACleanSlate(); Artisan::call('make:livewire', ['name' => 'foo/bar', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('Foo/Bar.php'))); $this->assertTrue(File::exists($this->livewireViewsPath('foo/bar.blade.php'))); } public function test_backslash_nested_component_is_created_correctly() { Artisan::call('make:livewire', ['name' => 'foo\\bar']); $this->assertTrue(File::exists($this->livewireComponentsPath('foo/⚡bar.blade.php'))); $this->makeACleanSlate(); Artisan::call('make:livewire', ['name' => 'foo\\bar', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('Foo/Bar.php'))); $this->assertTrue(File::exists($this->livewireViewsPath('foo/bar.blade.php'))); } public function test_multiword_component_is_created_with_kebab_case() { Artisan::call('make:livewire', ['name' => 'foo-bar']); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo-bar.blade.php'))); $this->makeACleanSlate(); Artisan::call('make:livewire', ['name' => 'foo-bar', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('FooBar.php'))); $this->assertTrue(File::exists($this->livewireViewsPath('foo-bar.blade.php'))); } public function test_pascal_case_component_is_automatically_converted() { Artisan::call('make:livewire', ['name' => 'FooBar']); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo-bar.blade.php'))); $this->makeACleanSlate(); Artisan::call('make:livewire', ['name' => 'FooBar.BazQux', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('FooBar/BazQux.php'))); $this->assertTrue(File::exists($this->livewireViewsPath('foo-bar/baz-qux.blade.php'))); } public function test_class_based_component_view_name_reference_matches_configured_view_path() { // We can't use Artisan::call here because we need to be able to set config vars. $this->app['config']->set('livewire.view_path', resource_path('views/not-livewire')); $this->app[Kernel::class]->call('make:livewire', ['name' => 'foo', '--class' => true]); $this->assertStringContainsString( "view('not-livewire.foo')", File::get($this->livewireClassesPath('Foo.php')) ); $this->assertTrue(File::exists(resource_path('views/not-livewire/foo.blade.php'))); } public function test_class_based_component_already_exists_shows_error() { // Create initial component Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('Foo.php'))); // Try to create again $exitCode = Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $this->assertEquals(1, $exitCode); } public function test_multi_file_component_already_exists_shows_error() { // Create initial component Artisan::call('make:livewire', ['name' => 'foo', '--mfc' => true]); $this->assertTrue(File::isDirectory($this->livewireComponentsPath('⚡foo'))); // Try to create again $exitCode = Artisan::call('make:livewire', ['name' => 'foo', '--mfc' => true]); $this->assertEquals(1, $exitCode); } public function test_single_file_component_content_structure() { Artisan::call('make:livewire', ['name' => 'test-component']); $content = File::get($this->livewireComponentsPath('⚡test-component.blade.php')); $this->assertStringContainsString('<?php', $content); $this->assertStringContainsString('use Livewire\Component;', $content); $this->assertStringContainsString('new class extends Component', $content); $this->assertStringContainsString('?>', $content); $this->assertStringContainsString('<div>', $content); } public function test_class_based_component_content_structure() { Artisan::call('make:livewire', ['name' => 'test-component', '--class' => true]); $classContent = File::get($this->livewireClassesPath('TestComponent.php')); $viewContent = File::get($this->livewireViewsPath('test-component.blade.php')); // Check class file $this->assertStringContainsString('namespace App\Livewire;', $classContent); $this->assertStringContainsString('use Livewire\Component;', $classContent); $this->assertStringContainsString('class TestComponent extends Component', $classContent); $this->assertStringContainsString("view('livewire.test-component')", $classContent); // Check view file $this->assertStringContainsString('<div>', $viewContent); } public function test_multi_file_component_content_structure() { Artisan::call('make:livewire', ['name' => 'test-component', '--mfc' => true, '--test' => true]); $classContent = File::get($this->livewireComponentsPath('⚡test-component/test-component.php')); $viewContent = File::get($this->livewireComponentsPath('⚡test-component/test-component.blade.php')); $testContent = File::get($this->livewireComponentsPath('⚡test-component/test-component.test.php')); // Check class file $this->assertStringContainsString('use Livewire\Component;', $classContent); $this->assertStringContainsString('new class extends Component', $classContent); // Check view file $this->assertStringContainsString('<div>', $viewContent); // Check test file $this->assertStringContainsString("it('renders successfully'", $testContent); $this->assertStringContainsString('test-component', $testContent); } public function test_default_component_type_can_be_configured() { // Test default SFC $this->app['config']->set('livewire.make_command.type', 'sfc'); Artisan::call('make:livewire', ['name' => 'default-sfc']); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡default-sfc.blade.php'))); $this->makeACleanSlate(); // Test default MFC $this->app['config']->set('livewire.make_command.type', 'mfc'); Artisan::call('make:livewire', ['name' => 'default-mfc']); $this->assertTrue(File::isDirectory($this->livewireComponentsPath('⚡default-mfc'))); $this->makeACleanSlate(); // Test default class $this->app['config']->set('livewire.make_command.type', 'class'); Artisan::call('make:livewire', ['name' => 'default-class']); $this->assertTrue(File::exists($this->livewireClassesPath('DefaultClass.php'))); } public function test_class_based_component_view_in_livewire_folder_is_not_mistaken_for_sfc() { // This test demonstrates the issue where a class-based component's view // in resources/views/livewire/ might be mistaken for an SFC // First, create a class-based component Artisan::call('make:livewire', ['name' => 'existing-class', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('ExistingClass.php'))); $this->assertTrue(File::exists($this->livewireViewsPath('existing-class.blade.php'))); // Now try to create an SFC with the same name // The system should recognize the existing class-based component // and not mistake its view for an SFC $exitCode = Artisan::call('make:livewire', ['name' => 'existing-class']); // It should fail because component already exists (as class-based) $this->assertEquals(1, $exitCode); // The SFC should NOT have been created $this->assertFalse(File::exists($this->livewireComponentsPath('⚡existing-class.blade.php'))); } public function test_single_file_component_is_created_in_pages_namespace() { Artisan::call('make:livewire', ['name' => 'pages::create-post']); $this->assertTrue(File::exists(resource_path('views/pages/⚡create-post.blade.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡create-post.blade.php'))); } public function test_nested_single_file_component_is_created_in_pages_namespace() { Artisan::call('make:livewire', ['name' => 'pages::blog.create-post']); $this->assertTrue(File::exists(resource_path('views/pages/blog/⚡create-post.blade.php'))); } public function test_multi_file_component_is_created_in_pages_namespace() { Artisan::call('make:livewire', ['name' => 'pages::dashboard', '--mfc' => true]); $this->assertTrue(File::isDirectory(resource_path('views/pages/⚡dashboard'))); $this->assertTrue(File::exists(resource_path('views/pages/⚡dashboard/dashboard.php'))); $this->assertTrue(File::exists(resource_path('views/pages/⚡dashboard/dashboard.blade.php'))); } public function test_class_component_is_created_in_namespace() { File::deleteDirectory(app_path('Foo')); File::deleteDirectory(resource_path('views/foo')); Livewire::addNamespace( namespace: 'foo', classNamespace: 'App\Foo', classPath: app_path('Foo'), classViewPath: resource_path('views/foo'), ); Artisan::call('make:livewire', ['name' => 'foo::bar', '--class' => true]); $this->assertTrue(File::exists(resource_path('views/foo/bar.blade.php'))); $this->assertTrue(File::exists(app_path('Foo/Bar.php'))); $contents = File::get(app_path('Foo/Bar.php')); $this->assertStringContainsString('namespace App\Foo;', $contents); $this->assertStringContainsString('class Bar extends Component', $contents); $this->assertStringContainsString("view('foo.bar')", $contents); } public function test_component_is_created_in_layouts_namespace() { Artisan::call('make:livewire', ['name' => 'layouts::sidebar']); $this->assertTrue(File::exists(resource_path('views/layouts/⚡sidebar.blade.php'))); } public function test_custom_namespace_from_config_works() { // Set the custom namespace in config $adminPath = resource_path('views/admin'); $this->app['config']->set('livewire.component_namespaces.admin', $adminPath); // Register the namespace with all the necessary systems (mimicking what LivewireServiceProvider does) app('livewire.finder')->addNamespace('admin', viewPath: $adminPath); app('blade.compiler')->anonymousComponentPath($adminPath, 'admin'); app('view')->addNamespace('admin', $adminPath); Artisan::call('make:livewire', ['name' => 'admin::users-table']); $this->assertTrue(File::exists($adminPath . '/⚡users-table.blade.php')); } public function test_namespace_works_without_emoji() { $this->app['config']->set('livewire.make_command.emoji', false); Artisan::call('make:livewire', ['name' => 'pages::settings']); $this->assertTrue(File::exists(resource_path('views/pages/settings.blade.php'))); $this->assertFalse(File::exists(resource_path('views/pages/⚡settings.blade.php'))); } public function test_namespace_with_deeply_nested_components() { Artisan::call('make:livewire', ['name' => 'pages::blog.posts.create-post']); $this->assertTrue(File::exists(resource_path('views/pages/blog/posts/⚡create-post.blade.php'))); } public function test_single_file_component_with_test_flag_creates_test_file() { Artisan::call('make:livewire', ['name' => 'foo', '--test' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo.blade.php'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo.test.php'))); $testContent = File::get($this->livewireComponentsPath('⚡foo.test.php')); $this->assertStringContainsString("it('renders successfully'", $testContent); $this->assertStringContainsString('foo', $testContent); } public function test_single_file_component_with_test_flag_without_emoji() { $this->app['config']->set('livewire.make_command.emoji', false); Artisan::call('make:livewire', ['name' => 'bar', '--test' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('bar.blade.php'))); $this->assertTrue(File::exists($this->livewireComponentsPath('bar.test.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡bar.test.php'))); } public function test_nested_single_file_component_with_test_flag() { Artisan::call('make:livewire', ['name' => 'admin.users', '--test' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('admin/⚡users.blade.php'))); $this->assertTrue(File::exists($this->livewireComponentsPath('admin/⚡users.test.php'))); } public function test_converting_single_file_to_multi_file_preserves_test_file() { // Create SFC with test Artisan::call('make:livewire', ['name' => 'foo', '--test' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo.blade.php'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo.test.php'))); // Convert to MFC Artisan::call('livewire:convert', ['name' => 'foo', '--mfc' => true]); // Check that test file was moved into MFC directory $this->assertTrue(File::isDirectory($this->livewireComponentsPath('⚡foo'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡foo/foo.test.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡foo.test.php'))); $testContent = File::get($this->livewireComponentsPath('⚡foo/foo.test.php')); $this->assertStringContainsString("it('renders successfully'", $testContent); } public function test_converting_multi_file_to_single_file_preserves_test_file() { // Create MFC with test Artisan::call('make:livewire', ['name' => 'bar', '--mfc' => true, '--test' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡bar/bar.test.php'))); // Convert to SFC Artisan::call('livewire:convert', ['name' => 'bar', '--sfc' => true]); // Check that test file was moved out of MFC directory $this->assertTrue(File::exists($this->livewireComponentsPath('⚡bar.blade.php'))); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡bar.test.php'))); $this->assertFalse(File::isDirectory($this->livewireComponentsPath('⚡bar'))); $testContent = File::get($this->livewireComponentsPath('⚡bar.test.php')); $this->assertStringContainsString("it('renders successfully'", $testContent); } public function test_converting_sfc_to_mfc_without_test_flag_preserves_existing_test() { // Create SFC with test Artisan::call('make:livewire', ['name' => 'baz', '--test' => true]); // Convert to MFC without --test flag (should still preserve test) Artisan::call('livewire:convert', ['name' => 'baz', '--mfc' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡baz/baz.test.php'))); } public function test_converting_sfc_to_mfc_with_test_flag_creates_test_when_none_exists() { // Create SFC without test Artisan::call('make:livewire', ['name' => 'qux']); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡qux.test.php'))); // Convert to MFC with --test flag Artisan::call('livewire:convert', ['name' => 'qux', '--mfc' => true, '--test' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡qux/qux.test.php'))); } public function test_converting_mfc_to_sfc_without_test_file_works() { // Create MFC without test Artisan::call('make:livewire', ['name' => 'quux', '--mfc' => true]); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡quux/quux.test.php'))); // Convert to SFC Artisan::call('livewire:convert', ['name' => 'quux', '--sfc' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡quux.blade.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡quux.test.php'))); } public function test_test_flag_creates_test_for_existing_single_file_component() { // Create SFC without test Artisan::call('make:livewire', ['name' => 'existing-sfc']); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡existing-sfc.blade.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡existing-sfc.test.php'))); // Create test for existing component $exitCode = Artisan::call('make:livewire', ['name' => 'existing-sfc', '--test' => true]); $this->assertEquals(0, $exitCode); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡existing-sfc.test.php'))); $testContent = File::get($this->livewireComponentsPath('⚡existing-sfc.test.php')); $this->assertStringContainsString("it('renders successfully'", $testContent); $this->assertStringContainsString('existing-sfc', $testContent); } public function test_test_flag_creates_test_for_existing_multi_file_component() { // Create MFC without test Artisan::call('make:livewire', ['name' => 'existing-mfc', '--mfc' => true]); $this->assertTrue(File::isDirectory($this->livewireComponentsPath('⚡existing-mfc'))); $this->assertFalse(File::exists($this->livewireComponentsPath('⚡existing-mfc/existing-mfc.test.php'))); // Create test for existing component $exitCode = Artisan::call('make:livewire', ['name' => 'existing-mfc', '--test' => true]); $this->assertEquals(0, $exitCode); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡existing-mfc/existing-mfc.test.php'))); $testContent = File::get($this->livewireComponentsPath('⚡existing-mfc/existing-mfc.test.php')); $this->assertStringContainsString("it('renders successfully'", $testContent); $this->assertStringContainsString('existing-mfc', $testContent); } public function test_test_flag_creates_test_for_existing_class_based_component() { // Create class-based component Artisan::call('make:livewire', ['name' => 'existing-class', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('ExistingClass.php'))); $this->assertFalse(File::exists($this->livewireTestsPath('ExistingClassTest.php'))); // Create test for existing component $exitCode = Artisan::call('make:livewire', ['name' => 'existing-class', '--test' => true]); $this->assertEquals(0, $exitCode); $this->assertTrue(File::exists($this->livewireTestsPath('ExistingClassTest.php'))); $testContent = File::get($this->livewireTestsPath('ExistingClassTest.php')); $this->assertStringContainsString("it('renders successfully'", $testContent); $this->assertStringContainsString('existing-class', $testContent); } public function test_test_flag_for_existing_component_errors_when_test_already_exists() { // Create SFC with test Artisan::call('make:livewire', ['name' => 'with-test', '--test' => true]); $this->assertTrue(File::exists($this->livewireComponentsPath('⚡with-test.test.php'))); // Try to create test again $exitCode = Artisan::call('make:livewire', ['name' => 'with-test', '--test' => true]); $this->assertEquals(1, $exitCode); } public function test_test_flag_for_nested_existing_component() { // Create nested SFC without test Artisan::call('make:livewire', ['name' => 'admin.settings']); $this->assertTrue(File::exists($this->livewireComponentsPath('admin/⚡settings.blade.php'))); $this->assertFalse(File::exists($this->livewireComponentsPath('admin/⚡settings.test.php'))); // Create test for existing component $exitCode = Artisan::call('make:livewire', ['name' => 'admin.settings', '--test' => true]); $this->assertEquals(0, $exitCode); $this->assertTrue(File::exists($this->livewireComponentsPath('admin/⚡settings.test.php'))); $testContent = File::get($this->livewireComponentsPath('admin/⚡settings.test.php')); $this->assertStringContainsString('admin.settings', $testContent); } public function test_test_flag_for_nested_existing_class_based_component() { // Create nested class-based component Artisan::call('make:livewire', ['name' => 'admin.dashboard', '--class' => true]); $this->assertTrue(File::exists($this->livewireClassesPath('Admin/Dashboard.php'))); $this->assertFalse(File::exists($this->livewireTestsPath('Admin/DashboardTest.php'))); // Create test for existing component $exitCode = Artisan::call('make:livewire', ['name' => 'admin.dashboard', '--test' => true]); $this->assertEquals(0, $exitCode); $this->assertTrue(File::exists($this->livewireTestsPath('Admin/DashboardTest.php'))); $testContent = File::get($this->livewireTestsPath('Admin/DashboardTest.php')); $this->assertStringContainsString('admin.dashboard', $testContent); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Tests/FormCommandUnitTest.php
src/Features/SupportConsoleCommands/Tests/FormCommandUnitTest.php
<?php namespace Livewire\Features\SupportConsoleCommands\Tests; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Artisan; class FormCommandUnitTest extends \Tests\TestCase { public function test_form_object_is_created_by_form_command() { Artisan::call('livewire:form', ['name' => 'SampleForm']); $filePath = $this->livewireClassesPath('Forms/SampleForm.php'); $this->assertTrue(File::exists($filePath)); $this->assertTrue(str(File::get($filePath))->contains('namespace App\Livewire\Forms;')); } public function test_form_object_is_created_in_subdirectory_by_form_command() { Artisan::call('livewire:form', ['name' => 'Auth/SampleForm']); $filePath = $this->livewireClassesPath('Forms/Auth/SampleForm.php'); $this->assertTrue(File::exists($filePath)); $this->assertTrue(str(File::get($filePath))->contains('namespace App\Livewire\Forms\Auth;')); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/MakeCommand.php
src/Features/SupportConsoleCommands/Commands/MakeCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use function Laravel\Prompts\text; use function Laravel\Prompts\confirm; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Attribute\AsCommand; use Livewire\Finder\Finder; use Livewire\Compiler\Parser\SingleFileParser; use Livewire\Compiler\Compiler; use Illuminate\Support\Str; use Illuminate\Foundation\Inspiring; use Illuminate\Filesystem\Filesystem; use Illuminate\Console\Command; #[AsCommand(name: 'make:livewire')] class MakeCommand extends Command { protected $name = 'make:livewire'; protected $description = 'Create a new Livewire component'; protected Filesystem $files; protected Finder $finder; protected Compiler $compiler; public function __construct() { parent::__construct(); $this->files = app('files'); $this->finder = app('livewire.finder'); $this->compiler = app('livewire.compiler'); } public function handle() { $name = $this->argument('name'); if (! $name) { $name = text('What should the component be named?', required: true); } $name = $this->normalizeComponentName($name); // If --test flag is provided and component already exists, just create the test if ($this->option('test') && $this->componentExistsInAnyForm($name)) { return $this->createTestForExistingComponent($name); } // Check if component already exists in ANY form before proceeding if ($this->componentExistsInAnyForm($name)) { $this->components->error('Component already exists.'); return 1; } $type = $this->determineComponentType( config('livewire.make_command.type', 'sfc'), ); switch ($type) { case 'class': return $this->createClassBasedComponent($name); case 'mfc': return $this->createMultiFileComponent($name); case 'sfc': default: return $this->createSingleFileComponent($name); } } protected function normalizeComponentName(string $name): string { return (string) str($name) ->replace('/', '.') ->replace('\\', '.') ->explode('.') ->map(fn ($i) => str($i)->kebab()) ->implode('.'); } protected function determineComponentType($fallback): string { if ($this->option('class')) { return 'class'; } if ($this->option('mfc')) { return 'mfc'; } if ($this->option('sfc')) { return 'sfc'; } if ($this->option('type')) { return $this->option('type'); } return $fallback; } protected function createClassBasedComponent(string $name): int { [$namespace, $componentName] = $this->finder->parseNamespaceAndName($name); if ($namespace !== null) { $classNamespaceDetails = $this->finder->getClassNamespace($namespace); if ($classNamespaceDetails === null) { $this->components->error('Namespace not found.'); return 1; } } else { $classNamespaceDetails = null; } $paths = $this->finder->resolveClassComponentFilePaths($name); $this->ensureDirectoryExists(dirname($paths['class'])); $this->ensureDirectoryExists(dirname($paths['view'])); $classContent = $this->buildClassBasedComponentClass($componentName, $classNamespaceDetails); $viewContent = $this->buildClassBasedComponentView(); $this->files->put($paths['class'], $classContent); $this->files->put($paths['view'], $viewContent); $this->components->info(sprintf('Livewire component [%s] created successfully.', $paths['class'])); return 0; } protected function createSingleFileComponent(string $name): int { $path = $this->finder->resolveSingleFileComponentPathForCreation($name); // Check if we're converting from a multi-file component $mfcPath = $this->finder->resolveMultiFileComponentPath($name); if ($mfcPath && $this->files->exists($mfcPath) && $this->files->isDirectory($mfcPath)) { // Skip interactive prompts in testing environment if (app()->runningUnitTests()) { $this->components->error('Component already exists.'); return 1; } $convert = confirm('Component already exists as a multi-file component. Would you like to convert it to a single-file component?'); if ($convert) { return $this->call('livewire:convert', ['name' => $name, '--sfc' => true]); } $this->components->error('Component already exists.'); return 1; } if ($this->files->exists($path)) { // Skip interactive prompts in testing environment if (app()->runningUnitTests()) { $this->components->error('Component already exists.'); return 1; } $upgrade = confirm('Component already exists. Would you like to upgrade this component to a multi-file component?'); if ($upgrade) { return $this->call('livewire:convert', ['name' => $name, '--mfc' => true]); } $this->components->error('Component already exists.'); return 1; } $this->ensureDirectoryExists(dirname($path)); $content = $this->buildSingleFileComponent(); $this->files->put($path, $content); // Create test file if --test flag is present if ($this->option('test')) { $testPath = $this->getSingleFileComponentTestPath($path); $testContent = $this->buildSingleFileComponentTest($name); $this->files->put($testPath, $testContent); } $this->components->info(sprintf('Livewire component [%s] created successfully.', $path)); return 0; } protected function createMultiFileComponent(string $name): int { $directory = $this->finder->resolveMultiFileComponentPathForCreation($name); // Get the component name without emoji for file names inside the directory $componentName = basename($directory); if ($this->shouldUseEmoji()) { $componentName = str_replace(['⚡', '⚡︎', '⚡️'], '', $componentName); } // Define file paths $classPath = $directory . '/' . $componentName . '.php'; $viewPath = $directory . '/' . $componentName . '.blade.php'; $testPath = $directory . '/' . $componentName . '.test.php'; $jsPath = $directory . '/' . $componentName . '.js'; // Check if we're upgrading from a single-file component $sfcPath = $this->finder->resolveSingleFileComponentPathForCreation($name); if ($this->files->exists($sfcPath)) { // Skip interactive prompts in testing environment if (app()->runningUnitTests()) { $this->components->error('Component already exists.'); return 1; } $upgrade = confirm('Component already exists as a single-file component. Would you like to upgrade it to a multi-file component?'); if ($upgrade) { return $this->call('livewire:convert', ['name' => $name, '--mfc' => true]); } $this->components->error('Component already exists.'); return 1; } if ($this->files->exists($directory)) { $this->components->error('Component already exists.'); return 1; } $this->ensureDirectoryExists($directory); $classContent = $this->buildMultiFileComponentClass(); $viewContent = $this->buildMultiFileComponentView(); $testContent = $this->buildMultiFileComponentTest($name); $jsContent = $this->buildMultiFileComponentJs(); $this->files->put($classPath, $classContent); $this->files->put($viewPath, $viewContent); if ($this->option('test')) { $this->files->put($testPath, $testContent); } if ($this->option('js')) { $this->files->put($jsPath, $jsContent); } $this->components->info(sprintf('Livewire component [%s] created successfully.', $directory)); return 0; } protected function shouldUseEmoji(): bool { if ($this->option('emoji') !== null) { return filter_var($this->option('emoji'), FILTER_VALIDATE_BOOLEAN); } return config('livewire.make_command.emoji', true); } protected function buildClassBasedComponentClass(string $componentName, ?array $classNamespaceDetails = null): string { $stub = $this->files->get($this->getStubPath('livewire.stub')); $segments = explode('.', $componentName); $className = Str::studly(end($segments)); $namespaceSegments = array_slice($segments, 0, -1); if ($classNamespaceDetails !== null) { $namespace = $classNamespaceDetails['classNamespace']; $viewPath = $classNamespaceDetails['classViewPath']; } else { $namespace = 'App\\Livewire'; $viewPath = config('livewire.view_path', resource_path('views/livewire')); } if (! empty($namespaceSegments)) { $namespace .= '\\' . collect($namespaceSegments) ->map(fn($segment) => Str::studly($segment)) ->implode('\\'); } // Get the configured view path and extract the view namespace from it $viewNamespace = $this->extractViewNamespace($viewPath); $viewName = $viewNamespace . '.' . collect($segments) ->map(fn($segment) => Str::kebab($segment)) ->implode('.'); $stub = str_replace('[namespace]', $namespace, $stub); $stub = str_replace('[class]', $className, $stub); $stub = str_replace('[view]', $viewName, $stub); return $stub; } protected function buildClassBasedComponentView(): string { $stub = $this->files->get($this->getStubPath('livewire.view.stub')); $stub = str_replace('[quote]', Inspiring::quotes()->random(), $stub); return $stub; } protected function buildSingleFileComponent(): string { $stub = $this->files->get($this->getStubPath('livewire-sfc.stub')); $stub = str_replace('[quote]', Inspiring::quotes()->random(), $stub); return $stub; } protected function buildMultiFileComponentClass(): string { return $this->files->get($this->getStubPath('livewire-mfc-class.stub')); } protected function buildMultiFileComponentView(): string { $stub = $this->files->get($this->getStubPath('livewire-mfc-view.stub')); $stub = str_replace('[quote]', Inspiring::quotes()->random(), $stub); return $stub; } protected function buildMultiFileComponentTest(string $name): string { $stub = $this->files->get($this->getStubPath('livewire-mfc-test.stub')); $componentName = collect(explode('.', $name)) ->map(fn($segment) => Str::kebab($segment)) ->implode('.'); $stub = str_replace('[component-name]', $componentName, $stub); return $stub; } protected function buildMultiFileComponentJs(): string { return $this->files->get($this->getStubPath('livewire-mfc-js.stub')); } protected function getSingleFileComponentTestPath(string $sfcPath): string { // Convert: /path/⚡foo.blade.php → /path/⚡foo.test.php return str_replace('.blade.php', '.test.php', $sfcPath); } protected function buildSingleFileComponentTest(string $name): string { // Use same stub as MFC, same format $stub = $this->files->get($this->getStubPath('livewire-mfc-test.stub')); $componentName = collect(explode('.', $name)) ->map(fn($segment) => Str::kebab($segment)) ->implode('.'); $stub = str_replace('[component-name]', $componentName, $stub); return $stub; } protected function getClassBasedComponentTestPath(string $name): string { $segments = explode('.', $name); $className = Str::studly(end($segments)) . 'Test'; $namespaceSegments = array_slice($segments, 0, -1); $path = base_path('tests/Feature/Livewire'); if (! empty($namespaceSegments)) { $path .= '/' . collect($namespaceSegments) ->map(fn($segment) => Str::studly($segment)) ->implode('/'); } return $path . '/' . $className . '.php'; } protected function buildClassBasedComponentTest(string $name): string { // Use same Pest-style stub as MFC/SFC for consistency $stub = $this->files->get($this->getStubPath('livewire-mfc-test.stub')); $componentName = collect(explode('.', $name)) ->map(fn($segment) => Str::kebab($segment)) ->implode('.'); $stub = str_replace('[component-name]', $componentName, $stub); return $stub; } protected function getStubPath(string $stub): string { $customPath = $this->laravel->basePath('stubs/' . $stub); if ($this->files->exists($customPath)) { return $customPath; } return __DIR__ . '/' . $stub; } protected function ensureDirectoryExists(string $path): void { if (! $this->files->isDirectory($path)) { $this->files->makeDirectory($path, 0755, true, true); } } protected function extractViewNamespace(string $viewPath): string { // Convert the view path to a namespace // e.g., resource_path('views/livewire') => 'livewire' // e.g., resource_path('views/not-livewire') => 'not-livewire' $viewsPath = resource_path('views'); // Remove the base views path to get the relative path $relativePath = str_replace($viewsPath . DIRECTORY_SEPARATOR, '', $viewPath); $relativePath = str_replace($viewsPath . '/', '', $relativePath); // Convert directory separators to dots for the namespace return str_replace(['/', '\\'], '.', $relativePath); } protected function componentExistsInAnyForm(string $name): bool { $finder = $this->finder; // Check for multi-file component $mfcPath = $finder->resolveMultiFileComponentPath($name); if ($mfcPath && $this->files->exists($mfcPath) && $this->files->isDirectory($mfcPath)) { return true; } // Check for single-file component $sfcPath = $finder->resolveSingleFileComponentPathForCreation($name); if ($this->files->exists($sfcPath)) { return true; } // Check for class-based component $paths = $finder->resolveClassComponentFilePaths($name); if (isset($paths['class']) && $this->files->exists($paths['class'])) { return true; } return false; } protected function createTestForExistingComponent(string $name): int { $finder = $this->finder; // Check for multi-file component first $mfcPath = $finder->resolveMultiFileComponentPath($name); if ($mfcPath && $this->files->exists($mfcPath) && $this->files->isDirectory($mfcPath)) { $componentName = basename($mfcPath); if ($this->shouldUseEmoji()) { $componentName = str_replace(['⚡', '⚡︎', '⚡️'], '', $componentName); } $testPath = $mfcPath . '/' . $componentName . '.test.php'; if ($this->files->exists($testPath)) { $this->components->error('Test file already exists.'); return 1; } $testContent = $this->buildMultiFileComponentTest($name); $this->files->put($testPath, $testContent); $this->components->info(sprintf('Livewire test [%s] created successfully.', $testPath)); return 0; } // Check for single-file component $sfcPath = $finder->resolveSingleFileComponentPathForCreation($name); if ($this->files->exists($sfcPath)) { $testPath = $this->getSingleFileComponentTestPath($sfcPath); if ($this->files->exists($testPath)) { $this->components->error('Test file already exists.'); return 1; } $testContent = $this->buildSingleFileComponentTest($name); $this->files->put($testPath, $testContent); $this->components->info(sprintf('Livewire test [%s] created successfully.', $testPath)); return 0; } // Check for class-based component $paths = $finder->resolveClassComponentFilePaths($name); if (isset($paths['class']) && $this->files->exists($paths['class'])) { // For class-based components, create test in tests/Feature/Livewire directory $testPath = $this->getClassBasedComponentTestPath($name); $this->ensureDirectoryExists(dirname($testPath)); if ($this->files->exists($testPath)) { $this->components->error('Test file already exists.'); return 1; } $testContent = $this->buildClassBasedComponentTest($name); $this->files->put($testPath, $testContent); $this->components->info(sprintf('Livewire test [%s] created successfully.', $testPath)); return 0; } $this->components->error('Component not found.'); return 1; } protected function getArguments() { return [ ['name', InputArgument::OPTIONAL, 'The name of the component'], ]; } protected function getOptions() { return [ ['sfc', null, InputOption::VALUE_NONE, 'Create a single-file component'], ['mfc', null, InputOption::VALUE_NONE, 'Create a multi-file component'], ['class', null, InputOption::VALUE_NONE, 'Create a class-based component'], ['type', null, InputOption::VALUE_REQUIRED, 'Component type (sfc, mfc, or class)'], ['test', null, InputOption::VALUE_NONE, 'Create a test file'], ['emoji', null, InputOption::VALUE_REQUIRED, 'Use emoji in file/directory names (true or false)'], ['js', null, InputOption::VALUE_NONE, 'Create a JavaScript file for multi-file components'], ]; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/ConfigCommand.php
src/Features/SupportConsoleCommands/Commands/ConfigCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'livewire:config')] class ConfigCommand extends Command { protected $signature = 'livewire:config'; protected $description = 'Publish Livewire config file'; public function handle() { $this->call('vendor:publish', ['--tag' => 'livewire:config', '--force' => true]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/LayoutCommand.php
src/Features/SupportConsoleCommands/Commands/LayoutCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'livewire:layout')] class LayoutCommand extends FileManipulationCommand { protected $signature = 'livewire:layout {--force} {--stub= : If you have several stubs, stored in subfolders }'; protected $description = 'Create a new app layout file'; public function handle() { $baseViewPath = resource_path('views'); $layout = str(config('livewire.component_layout')); $layoutPath = $this->layoutPath($baseViewPath, $layout); $relativeLayoutPath = $this->relativeLayoutPath($layoutPath); $force = $this->option('force'); $stubPath = $this->stubPath($this->option('stub')); if (File::exists($layoutPath) && ! $force) { $this->line("<fg=red;options=bold>View already exists:</> {$relativeLayoutPath}"); return false; } $this->ensureDirectoryExists($layoutPath); $result = File::copy($stubPath, $layoutPath); if ($result) { $this->line("<options=bold,reverse;fg=green> LAYOUT CREATED </> 🤙\n"); $this->line("<options=bold;fg=green>CLASS:</> {$relativeLayoutPath}"); } } protected function stubPath($stubSubDirectory = '') { $stubName = 'livewire.layout.stub'; if (! empty($stubSubDirectory) && str($stubSubDirectory)->startsWith('..')) { $stubDirectory = rtrim(str($stubSubDirectory)->replaceFirst('..' . DIRECTORY_SEPARATOR, ''), DIRECTORY_SEPARATOR) . '/'; } else { $stubDirectory = rtrim('stubs' . DIRECTORY_SEPARATOR . $stubSubDirectory, DIRECTORY_SEPARATOR) . '/'; } if (File::exists($stubPath = base_path($stubDirectory . $stubName))) { return $stubPath; } return __DIR__ . DIRECTORY_SEPARATOR . $stubName; } protected function layoutPath($baseViewPath, $layout) { // Handle namespaced views like 'layouts::app' if ($layout->contains('::')) { [$namespace, $name] = $layout->explode('::'); // Check if this namespace is registered in Livewire config $namespacePath = config("livewire.component_namespaces.{$namespace}"); if ($namespacePath) { // Use the configured namespace path $baseViewPath = $namespacePath; } else { // Default to resources/views/{namespace} $baseViewPath = resource_path("views/{$namespace}"); } // Now process the name part (e.g., 'app' or 'admin.dashboard') $directories = str($name)->explode('.'); } else { // Non-namespaced view, process normally $directories = $layout->explode('.'); } $name = Str::kebab($directories->pop()); return $baseViewPath . DIRECTORY_SEPARATOR . collect() ->concat($directories) ->map([Str::class, 'kebab']) ->push("{$name}.blade.php") ->implode(DIRECTORY_SEPARATOR); } protected function relativeLayoutPath($layoutPath) { return (string) str($layoutPath)->replaceFirst(base_path() . '/', ''); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/StubsCommand.php
src/Features/SupportConsoleCommands/Commands/StubsCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'livewire:stubs')] class StubsCommand extends Command { protected $signature = 'livewire:stubs'; protected $description = 'Publish Livewire stubs'; protected $parser; public function handle() { if (! is_dir($stubsPath = base_path('stubs'))) { (new Filesystem)->makeDirectory($stubsPath); } file_put_contents( $stubsPath.'/livewire.stub', file_get_contents(__DIR__.'/livewire.stub') ); file_put_contents( $stubsPath.'/livewire.inline.stub', file_get_contents(__DIR__.'/livewire.inline.stub') ); file_put_contents( $stubsPath.'/livewire.view.stub', file_get_contents(__DIR__.'/livewire.view.stub') ); file_put_contents( $stubsPath.'/livewire.test.stub', file_get_contents(__DIR__.'/livewire.test.stub') ); file_put_contents( $stubsPath.'/livewire.pest.stub', file_get_contents(__DIR__.'/livewire.pest.stub') ); file_put_contents( $stubsPath.'/livewire.form.stub', file_get_contents(__DIR__.'/livewire.form.stub') ); file_put_contents( $stubsPath.'/livewire.attribute.stub', file_get_contents(__DIR__.'/livewire.attribute.stub') ); $this->info('Stubs published successfully.'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/AttributeCommand.php
src/Features/SupportConsoleCommands/Commands/AttributeCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use Illuminate\Console\GeneratorCommand; use Illuminate\Support\Facades\File; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'livewire:attribute')] class AttributeCommand extends GeneratorCommand { /** * The console command name. * * @var string */ protected $signature = 'livewire:attribute {name} {--force}'; /** * The console command description. * * @var string */ protected $description = 'Create a new Livewire attribute class'; /** * The type of class being generated. * * @var string */ protected $type = 'Attribute'; /** * Get the stub file for the generator. * * @return string */ public function getStub() { if (File::exists(base_path('stubs/livewire.attribute.stub'))) { return base_path('stubs/livewire.attribute.stub'); } return __DIR__ . DIRECTORY_SEPARATOR . 'livewire.attribute.stub'; } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ public function getDefaultNamespace($rootNamespace) { return $rootNamespace . '\Livewire\Attributes'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/ConvertCommand.php
src/Features/SupportConsoleCommands/Commands/ConvertCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use function Laravel\Prompts\confirm; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Attribute\AsCommand; use Livewire\Finder\Finder; use Livewire\Compiler\Parser\SingleFileParser; use Livewire\Compiler\Parser\MultiFileParser; use Illuminate\Support\Str; use Illuminate\Filesystem\Filesystem; use Illuminate\Console\Command; #[AsCommand(name: 'livewire:convert')] class ConvertCommand extends Command { protected $name = 'livewire:convert'; protected $description = 'Convert a Livewire component between single-file and multi-file formats'; protected Filesystem $files; protected Finder $finder; public function __construct() { parent::__construct(); $this->files = app('files'); $this->finder = app('livewire.finder'); } public function handle() { $name = $this->argument('name'); if (! $name) { $this->components->error('Component name is required.'); return 1; } $name = $this->normalizeComponentName($name); // Detect what type the component currently is $sfcPath = $this->finder->resolveSingleFileComponentPath($name); $mfcPath = $this->finder->resolveMultiFileComponentPath($name); $isSfc = $sfcPath && $this->files->exists($sfcPath); $isMfc = $mfcPath && $this->files->exists($mfcPath) && $this->files->isDirectory($mfcPath); if (! $isSfc && ! $isMfc) { $this->components->error('Component not found.'); return 1; } if ($isSfc && $isMfc) { $this->components->error('Component exists in both single-file and multi-file formats. Please resolve this conflict first.'); return 1; } // Determine target format $targetFormat = $this->determineTargetFormat($isSfc); if ($targetFormat === 'mfc' && $isSfc) { return $this->convertSingleFileToMultiFile($name, $sfcPath); } if ($targetFormat === 'sfc' && $isMfc) { return $this->convertMultiFileToSingleFile($name, $mfcPath); } $this->components->error('Component is already in the target format.'); return 1; } protected function normalizeComponentName(string $name): string { return (string) str($name) ->replace('/', '.') ->replace('\\', '.') ->explode('.') ->map(fn ($i) => str($i)->kebab()) ->implode('.'); } protected function determineTargetFormat(bool $isSfc): string { if ($this->option('mfc')) { return 'mfc'; } if ($this->option('sfc')) { return 'sfc'; } // If no option specified, auto-detect and convert to opposite return $isSfc ? 'mfc' : 'sfc'; } public function convertSingleFileToMultiFile(string $name, string $sfcPath): int { // Use the SFC filename (without .blade.php) as the directory name // This ensures we preserve emoji/naming exactly as it exists $sfcFilename = basename($sfcPath); $directoryName = str_replace('.blade.php', '', $sfcFilename); $directory = dirname($sfcPath) . '/' . $directoryName; // Component name for files inside the directory (without emoji) $componentName = str_replace(['⚡', '⚡︎', '⚡️'], '', $directoryName); $classPath = $directory . '/' . $componentName . '.php'; $viewPath = $directory . '/' . $componentName . '.blade.php'; $testPath = $directory . '/' . $componentName . '.test.php'; $jsPath = $directory . '/' . $componentName . '.js'; $parser = SingleFileParser::parse(app('livewire.compiler'), $sfcPath); $this->ensureDirectoryExists($directory); $scriptContents = $parser->generateScriptContentsForMultiFile(); $classContents = $parser->generateClassContentsForMultiFile(); $viewContents = $parser->generateViewContentsForMultiFile(); $this->files->put($classPath, $classContents); $this->files->put($viewPath, $viewContents); // Check for existing test file next to SFC $sfcTestPath = str_replace('.blade.php', '.test.php', $sfcPath); $existingTestFile = $this->files->exists($sfcTestPath); if ($existingTestFile) { // Move existing test file into MFC directory $testContents = $this->files->get($sfcTestPath); $this->files->put($testPath, $testContents); $this->files->delete($sfcTestPath); } elseif ($this->option('test')) { // Create new test file if --test flag passed and no existing test $this->files->put($testPath, $this->buildMultiFileComponentTest($name)); } if ($scriptContents !== null) { $this->files->put($jsPath, $scriptContents); } $this->files->delete($sfcPath); $this->components->info(sprintf('Livewire component [%s] converted to multi-file successfully.', $directory)); return 0; } public function convertMultiFileToSingleFile(string $name, string $mfcPath): int { // Use the MFC directory name as the SFC filename (with .blade.php) // This ensures we preserve emoji/naming exactly as it exists $directoryName = basename($mfcPath); $sfcPath = dirname($mfcPath) . '/' . $directoryName . '.blade.php'; // Component name for files inside the directory (without emoji) $componentName = str_replace(['⚡', '⚡︎', '⚡️'], '', $directoryName); $classPath = $mfcPath . '/' . $componentName . '.php'; $viewPath = $mfcPath . '/' . $componentName . '.blade.php'; $testPath = $mfcPath . '/' . $componentName . '.test.php'; $jsPath = $mfcPath . '/' . $componentName . '.js'; if (! $this->files->exists($classPath)) { $this->components->error('Multi-file component class file not found.'); return 1; } if (! $this->files->exists($viewPath)) { $this->components->error('Multi-file component view file not found.'); return 1; } $testFileExists = $this->files->exists($testPath); $parser = MultiFileParser::parse(app('livewire.compiler'), $mfcPath); // Generate the single-file component contents $sfcContents = $parser->generateContentsForSingleFile(); $this->ensureDirectoryExists(dirname($sfcPath)); $this->files->put($sfcPath, $sfcContents); // Move test file out before deleting directory if ($testFileExists) { $testContents = $this->files->get($testPath); $sfcTestPath = str_replace('.blade.php', '.test.php', $sfcPath); $this->files->put($sfcTestPath, $testContents); } // Delete the multi-file directory $this->files->deleteDirectory($mfcPath); $this->components->info(sprintf('Livewire component [%s] converted to single-file successfully.', $sfcPath)); return 0; } protected function buildMultiFileComponentTest(string $name): string { $stub = $this->files->get($this->getStubPath('livewire-mfc-test.stub')); $componentName = collect(explode('.', $name)) ->map(fn ($segment) => Str::kebab($segment)) ->implode('.'); $stub = str_replace('[component-name]', $componentName, $stub); return $stub; } protected function getStubPath(string $stub): string { $customPath = $this->laravel->basePath('stubs/' . $stub); if ($this->files->exists($customPath)) { return $customPath; } // Look for the stub in the MakeCommand directory return dirname(__FILE__) . '/' . $stub; } protected function ensureDirectoryExists(string $path): void { if (! $this->files->isDirectory($path)) { $this->files->makeDirectory($path, 0755, true, true); } } protected function shouldUseEmoji(): bool { if ($this->option('emoji') !== null) { return filter_var($this->option('emoji'), FILTER_VALIDATE_BOOLEAN); } return config('livewire.make_command.emoji', true); } protected function getArguments() { return [ ['name', InputArgument::REQUIRED, 'The name of the component'], ]; } protected function getOptions() { return [ ['sfc', null, InputOption::VALUE_NONE, 'Convert to single-file component'], ['mfc', null, InputOption::VALUE_NONE, 'Convert to multi-file component'], ['test', null, InputOption::VALUE_NONE, 'Create a test file when converting to multi-file (if one does not exist)'], ['emoji', null, InputOption::VALUE_REQUIRED, 'Use emoji in file/directory names (true or false)'], ]; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/S3CleanupCommand.php
src/Features/SupportConsoleCommands/Commands/S3CleanupCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use Aws\S3\S3Client; use function array_merge; use function Livewire\invade; use Livewire\Features\SupportFileUploads\FileUploadConfiguration; use Illuminate\Console\Command; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'livewire:configure-s3-upload-cleanup')] class S3CleanupCommand extends Command { protected $signature = 'livewire:configure-s3-upload-cleanup'; protected $description = 'Configure temporary file upload s3 directory to automatically cleanup files older than 24hrs'; public function handle() { if (! FileUploadConfiguration::isUsingS3()) { $this->error("Configuration ['livewire.temporary_file_upload.disk'] is not set to a disk with an S3 driver."); return; } $driver = FileUploadConfiguration::storage()->getDriver(); // Flysystem V2+ doesn't allow direct access to adapter, so we need to invade instead. $adapter = invade($driver)->adapter; // Flysystem V2+ doesn't allow direct access to client, so we need to invade instead. $client = invade($adapter)->client; // Flysystem V2+ doesn't allow direct access to bucket, so we need to invade instead. $bucket = invade($adapter)->bucket; $prefix = FileUploadConfiguration::path(); $rules[] = [ 'Filter' => [ 'Prefix' => $prefix, ], 'Expiration' => [ 'Days' => 1, ], 'Status' => 'Enabled', ]; $rules = $this->mergeRulesWithExistingConfiguration($client, $bucket, $prefix, $rules); try { $client->putBucketLifecycleConfiguration([ 'Bucket' => $bucket, 'LifecycleConfiguration' => [ 'Rules' => $rules ], ]); } catch (\Exception $e) { $this->error('Failed to configure S3 bucket ['.$bucket.'] to automatically cleanup files older than 24hrs!'); $this->error($e->getMessage()); return; } $this->info('Livewire temporary S3 upload directory ['.$prefix.'] set to automatically cleanup files older than 24hrs!'); } private function checkIfLivewireConfigurationIsAlreadySet(array $existingConfigurationRules, string $bucket, S3Client $client, string $prefix) { $existingConfigurationHasLivewire = collect($existingConfigurationRules)->contains('Filter.Prefix', $prefix); if($existingConfigurationHasLivewire) { $this->info('Livewire temporary S3 upload directory ['.$prefix.'] already set to automatically cleanup files older than 24hrs!'); $this->info('No changes made to S3 bucket ['.$bucket.'] configuration.'); exit; } } private function mergeRulesWithExistingConfiguration(S3Client $client, string $bucket, string $prefix, array $rules): array { try { $existingConfiguration = $client->getBucketLifecycleConfiguration([ 'Bucket' => $bucket, ]); } catch (\Exception $e) { // if no configuration exists, we'll just ignore the error and continue. $existingConfiguration = null; } if ($existingConfiguration) { $this->checkIfLivewireConfigurationIsAlreadySet($existingConfiguration['Rules'], $bucket, $client, $prefix); $existingConfiguration = $existingConfiguration['Rules']; $rules = array_merge($existingConfiguration, $rules); } return $rules; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/the-tao.php
src/Features/SupportConsoleCommands/Commands/the-tao.php
<?php return [ 'Because she competes with no one, no one can compete with her.', 'The best athlete wants his opponent at his best.', 'Nothing in the world is as soft and yielding as water.', 'Be like water.', 'In work, do what you enjoy.', 'Care about people\'s approval and you will be their prisoner.', 'Do your work, then step back.', 'Success is as dangerous as failure.', 'The Master doesn\'t talk, he acts.', 'A good traveler has no fixed plans and is not intent upon arriving.', 'Knowing others is intelligence; knowing yourself is true wisdom.', 'If your happiness depends on money, you will never be happy with yourself.', 'If you look to others for fulfillment, you will never truly be fulfilled.', 'To attain knowledge, add things every day; To attain wisdom, subtract things every day.', 'Close your eyes. Count to one. That is how long forever feels.', 'The whole world belongs to you.', 'Stop trying to control.', ];
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/FormCommand.php
src/Features/SupportConsoleCommands/Commands/FormCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use Illuminate\Console\GeneratorCommand; use Illuminate\Support\Facades\File; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'livewire:form')] class FormCommand extends GeneratorCommand { /** * The console command name. * * @var string */ protected $signature = 'livewire:form {name} {--force}'; /** * The console command description. * * @var string */ protected $description = 'Create a new Livewire form class'; /** * The type of class being generated. * * @var string */ protected $type = 'Form'; /** * Get the stub file for the generator. * * @return string */ public function getStub() { if (File::exists(base_path('stubs/livewire.form.stub'))) { return base_path('stubs/livewire.form.stub'); } return __DIR__ . DIRECTORY_SEPARATOR . 'livewire.form.stub'; } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ public function getDefaultNamespace($rootNamespace) { return $rootNamespace . '\Livewire\Forms'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/LivewireMakeCommand.php
src/Features/SupportConsoleCommands/Commands/LivewireMakeCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'livewire:make')] class LivewireMakeCommand extends MakeCommand { protected $name = 'livewire:make'; protected $hidden = true; // Hide from command list to avoid duplication }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/FileManipulationCommand.php
src/Features/SupportConsoleCommands/Commands/FileManipulationCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\File; use function Livewire\str; class FileManipulationCommand extends Command { protected $parser; protected function ensureDirectoryExists($path) { if (! File::isDirectory(dirname($path))) { File::makeDirectory(dirname($path), 0777, $recursive = true, $force = true); } } public function isFirstTimeMakingAComponent() { $namespace = str(config('livewire.class_namespace'))->replaceFirst(app()->getNamespace(), ''); $livewireFolder = app_path($namespace->explode('\\')->implode(DIRECTORY_SEPARATOR)); return ! File::isDirectory($livewireFolder); } public function writeWelcomeMessage() { $asciiLogo = <<<EOT <fg=magenta> _._</> <fg=magenta>/ /<fg=white>o</>\ \ </> <fg=cyan> || () () __ </> <fg=magenta>|_\ /_|</> <fg=cyan> || || \\\// /_\ \\\ // || |~~ /_\ </> <fg=magenta> <fg=cyan>|</>`<fg=cyan>|</>`<fg=cyan>|</> </> <fg=cyan> || || \/ \\\_ \^/ || || \\\_ </> EOT; // _._ // / /o\ \ || () () __ // |_\ /_| || || \\\// /_\ \\\ // || |~~ /_\ // |`|`| || || \/ \\\_ \^/ || || \\\_ $this->line("\n".$asciiLogo."\n"); $this->line("\n<options=bold>Congratulations, you've created your first Livewire component!</> 🎉🎉🎉\n"); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportConsoleCommands/Commands/PublishCommand.php
src/Features/SupportConsoleCommands/Commands/PublishCommand.php
<?php namespace Livewire\Features\SupportConsoleCommands\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Attribute\AsCommand; #[AsCommand(name: 'livewire:publish')] class PublishCommand extends Command { protected $signature = 'livewire:publish { --assets : Indicates if Livewire\'s front-end assets should be published } { --config : Indicates if Livewire\'s config file should be published } { --pagination : Indicates if Livewire\'s pagination views should be published }'; protected $description = 'Publish Livewire configuration'; public function handle() { if ($this->option('assets')) { $this->publishAssets(); } elseif ($this->option('config')) { $this->publishConfig(); } elseif ($this->option('pagination')) { $this->publishPagination(); } else { $this->publishConfig(); $this->publishPagination(); } } public function publishAssets() { $this->call('vendor:publish', ['--tag' => 'livewire:assets', '--force' => true]); } public function publishConfig() { $this->call('vendor:publish', ['--tag' => 'livewire:config', '--force' => true]); } public function publishPagination() { $this->call('vendor:publish', ['--tag' => 'livewire:pagination', '--force' => true]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLocales/SupportLocales.php
src/Features/SupportLocales/SupportLocales.php
<?php namespace Livewire\Features\SupportLocales; use Livewire\ComponentHook; class SupportLocales extends ComponentHook { function hydrate($memo) { if ($locale = $memo['locale']) app()->setLocale($locale); } function dehydrate($context) { $context->addMemo('locale', app()->getLocale()); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLocales/UnitTest.php
src/Features/SupportLocales/UnitTest.php
<?php namespace Livewire\Features\SupportLocales; use Illuminate\Support\Facades\App; use Livewire\Livewire; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_a_livewire_component_can_persist_its_locale() { // Set locale App::setLocale('en'); $this->assertEquals(App::getLocale(), 'en'); // Mount component and new ensure locale is set $component = Livewire::test(ComponentForLocalePersistanceHydrationMiddleware::class); $this->assertEquals(App::getLocale(), 'es'); // Reset locale to ensure it isn't persisted in the test session App::setLocale('en'); $this->assertEquals(App::getLocale(), 'en'); // Verify locale is persisted from component mount $component->call('$refresh'); $this->assertEquals(App::getLocale(), 'es'); } } class ComponentForLocalePersistanceHydrationMiddleware extends TestComponent { public function mount() { App::setLocale('es'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAsync/BaseAsync.php
src/Features/SupportAsync/BaseAsync.php
<?php namespace Livewire\Features\SupportAsync; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; #[\Attribute] class BaseAsync extends LivewireAttribute { public function dehydrate($context) { $methodName = $this->getName(); $context->pushMemo('async', $methodName); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLazyLoading/BaseDefer.php
src/Features/SupportLazyLoading/BaseDefer.php
<?php namespace Livewire\Features\SupportLazyLoading; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; #[\Attribute(\Attribute::TARGET_CLASS)] class BaseDefer extends LivewireAttribute { public function __construct( public $isolate = null, public $bundle = null, ) {} }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLazyLoading/BrowserTest.php
src/Features/SupportLazyLoading/BrowserTest.php
<?php namespace Livewire\Features\SupportLazyLoading; use Illuminate\Support\Facades\Route; use Tests\BrowserTestCase; use Livewire\Livewire; use Livewire\Component; use Livewire\Attributes\Reactive; class BrowserTest extends BrowserTestCase { public function test_can_lazy_load_a_component() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <livewire:child lazy /> </div> HTML; } }, 'child' => new class extends Component { public function mount() { sleep(1); } public function render() { return <<<HTML <div id="child"> Child! </div> HTML; } }]) ->assertDontSee('Child!') ->waitFor('#child') ->assertSee('Child!') ; } public function test_can_defer_lazy_load_a_component() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <div style="height: 200vh"></div> <livewire:child defer /> </div> HTML; } }, 'child' => new class extends Component { public function mount() { sleep(1); } public function render() { return <<<HTML <div id="child"> Child! </div> HTML; } }]) ->assertDontSee('Child!') ->waitFor('#child') ->assertSee('Child!'); } public function test_cant_lazy_load_a_component_on_intersect_outside_viewport() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <div style="height: 200vh"></div> <livewire:child lazy /> </div> HTML; } }, 'child' => new class extends Component { public function mount() { sleep(1); } public function render() { return <<<HTML <div id="child"> Child! </div> HTML; } }]) ->assertDontSee('Child!') ->pause(2000) ->assertDontSee('Child!'); } public function can_lazy_load_full_page_component_using_attribute() { Livewire::visit(new #[\Livewire\Attributes\Lazy] class extends Component { public function mount() { sleep(1); } public function placeholder() { return <<<HTML <div id="loading"> Loading... </div> HTML; } public function render() { return <<<HTML <div id="page"> Hello World </div> HTML; } }) ->assertSee('Loading...') ->assertDontSee('Hello World') ->waitFor('#page') ->assertDontSee('Loading...') ->assertSee('Hello World') ; } public function can_defer_lazy_load_full_page_component_using_attribute() { Livewire::visit(new #[\Livewire\Attributes\Defer] class extends Component { public function mount() { sleep(1); } public function placeholder() { return <<<HTML <div id="loading"> Loading... </div> HTML; } public function render() { return <<<HTML <div id="page"> Hello World </div> HTML; } }) ->assertSee('Loading...') ->assertDontSee('Hello World') ->waitFor('#page') ->assertDontSee('Loading...') ->assertSee('Hello World') ; } public function test_can_lazy_load_component_using_route() { $this->beforeServingApplication(function() { Livewire::component('page', Page::class); Route::get('/', Page::class)->lazy()->middleware('web'); }); $this->browse(function ($browser) { $browser ->visit('/') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('Loading...') ->assertDontSee('Hello World') ->waitFor('#page') ->assertDontSee('Loading...') ->assertSee('Hello World'); }); } public function test_can_defer_lazy_load_component_using_route() { $this->beforeServingApplication(function() { Livewire::component('page', Page::class); Route::get('/', Page::class)->defer()->middleware('web'); }); $this->browse(function ($browser) { $browser ->visit('/') ->tap(fn ($b) => $b->script('window._lw_dusk_test = true')) ->assertScript('return window._lw_dusk_test') ->assertSee('Loading...') ->assertDontSee('Hello World') ->waitFor('#page') ->assertDontSee('Loading...') ->assertSee('Hello World'); }); } public function test_can_lazy_load_a_component_with_a_placeholder() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <livewire:child lazy /> </div> HTML; } }, 'child' => new class extends Component { public function mount() { sleep(1); } public function placeholder() { return <<<HTML <div id="loading"> Loading... </div> HTML; } public function render() { return <<<HTML <div id="child"> Child! </div> HTML; } }]) ->assertSee('Loading...') ->assertDontSee('Child!') ->waitFor('#child') ->assertDontSee('Loading...') ->assertSee('Child!') ; } public function test_can_pass_props_to_lazyilly_loaded_component() { Livewire::visit([new class extends Component { public $count = 1; public function render() { return <<<'HTML' <div> <livewire:child :$count lazy /> </div> HTML; } }, 'child' => new class extends Component { public $count; public function mount() { sleep(1); } public function render() { return <<<'HTML' <div id="child"> Count: {{ $count }} </div> HTML; } }]) ->waitFor('#child') ->assertSee('Count: 1') ; } public function test_can_pass_props_to_mount_method_to_lazyilly_loaded_component() { Livewire::visit([new class extends Component { public $count = 1; public function render() { return <<<'HTML' <div> <livewire:child :$count lazy /> </div> HTML; } }, 'child' => new class extends Component { public $count; public function mount($count) { $this->count = $this->count + 2; } public function render() { return <<<'HTML' <div id="child"> Count: {{ $count }} </div> HTML; } }]) ->waitFor('#child') ->assertSee('Count: 3') ; } public function test_can_pass_reactive_props_to_lazyilly_loaded_component() { Livewire::visit([new class extends Component { public $count = 1; public function inc() { $this->count++; } public function render() { return <<<'HTML' <div> <livewire:child :$count lazy /> <button wire:click="inc" dusk="button">+</button> </div> HTML; } }, 'child' => new class extends Component { #[Reactive] public $count; public function mount() { sleep(1); } public function render() { return <<<'HTML' <div id="child"> Count: {{ $count }} </div> HTML; } }]) ->waitFor('#child') ->waitForText('Count: 1') ->assertSee('Count: 1') ->waitForLivewire()->click('@button') ->waitForText('Count: 2') ->assertSee('Count: 2') ->waitForLivewire()->click('@button') ->waitForText('Count: 3') ->assertSee('Count: 3') ; } public function test_can_access_component_parameters_in_placeholder_view() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <livewire:child my-parameter="A Parameter Value" lazy /> </div> HTML; } }, 'child' => new class extends Component { public function mount($myParameter) { sleep(1); } public function placeholder(array $params = []) { return view('placeholder', $params); } public function render() { return <<<HTML <div id="child"> Child! </div> HTML; } }]) ->waitFor('#loading') ->assertSee('A Parameter Value') ->assertDontSee('Child!') ->waitFor('#child') ->assertSee('Child!') ; } public function test_lazy_components_are_not_bundled_by_default() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <livewire:child1 lazy /> <livewire:child2 lazy /> <livewire:child3 lazy /> </div> @script <script> window.requestCount = 0 Livewire.interceptRequest(({ onSend }) => { onSend(() => window.requestCount++) }) </script> @endscript HTML; } }, 'child1' => new class extends Component { public function render() { return '<div>Child 1</div>'; } }, 'child2' => new class extends Component { public function render() { return '<div>Child 2</div>'; } }, 'child3' => new class extends Component { public function render() { return '<div>Child 3</div>'; } } ]) ->waitForLivewireToLoad() ->waitForText('Child 1') ->waitForText('Child 2') ->waitForText('Child 3') // Lazy components should be isolated by default, making separate requests ->assertScript('window.requestCount', 3) ; } public function test_lazy_bundle_bundles_multiple_lazy_components_into_single_request() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <livewire:child1 lazy.bundle /> <livewire:child2 lazy.bundle /> <livewire:child3 lazy.bundle /> </div> @script <script> window.requestCount = 0 Livewire.interceptRequest(({ onSend }) => { onSend(() => window.requestCount++) }) </script> @endscript HTML; } }, 'child1' => new class extends Component { public function render() { return '<div>Child 1</div>'; } }, 'child2' => new class extends Component { public function render() { return '<div>Child 2</div>'; } }, 'child3' => new class extends Component { public function render() { return '<div>Child 3</div>'; } } ]) ->waitForLivewireToLoad() ->waitForText('Child 1') ->waitForText('Child 2') ->waitForText('Child 3') // All three lazy components should be bundled into a single request ->assertScript('window.requestCount', 1) ; } public function test_defer_components_are_not_bundled_by_default() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <livewire:child1 defer /> <livewire:child2 defer /> <livewire:child3 defer /> </div> @script <script> window.requestCount = 0 Livewire.interceptRequest(({ onSend }) => { onSend(() => window.requestCount++) }) </script> @endscript HTML; } }, 'child1' => new class extends Component { public function render() { return '<div>Child 1</div>'; } }, 'child2' => new class extends Component { public function render() { return '<div>Child 2</div>'; } }, 'child3' => new class extends Component { public function render() { return '<div>Child 3</div>'; } } ]) ->waitForLivewireToLoad() ->waitForText('Child 1') ->waitForText('Child 2') ->waitForText('Child 3') // Defer components should be isolated by default, making separate requests ->assertScript('window.requestCount', 3) ; } public function test_defer_bundle_bundles_multiple_defer_components_into_single_request() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <livewire:child1 defer.bundle /> <livewire:child2 defer.bundle /> <livewire:child3 defer.bundle /> </div> @script <script> window.requestCount = 0 Livewire.interceptRequest(({ onSend }) => { onSend(() => window.requestCount++) }) </script> @endscript HTML; } }, 'child1' => new class extends Component { public function render() { return '<div>Child 1</div>'; } }, 'child2' => new class extends Component { public function render() { return '<div>Child 2</div>'; } }, 'child3' => new class extends Component { public function render() { return '<div>Child 3</div>'; } } ]) ->waitForLivewireToLoad() ->waitForText('Child 1') ->waitForText('Child 2') ->waitForText('Child 3') // All three defer components should be bundled into a single request ->assertScript('window.requestCount', 1) ; } } class Page extends Component { public function mount() { sleep(1); } public function placeholder() { return <<<HTML <div id="loading"> Loading... </div> HTML; } public function render() { return <<<HTML <div id="page"> Hello World </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLazyLoading/SupportLazyLoading.php
src/Features/SupportLazyLoading/SupportLazyLoading.php
<?php namespace Livewire\Features\SupportLazyLoading; use Livewire\Features\SupportLifecycleHooks\SupportLifecycleHooks; use Livewire\Mechanisms\HandleComponents\ComponentContext; use Livewire\Mechanisms\HandleComponents\ViewContext; use function Livewire\{ on, store, trigger, wrap }; use Illuminate\Routing\Route; use Livewire\ComponentHook; use Livewire\Drawer\Utils; use Livewire\Component; class SupportLazyLoading extends ComponentHook { static $disableWhileTesting = false; static function disableWhileTesting() { static::$disableWhileTesting = true; } static function provide() { static::registerRouteMacro(); on('flush-state', function () { static::$disableWhileTesting = false; }); } static function registerRouteMacro() { Route::macro('lazy', function ($enabled = true) { $this->defaults['lazy'] = $enabled; return $this; }); Route::macro('defer', function ($enabled = true) { $this->defaults['defer'] = $enabled; return $this; }); } public function mount($params) { $shouldBeLazy = false; $isDeferred = false; $isolate = true; if (isset($params['lazy']) && $params['lazy']) $shouldBeLazy = true; if (isset($params['lazy.bundle']) && $params['lazy.bundle']) $shouldBeLazy = true; if (isset($params['defer']) && $params['defer']) $shouldBeLazy = true; if (isset($params['defer.bundle']) && $params['defer.bundle']) $shouldBeLazy = true; if (isset($params['lazy']) && $params['lazy'] === 'on-load') $isDeferred = true; if (isset($params['lazy.bundle']) && $params['lazy.bundle'] === 'on-load') $isDeferred = true; if (isset($params['defer']) && $params['defer']) $isDeferred = true; if (isset($params['defer.bundle']) && $params['defer.bundle']) $isDeferred = true; if (isset($params['lazy.bundle']) && $params['lazy.bundle']) $isolate = false; if (isset($params['defer.bundle']) && $params['defer.bundle']) $isolate = false; $reflectionClass = new \ReflectionClass($this->component); $lazyAttribute = $reflectionClass->getAttributes(\Livewire\Attributes\Lazy::class)[0] ?? null; $deferAttribute = $reflectionClass->getAttributes(\Livewire\Attributes\Defer::class)[0] ?? null; if ($lazyAttribute) $shouldBeLazy = true; if ($deferAttribute) $shouldBeLazy = true; if ($deferAttribute) $isDeferred = true; // If Livewire::withoutLazyLoading()... if (static::$disableWhileTesting) return; // If `:lazy="false"` or no lazy loading is included at all... if (! $shouldBeLazy) return; if ($lazyAttribute) { $attribute = $lazyAttribute->newInstance(); if ($attribute->bundle !== null) $isolate = ! $attribute->bundle; if ($attribute->isolate !== null) $isolate = $attribute->isolate; } if ($deferAttribute) { $attribute = $deferAttribute->newInstance(); if ($attribute->bundle !== null) $isolate = ! $attribute->bundle; if ($attribute->isolate !== null) $isolate = $attribute->isolate; } $this->component->skipMount(); store($this->component)->set('isLazyLoadMounting', true); store($this->component)->set('isLazyIsolated', $isolate); $this->component->skipRender( $this->generatePlaceholderHtml($params, $isDeferred) ); } public function hydrate($memo) { if (! isset($memo['lazyLoaded'])) return; if ($memo['lazyLoaded'] === true) return; $this->component->skipHydrate(); store($this->component)->set('isLazyLoadHydrating', true); } function dehydrate($context) { if (store($this->component)->get('isLazyLoadMounting') === true) { $context->addMemo('lazyLoaded', false); $context->addMemo('lazyIsolated', store($this->component)->get('isLazyIsolated')); } elseif (store($this->component)->get('isLazyLoadHydrating') === true) { $context->addMemo('lazyLoaded', true); } } function call($method, $params, $returnEarly) { if ($method !== '__lazyLoad') return; [ $encoded ] = $params; $mountParams = $this->resurrectMountParams($encoded); $this->callMountLifecycleMethod($mountParams); $returnEarly(); } public function generatePlaceholderHtml($params, $isDeferred = false) { $this->registerContainerComponent(); $container = app('livewire')->new('__mountParamsContainer'); $container->forMount = array_diff_key($params, array_flip(['lazy', 'defer'])); $context = new ComponentContext($container, mounting: true); trigger('dehydrate', $container, $context); $snapshot = app('livewire')->snapshot($container, $context); $encoded = base64_encode(json_encode($snapshot)); $placeholder = $this->getPlaceholderView($this->component, $params); $finish = trigger('render.placeholder', $this->component, $placeholder, $params); $viewContext = new ViewContext; $html = $placeholder->render(function ($view) use ($viewContext) { // Extract leftover slots, sections, and pushes before they get flushed... $viewContext->extractFromEnvironment($view->getFactory()); }); $html = Utils::insertAttributesIntoHtmlRoot($html, [ ($isDeferred ? 'x-init' : 'x-intersect') => '$wire.__lazyLoad(\''.$encoded.'\')', ]); $replaceHtml = function ($newHtml) use (&$html) { $html = $newHtml; }; $html = $finish($html, $replaceHtml, $viewContext); return $html; } protected function getPlaceholderView($component, $params) { // @todo: This is a hack. Fix this so it uses a deterministically generated name... $name = (string) str($this->component->getName())->afterLast('.'); $compiledPlaceholder = "livewire-compiled::{$name}_placeholder"; $globalPlaceholder = config('livewire.component_placeholder'); if (view()->exists($compiledPlaceholder)) { $placeholderHtml = $compiledPlaceholder; } else if ($globalPlaceholder) { $placeholderHtml = view($globalPlaceholder)->render(); } else { $placeholderHtml = '<div></div>'; } $viewOrString = wrap($component)->withFallback($placeholderHtml)->placeholder($params); $properties = Utils::getPublicPropertiesDefinedOnSubclass($component); $view = Utils::generateBladeView($viewOrString, $properties); return $view; } function resurrectMountParams($encoded) { $snapshot = json_decode(base64_decode($encoded), associative: true); $this->registerContainerComponent(); [ $container ] = app('livewire')->fromSnapshot($snapshot); return $container->forMount; } function callMountLifecycleMethod($params) { $hook = new SupportLifecycleHooks; $hook->setComponent($this->component); $hook->mount($params); } public function registerContainerComponent() { app('livewire')->component('__mountParamsContainer', new class extends Component { public $forMount; }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLazyLoading/UnitTest.php
src/Features/SupportLazyLoading/UnitTest.php
<?php namespace Livewire\Features\SupportLazyLoading; use Illuminate\Support\Facades\Route; use Livewire\Attributes\Layout; use Livewire\Attributes\Lazy; use Livewire\Component; use Livewire\Livewire; class UnitTest extends \Tests\TestCase { public function test_can_lazy_load_component_with_custom_layout() { Livewire::component('page', PageWithCustomLayout::class); Route::get('/one', PageWithCustomLayout::class)->middleware('web'); Livewire::component('page', PageWithCustomLayoutOnView::class); Route::get('/two', PageWithCustomLayoutOnView::class)->middleware('web'); Livewire::component('page', PageWithCustomLayoutAttributeOnMethod::class); Route::get('/three', PageWithCustomLayoutAttributeOnMethod::class)->middleware('web'); $this->get('/one')->assertSee('This is a custom layout'); $this->get('/two')->assertSee('This is a custom layout'); $this->get('/three')->assertSee('This is a custom layout'); } public function test_can_disable_lazy_loading_during_unit_tests() { Livewire::component('lazy-component', BasicLazyComponent::class); Livewire::withoutLazyLoading()->test(new class extends Component { public function render() { return <<<'HTML' <div> <livewire:lazy-component /> </div> HTML; } }) ->assertDontSee('Loading...') ->assertSee('Hello world!'); } } #[Lazy] class BasicLazyComponent extends Component { public function placeholder() { return '<div>Loading...</div>'; } public function render() { return '<div>Hello world!</div>'; } } #[Layout('components.layouts.custom'), Lazy] class PageWithCustomLayout extends Component { public function placeholder() { return '<div>Loading...</div>'; } } #[Lazy] class PageWithCustomLayoutAttributeOnMethod extends Component { #[Layout('components.layouts.custom')] public function placeholder() { return '<div>Loading...</div>'; } } #[Lazy] class PageWithCustomLayoutOnView extends Component { public function placeholder() { return view('show-name', ['name' => 'foo'])->layout('components.layouts.custom'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLazyLoading/BaseLazy.php
src/Features/SupportLazyLoading/BaseLazy.php
<?php namespace Livewire\Features\SupportLazyLoading; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; #[\Attribute(\Attribute::TARGET_CLASS)] class BaseLazy extends LivewireAttribute { public function __construct( public $isolate = null, public $bundle = null, ) {} }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportScriptsAndAssets/SupportScriptsAndAssets.php
src/Features/SupportScriptsAndAssets/SupportScriptsAndAssets.php
<?php namespace Livewire\Features\SupportScriptsAndAssets; use Illuminate\Support\Facades\Blade; use function Livewire\store; use Livewire\ComponentHook; use function Livewire\on; class SupportScriptsAndAssets extends ComponentHook { public static $alreadyRunAssetKeys = []; public static $countersByViewPath = []; public static $renderedAssets = []; public static $nonLivewireAssets = []; public static function getAssets() { return static::$renderedAssets; } public static function processNonLivewireAssets() { // If any assets have been added outside of a Livewire component, then they will not be // processed like the other assets as there is no dehydrate being called. So instead // we process them manually that way they are included with the other assets when // they are injected... $alreadyRunAssetKeys = []; foreach (static::$nonLivewireAssets as $key => $assets) { if (! in_array($key, $alreadyRunAssetKeys)) { // These will get injected into the HTML if it's an initial page load... static::$renderedAssets[$key] = $assets; $alreadyRunAssetKeys[] = $key; } } } public static function getUniqueBladeCompileTimeKey() { // Rather than using random strings as compile-time keys for blade directives, // we want something more detereminstic to protect against problems that arise // from using load-balancers and such. // Therefore, we create a key based on the currently compiling view path and // number of already compiled directives here... $viewPath = crc32(app('blade.compiler')->getPath() ?? ''); if (! isset(static::$countersByViewPath[$viewPath])) static::$countersByViewPath[$viewPath] = 0; $key = $viewPath.'-'.static::$countersByViewPath[$viewPath]; static::$countersByViewPath[$viewPath]++; return $key; } static function provide() { on('flush-state', function () { static::$alreadyRunAssetKeys = []; static::$countersByViewPath = []; static::$renderedAssets = []; static::$nonLivewireAssets = []; }); Blade::directive('script', function () { $key = static::getUniqueBladeCompileTimeKey(); return <<<PHP <?php \$__scriptKey = '$key'; ob_start(); ?> PHP; }); Blade::directive('endscript', function () { return <<<PHP <?php \$__output = ob_get_clean(); \Livewire\store(\$this)->push('scripts', \$__output, \$__scriptKey) ?> PHP; }); Blade::directive('assets', function () { $key = static::getUniqueBladeCompileTimeKey(); return <<<PHP <?php \$__assetKey = '$key'; ob_start(); ?> PHP; }); Blade::directive('endassets', function () { return <<<PHP <?php \$__output = ob_get_clean(); // If the asset has already been loaded anywhere during this request, skip it... if (in_array(\$__assetKey, \Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets::\$alreadyRunAssetKeys)) { // Skip it... } else { \Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets::\$alreadyRunAssetKeys[] = \$__assetKey; // Check if we're in a Livewire component or not and store the asset accordingly... if (isset(\$this)) { \Livewire\store(\$this)->push('assets', \$__output, \$__assetKey); } else { \Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets::\$nonLivewireAssets[\$__assetKey] = \$__output; } } ?> PHP; }); } function hydrate($memo) { // Store the "scripts" and "assets" memos so they can be re-added later (persisted between requests)... if (isset($memo['scripts'])) { store($this->component)->set('forwardScriptsToDehydrateMemo', $memo['scripts']); } if (isset($memo['assets'])) { store($this->component)->set('forwardAssetsToDehydrateMemo', $memo['assets']); } } function dehydrate($context) { $alreadyRunScriptKeys = store($this->component)->get('forwardScriptsToDehydrateMemo', []); // Add any scripts to the payload that haven't been run yet for this component.... foreach (store($this->component)->get('scripts', []) as $key => $script) { if (! in_array($key, $alreadyRunScriptKeys)) { $context->pushEffect('scripts', $script, $key); $alreadyRunScriptKeys[] = $key; } } $context->addMemo('scripts', $alreadyRunScriptKeys); // Add any assets to the payload that haven't been run yet for the entire page... $alreadyRunAssetKeys = store($this->component)->get('forwardAssetsToDehydrateMemo', []); foreach (store($this->component)->get('assets', []) as $key => $assets) { if (! in_array($key, $alreadyRunAssetKeys)) { // These will either get injected into the HTML if it's an initial page load // or they will be added to the "assets" key in an ajax payload... static::$renderedAssets[$key] = $assets; $alreadyRunAssetKeys[] = $key; } } $context->addMemo('assets', $alreadyRunAssetKeys); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportScriptsAndAssets/BrowserTest.php
src/Features/SupportScriptsAndAssets/BrowserTest.php
<?php namespace Livewire\Features\SupportScriptsAndAssets; use Illuminate\Support\Facades\Blade; use Livewire\Livewire; use Livewire\Drawer\Utils; use Illuminate\Support\Facades\Route; class BrowserTest extends \Tests\BrowserTestCase { public static function tweakApplicationHook() { return function () { Route::get('/non-livewire-asset.js', function () { return Utils::pretendResponseIsFile(__DIR__.'/non-livewire-asset.js'); }); Route::get('/non-livewire-assets', function () { return Blade::render(<<< BLADE <html> <head> </head> <body> <div> <h1 dusk="foo"></h1> </div> @assets <script src="/non-livewire-asset.js" defer></script> @endassets </body> </html> BLADE); }); }; } public function test_can_evaluate_a_script_inside_a_component() { Livewire::visit(new class extends \Livewire\Component { public $message = 'original'; public function render() { return <<<'HTML' <div> <h1 dusk="foo"></h1> <h2 dusk="bar" x-text="$wire.message"></h2> </div> @script <script> document.querySelector('[dusk="foo"]').textContent = 'evaluated' $wire.message = 'changed' </script> @endscript HTML; } }) ->waitForText('evaluated') ->assertSeeIn('@foo', 'evaluated') ->assertSeeIn('@bar', 'changed') ; } public function test_can_register_an_alpine_component_inside_a_script_tag() { Livewire::visit(new class extends \Livewire\Component { public $message = 'original'; public function render() { return <<<'HTML' <div> <h1 dusk="foo" x-dusk-test x-init="console.log('init')"></h1> </div> @script <script> console.log('hi') Alpine.directive('dusk-test', (el) => { el.textContent = 'evaluated' }) </script> @endscript HTML; } }) ->waitForText('evaluated') ->assertSeeIn('@foo', 'evaluated') ; } public function test_multiple_scripts_can_be_evaluated() { Livewire::visit(new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <h1 dusk="foo"></h1> <h2 dusk="bar"></h2> </div> @script <script> document.querySelector('[dusk="foo"]').textContent = 'evaluated-first' </script> @endscript @script <script> document.querySelector('[dusk="bar"]').textContent = 'evaluated-second' </script> @endscript HTML; } }) ->waitForText('evaluated-first') ->assertSeeIn('@foo', 'evaluated-first') ->assertSeeIn('@bar', 'evaluated-second') ; } public function test_scripts_can_be_added_conditionally() { Livewire::visit(new class extends \Livewire\Component { public $show = false; public function render() { return <<<'HTML' <div> <button dusk="button" wire:click="$set('show', true)">refresh</button> <h1 dusk="foo" wire:ignore></h1> </div> @if($show) @script <script> document.querySelector('[dusk="foo"]').textContent = 'evaluated-second' </script> @endscript @endif @script <script> document.querySelector('[dusk="foo"]').textContent = 'evaluated-first' </script> @endscript HTML; } }) ->assertSeeIn('@foo', 'evaluated-first') ->waitForLivewire()->click('@button') ->assertSeeIn('@foo', 'evaluated-second') ; } public function test_assets_can_be_loaded() { Route::get('/test.js', function () { return Utils::pretendResponseIsFile(__DIR__.'/test.js'); }); Livewire::visit(new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <h1 dusk="foo" wire:ignore></h1> </div> @assets <script src="/test.js" defer></script> @endassets HTML; } }) ->assertSeeIn('@foo', 'evaluated') ; } public function test_remote_assets_can_be_loaded() { Livewire::visit(new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <input type="text" data-picker> <span dusk="output" x-text="'foo'"></span> </div> @assets <script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js" defer></script> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css"> @endassets @script <script> window.datePicker = new Pikaday({ field: $wire.$el.querySelector('[data-picker]') }); </script> @endscript HTML; } }) ->waitForTextIn('@output', 'foo') ->assertScript('!! window.datePicker') ; } public function test_remote_assets_can_be_loaded_lazily() { Livewire::visit(new class extends \Livewire\Component { public $load = false; public function render() { return <<<'HTML' <div> <input type="text" data-picker> <button wire:click="$toggle('load')" dusk="button">Load assets</button> <span dusk="output" x-text="'foo'"></span> </div> @if ($load) @assets <script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js" defer></script> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css"> @endassets @script <script> window.datePicker = new Pikaday({ field: $wire.$el.querySelector('[data-picker]') }); </script> @endscript @endif HTML; } }) ->waitForTextIn('@output', 'foo') ->waitForLivewire()->click('@button') ->waitUntil('!! window.datePicker === true') ; } public function test_remote_assets_can_be_loaded_from_a_deferred_nested_component() { Livewire::visit([new class extends \Livewire\Component { public $load = false; public function render() { return <<<'HTML' <div> <button wire:click="$toggle('load')" dusk="button">Load assets</button> <span dusk="output" x-text="'foo'"></span> @if ($load) <livewire:child /> @endif </div> HTML; } }, 'child' => new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <input type="text" data-picker> </div> @assets <script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css"> @endassets @script <script> window.datePicker = new Pikaday({ field: $wire.$el.querySelector('[data-picker]') }); </script> @endscript HTML; } }, ]) ->waitForTextIn('@output', 'foo') ->waitForLivewire()->click('@button') ->waitUntil('!! window.datePicker === true') ; } public function test_assets_directive_can_be_used_outside_of_a_livewire_compoentn_and_can_be_loaded() { // See the `tweakApplicationHook` method for the route definition. $this->browse(function ($browser) { $browser->visit('/non-livewire-assets') ->assertSeeIn('@foo', 'non livewire evaluated'); }); } public function test_remote_inline_scripts_can_be_loaded_from_a_deferred_nested_component() { Livewire::visit([new class extends \Livewire\Component { public $load = false; public function render() { return <<<'HTML' <div> <button wire:click="$toggle('load')" dusk="button">Load assets</button> <span dusk="output" x-text="'foo'"></span> @if ($load) <livewire:child /> @endif </div> HTML; } }, 'child' => new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <input type="text" data-picker> </div> @assets <script> window.Pikaday = function (options) { // ... return this } </script> @endassets @script <script> window.datePicker = new Pikaday({ field: $wire.$el.querySelector('[data-picker]') }); </script> @endscript HTML; } }, ]) ->waitForTextIn('@output', 'foo') ->waitForLivewire()->click('@button') ->waitUntil('!! window.datePicker === true') ; } public function test_can_listen_for_initial_dispatches_inside_script() { Livewire::visit(new class extends \Livewire\Component { public function render() { $this->dispatch('test')->self(); return <<<'HTML' <div> <h1 dusk="foo"></h1> </div> @script <script> $wire.on('test', () => { $wire.el.querySelector('h1').textContent = 'received' }) </script> @endscript HTML; } }) ->waitForTextIn('@foo', 'received') ; } public function test_functions_loaded_in_scripts_are_not_auto_evaluated() { Livewire::visit(new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <div dusk="output"></div> </div> @script <script> function run() { document.querySelector('[dusk="output"]').textContent = 'evaluated'; } document.querySelector('[dusk="output"]').textContent = 'initialized'; </script> @endscript HTML; } }) ->waitForText('initialized') ->assertSeeIn('@output', 'initialized') ->assertDontSeeIn('@output', 'evaluated') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRouting/UnitTest.php
src/Features/SupportRouting/UnitTest.php
<?php namespace Livewire\Features\SupportRouting; use Illuminate\Support\Facades\Route; use Livewire\Component; use Livewire\Livewire; use Tests\TestCase; class UnitTest extends TestCase { public function test_can_route_to_a_class_based_component_from_standard_route() { Route::get('/component-for-routing', ComponentForRouting::class); $this ->withoutExceptionHandling() ->get('/component-for-routing') ->assertSee('Component for routing'); } public function test_can_use_livewire_macro_to_route_directory_to_class_based_components() { Route::livewire('/component-for-routing', ComponentForRouting::class); $this ->withoutExceptionHandling() ->get('/component-for-routing') ->assertSee('Component for routing'); } public function test_can_use_livewire_macro_to_define_routes() { Livewire::component('component-for-routing', ComponentForRouting::class); Route::livewire('/component-for-routing', 'component-for-routing'); $this ->withoutExceptionHandling() ->get('/component-for-routing') ->assertSee('Component for routing'); } public function test_can_use_livewire_macro_with_anonymous_component_to_define_routes() { Route::livewire('/component-for-routing', new class extends Component { public function render() { return '<div>Component for routing</div>'; } }); $this ->withoutExceptionHandling() ->get('/component-for-routing') ->assertSee('Component for routing'); } public function test_can_use_livewire_macro_with_auto_discvovered_single_file_component() { app('livewire.finder')->addLocation(viewPath: __DIR__ . '/fixtures'); Route::livewire('/component-for-routing', 'sfc-counter'); $this ->withoutExceptionHandling() ->get('/component-for-routing') ->assertSee('Count: 1'); } public function test_route_parameters_are_passed_to_component() { Route::livewire('/route-with-params/{myId}', ComponentForRoutingWithParams::class); $this->get('/route-with-params/123')->assertSeeText('123'); } } class ComponentForRouting extends Component { public function render() { return '<div>Component for routing</div>'; } } class ComponentForRoutingWithParams extends Component { public $myId; public function render() { return <<<'HTML' <div> {{ $myId }} </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRouting/SupportRouting.php
src/Features/SupportRouting/SupportRouting.php
<?php namespace Livewire\Features\SupportRouting; use Illuminate\Support\Facades\Route; use Livewire\ComponentHook; class SupportRouting extends ComponentHook { public static function provide() { Route::macro('livewire', function ($uri, $component) { if (is_object($component)) { app('livewire')->addComponent($component); } return Route::get($uri, function () use ($component) { return app()->call([ app('livewire')->new($component), '__invoke', ]); }); }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRouting/fixtures/sfc-counter.blade.php
src/Features/SupportRouting/fixtures/sfc-counter.blade.php
<?php new class extends Livewire\Component { public int $count = 1; public function increment() { $this->count++; } }; ?> <div> <span>Count: {{ $count }}</span> <button wire:click="increment">Increment</button> </div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSession/BaseSession.php
src/Features/SupportSession/BaseSession.php
<?php namespace Livewire\Features\SupportSession; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; use Illuminate\Support\Facades\Session; use Attribute; #[Attribute(Attribute::TARGET_PROPERTY)] class BaseSession extends LivewireAttribute { function __construct( protected $key = null, ) {} public function mount($params) { if (! $this->exists()) return; $fromSession = $this->read(); $this->setValue($fromSession); } public function dehydrate($context) { $this->write(); } protected function exists() { return Session::exists($this->key()); } protected function read() { return Session::get($this->key()); } protected function write() { Session::put($this->key(), $this->getValue()); } protected function key() { if (! $this->key) { return (string) 'lw' . crc32($this->component->getName() . $this->getName()); } return self::replaceDynamicPlaceholders($this->key, $this->component); } static function replaceDynamicPlaceholders($key, $component) { return preg_replace_callback('/\{(.*)\}/U', function ($matches) use ($component) { return data_get($component, $matches[1], function () use ($matches) { throw new \Exception('Unable to evaluate dynamic session key placeholder: '.$matches[0]); }); }, $key); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSession/BrowserTest.php
src/Features/SupportSession/BrowserTest.php
<?php namespace Livewire\Features\SupportSession; use Livewire\Attributes\Session; use Tests\BrowserTestCase; use Livewire\Component; use Livewire\Livewire; class BrowserTest extends BrowserTestCase { public function test_can_persist_a_property_to_the_session() { Livewire::visit(new class extends Component { #[Session] public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> <button dusk="button" wire:click="increment">+</button> <span dusk="count">{{ $count }}</span> </div> HTML; } }) ->assertSeeIn('@count', '0') ->waitForLivewire()->click('@button') ->assertSeeIn('@count', '1') ->refresh() ->assertSeeIn('@count', '1') ->waitForLivewire()->click('@button') ->assertSeeIn('@count', '2') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSession/UnitTest.php
src/Features/SupportSession/UnitTest.php
<?php namespace Livewire\Features\SupportSession; use Illuminate\Support\Facades\Session as FacadesSession; use Livewire\Attributes\Session; use Tests\TestCase; use Livewire\Livewire; use Tests\TestComponent; class UnitTest extends TestCase { public function test_it_creates_a_session_key() { $component = Livewire::test(new class extends TestComponent { #[Session] public $count = 0; function render() { return <<<'HTML' <div>foo{{ $count }}</div> HTML; } }); $this->assertTrue(FacadesSession::has('lw'.crc32($component->instance()->getName().'count'))); } public function test_it_creates_a_dynamic_session_id() { Livewire::test(new class extends TestComponent { public $post = ['id' => 2]; #[Session(key: 'baz.{post.id}')] public $count = 0; function render() { return <<<'HTML' <div>foo{{ $count }}</div> HTML; } }); $this->assertTrue(FacadesSession::has('baz.2')); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireables/WireableSynth.php
src/Features/SupportWireables/WireableSynth.php
<?php namespace Livewire\Features\SupportWireables; use Livewire\Wireable; use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; class WireableSynth extends Synth { public static $key = 'wrbl'; static function match($target) { return is_object($target) && $target instanceof Wireable; } static function unwrapForValidation($target) { return $target->toLivewire(); } function dehydrate($target, $dehydrateChild) { $data = $target->toLivewire(); foreach ($data as $key => $child) { $data[$key] = $dehydrateChild($key, $child); } return [ $data, ['class' => get_class($target)], ]; } function hydrate($value, $meta, $hydrateChild) { // Verify class implements Wireable even though checksum protects this... if (! isset($meta['class']) || ! is_a($meta['class'], Wireable::class, true)) { throw new \Exception('Livewire: Invalid wireable class.'); } foreach ($value as $key => $child) { $value[$key] = $hydrateChild($key, $child); } return $meta['class']::fromLivewire($value); } function set(&$target, $key, $value) { $target->{$key} = $value; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireables/SupportWireables.php
src/Features/SupportWireables/SupportWireables.php
<?php namespace Livewire\Features\SupportWireables; use Livewire\ComponentHook; class SupportWireables extends ComponentHook { static function provide() { app('livewire')->propertySynthesizer(WireableSynth::class); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireables/BrowserTest.php
src/Features/SupportWireables/BrowserTest.php
<?php namespace Livewire\Features\SupportWireables; use Livewire\Livewire; use Livewire\Wireable; use RuntimeException; class BrowserTest extends \Tests\BrowserTestCase { public function test_it_can_update_a_custom_wireable_object() { Livewire::visit(new class () extends \Livewire\Component { public Person $person; public function mount(): void { $this->person = new Person('Jæja', 42); } public function render(): string { return <<<'HTML' <div> <button type="button" wire:click="$set('person', {'name': 'foo', 'age': 43})" dusk="button">Button</button> <span>{{ $person->age }}</span </div> HTML; } }) ->assertSee('42') ->waitForLivewire()->click('@button') ->assertSee('43'); } public function test_it_can_update_a_custom_wireable_via_inputs() { Livewire::visit(new class () extends \Livewire\Component { public Person $person; public function mount(): void { $this->person = new Person('Jæja', 42); } public function render(): string { return <<<'HTML' <div> <input type="text" dusk="age" wire:model.live="person.age" /> <span>{{ $person->age }}</span> </div> HTML; } }) ->waitForText('42') ->assertSee('42') ->type('@age', '43') ->waitForText('43') ->assertSee('43'); } } class Person implements Wireable { public function __construct( public string $name, public int $age ) { } public function toLivewire() { return ['name' => $this->name, 'age' => $this->age]; } public static function fromLivewire($value) { if (! is_array($value)) { throw new RuntimeException("Can't fromLivewire without it being an array."); } return new self($value['name'], (int) $value['age']); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireables/UnitTest.php
src/Features/SupportWireables/UnitTest.php
<?php namespace Livewire\Features\SupportWireables; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Livewire\Component; use Livewire\Livewire; use Livewire\Wireable; class UnitTest extends \Tests\TestCase { public function test_a_wireable_can_be_set_as_a_public_property_and_validates() { $wireable = new WireableClass($message = Str::random(), $embeddedMessage = Str::random()); Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]) ->assertSee($message) ->assertSee($embeddedMessage) ->call('$refresh') ->assertSee($message) ->assertSee($embeddedMessage) ->call('runValidation') ->assertHasNoErrors(['wireable.message', 'wireable.embeddedWireable.message']) ->call('removeWireable') ->assertDontSee($message) ->assertDontSee($embeddedMessage); } public function test_a_wireable_can_be_updated() { $wireable = new WireableClass('foo', '42'); Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]) ->assertSee('foo') ->call("\$set", 'wireable', ['message' => 'bar', 'embeddedWireable' => ['message' => '42']]) ->call("\$set", 'wireable.message', 'bar') ->assertSee('bar'); } public function test_a_wireable_can_be_set_as_a_public_property_and_validates_only() { $wireable = new WireableClass($message = Str::random(), $embeddedMessage = Str::random()); Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]) ->assertSee($message) ->assertSee($embeddedMessage) ->call('$refresh') ->assertSee($message) ->assertSee($embeddedMessage) ->call('runValidateOnly', 'wireable.message') ->assertHasNoErrors('wireable.message') ->call('runValidateOnly', 'wireable.embeddedWireable.message') ->assertHasNoErrors('wireable.embeddedWireable.message') ->call('removeWireable') ->assertDontSee($message) ->assertDontSee($embeddedMessage); } public function test_a_wireable_can_be_set_as_a_public_property_and_has_single_validation_error() { $wireable = new WireableClass($message = '', $embeddedMessage = Str::random()); Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]) ->assertSee($message) ->assertSee($embeddedMessage) ->call('$refresh') ->assertSee($message) ->assertSee($embeddedMessage) ->call('runValidation') ->assertHasErrors(['wireable.message' => 'required']) ->assertHasNoErrors('wireable.embeddedWireable.message') ->call('removeWireable') ->assertDontSee($embeddedMessage); } public function test_a_wireable_can_be_set_as_a_public_property_and_has_single_validation_error_on_validates_only() { $wireable = new WireableClass($message = '', $embeddedMessage = Str::random()); Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]) ->assertSee($message) ->assertSee($embeddedMessage) ->call('$refresh') ->assertSee($message) ->assertSee($embeddedMessage) ->call('runValidateOnly', 'wireable.message') ->assertHasErrors(['wireable.message' => 'required']) ->assertHasNoErrors('wireable.embeddedWireable.message') ->call('removeWireable') ->assertDontSee($embeddedMessage); } public function test_a_wireable_can_be_set_as_a_public_property_and_has_embedded_validation_error() { $wireable = new WireableClass($message = Str::random(), $embeddedMessage = ''); Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]) ->assertSee($message) ->assertSee($embeddedMessage) ->call('$refresh') ->assertSee($message) ->assertSee($embeddedMessage) ->call('runValidation') ->assertHasErrors(['wireable.embeddedWireable.message' => 'required']) ->assertHasNoErrors('wireable.message') ->call('removeWireable') ->assertDontSee($message); } public function test_a_wireable_can_be_set_as_a_public_property_and_has_embedded_validation_error_on_validate_only() { $wireable = new WireableClass($message = Str::random(), $embeddedMessage = ''); Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]) ->assertSee($message) ->assertSee($embeddedMessage) ->call('$refresh') ->assertSee($message) ->assertSee($embeddedMessage) ->call('runValidateOnly', 'wireable.embeddedWireable.message') ->assertHasErrors(['wireable.embeddedWireable.message' => 'required']) ->assertHasNoErrors('wireable.message') ->call('removeWireable') ->assertDontSee($message); } public function test_a_wireable_can_be_set_as_a_public_property_and_has_single_and_embedded_validation_errors() { $wireable = new WireableClass($message = '', $embeddedMessage = ''); Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]) ->assertSee($message) ->assertSee($embeddedMessage) ->call('$refresh') ->assertSee($message) ->assertSee($embeddedMessage) ->call('runValidation') ->assertHasErrors(['wireable.message' => 'required', 'wireable.embeddedWireable.message' => 'required']) ->call('removeWireable'); } public function test_a_wireable_can_be_set_as_a_public_property_and_has_single_and_embedded_validation_errors_on_validate_only() { $wireable = new WireableClass($message = '', $embeddedMessage = ''); Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]) ->assertSee($message) ->assertSee($embeddedMessage) ->call('$refresh') ->assertSee($message) ->assertSee($embeddedMessage) ->call('runValidateOnly', 'wireable.message') ->assertHasErrors(['wireable.message' => 'required']) ->call('$refresh') ->assertSee($message) ->assertSee($embeddedMessage) ->call('runValidateOnly', 'wireable.embeddedWireable.message') ->assertHasErrors(['wireable.embeddedWireable.message' => 'required']) ->call('removeWireable'); } public function test_wireable_synth_rejects_non_wireable_classes() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid wireable class'); $wireable = new WireableClass('test', 'test'); $component = Livewire::test(ComponentWithWireablePublicProperty::class, ['wireable' => $wireable]); // Create a synth instance and try to hydrate with a non-Wireable class $synth = new WireableSynth( new \Livewire\Mechanisms\HandleComponents\ComponentContext($component->instance()), 'wireable' ); // This should throw because stdClass doesn't implement Wireable $synth->hydrate(['message' => 'test'], ['class' => \stdClass::class], fn($k, $v) => $v); } } class WireableClass implements Wireable { public $message; public EmbeddedWireableClass $embeddedWireable; public function __construct($message, $embeddedMessage) { $this->message = $message; $this->embeddedWireable = new EmbeddedWireableClass($embeddedMessage); } public function toLivewire() { return [ 'message' => $this->message, 'embeddedWireable' => $this->embeddedWireable->toLivewire(), ]; } public static function fromLivewire($value): self { return new self($value['message'], $value['embeddedWireable']['message']); } } class EmbeddedWireableClass implements Wireable { public $message; public function __construct($message) { $this->message = $message; } public function toLivewire() { return [ 'message' => $this->message, ]; } public static function fromLivewire($value): self { return new self($value['message']); } } class ComponentWithWireablePublicProperty extends Component { public ?WireableClass $wireable; public $rules = [ 'wireable.message' => 'string|required', 'wireable.embeddedWireable.message' => 'string|required' ]; public function mount($wireable) { $this->wireable = $wireable; } public function runValidation() { $this->validate(); } public function runValidateOnly($propertyName) { $this->validateOnly($propertyName); } public function removeWireable() { $this->resetErrorBag(); $this->wireable = null; } public function runResetValidation() { $this->resetValidation(); } public function render() { return <<<'HTML' <div> <div> @if ($wireable) {{ $wireable->message }} @if ($wireable->embeddedWireable ?? false) {{ $wireable->embeddedWireable->message }} @endif @endif </div> </div> HTML; } } class CustomWireableCollection extends Collection implements Wireable { public function toLivewire() { return $this->mapWithKeys(function ($dto, $key) { return [$key => $dto instanceof CustomWireableDTO ? $dto->toLivewire() : $dto]; })->all(); } public static function fromLivewire($value) { return static::wrap($value) ->mapWithKeys(function ($dto, $key) { return [$key => CustomWireableDTO::fromLivewire($dto)]; }); } } class CustomWireableDTO implements Wireable { public $amount; public function __construct($amount) { $this->amount = $amount; } public function toLivewire() { return [ 'amount' => $this->amount ]; } public static function fromLivewire($value) { return new static( $value['amount'] ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSlots/SupportSlots.php
src/Features/SupportSlots/SupportSlots.php
<?php namespace Livewire\Features\SupportSlots; use Livewire\ComponentHook; use function Livewire\on; class SupportSlots extends ComponentHook { public static function provide() { on('mount.stub', function ($tag, $id, $params, $parent, $key, $slots) { // If a child component is skipped in a subsequent render, capture slots passed // into to it so that the parent can add them to the response for morphing... $parent->withChildSlots($slots, $id); }); } public function render($view, $properties) { // Ensure that the slot proxy is available for child views... $slots = $this->component->getSlots(); $slotProxy = new SlotProxy($this->component, $slots); $view->with([ 'slot' => $slotProxy, 'slots' => $slotProxy, ]); } public function renderIsland($name, $view, $properties) { $slots = $this->component->getSlots(); $slotProxy = new SlotProxy($this->component, $slots); $view->with([ 'slot' => $slotProxy, 'slots' => $slotProxy, ]); } function hydrate($memo) { // When a child component re-renders, we will need to stub out the known slots // with placeholders so that they can be rendered and morph'd correctly... $slots = $memo['slots'] ?? []; if (! empty($slots)) { $this->component->withPlaceholderSlots($slots); } } public function dehydrate($context) { $this->dehydrateSlotsThatWereRenderedIntoMorphEffects($context); $this->dehydrateSlotsThatWerePassedToTheComponentForSubsequentRenders($context); } protected function dehydrateSlotsThatWereRenderedIntoMorphEffects($context) { // When a parent renders, capture the slots and include them in the response... $slots = $this->component->getSlotsForSkippedChildRenders(); if (! empty($slots)) { $context->addEffect('slotFragments', $slots); } } protected function dehydrateSlotsThatWerePassedToTheComponentForSubsequentRenders($context) { // Ensure a child component is aware of what slots belong to it... $slots = $this->component->getSlots(); $slotMemo = []; foreach ($slots as $slot) { $slotMemo[] = [ 'name' => $slot->getName(), 'componentId' => $slot->getComponentId(), 'parentId' => $slot->getParentId(), ]; } if (! empty($slotMemo)) { $context->addMemo('slots', $slotMemo); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSlots/Slot.php
src/Features/SupportSlots/Slot.php
<?php namespace Livewire\Features\SupportSlots; use Illuminate\Contracts\Support\Htmlable; class Slot implements Htmlable { public function __construct( public string $name, public string $content, public string $componentId, public ?string $parentComponentId = null, ) {} public function getName(): string { return $this->name; } public function getComponentId(): string { return $this->componentId; } public function getParentId(): ?string { return $this->parentComponentId; } public function toHtml(): string { $parentPart = $this->parentComponentId ? ['parent' => $this->parentComponentId] : []; return $this->wrapWithFragmentMarkers($this->content, [ 'name' => $this->name, 'type' => 'slot', 'id' => $this->componentId, // This is here for JS to match opening and close markers... 'token' => crc32($this->name . $this->componentId . $this->parentComponentId ?? ''), 'mode' => 'morph', ...$parentPart, ]); } protected function wrapWithFragmentMarkers($output, $metadata) { $startFragment = "<!--[if FRAGMENT:{$this->encodeFragmentMetadata($metadata)}]><![endif]-->"; $endFragment = "<!--[if ENDFRAGMENT:{$this->encodeFragmentMetadata($metadata)}]><![endif]-->"; return $startFragment . $output . $endFragment; } protected function encodeFragmentMetadata($metadata) { $output = ''; foreach ($metadata as $key => $value) { $output .= "{$key}={$value}|"; } return rtrim($output, '|'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSlots/SlotProxy.php
src/Features/SupportSlots/SlotProxy.php
<?php namespace Livewire\Features\SupportSlots; use ArrayAccess; use Illuminate\Contracts\Support\Htmlable; use Livewire\Features\SupportSlots\Slot; use Livewire\Component; class SlotProxy implements Htmlable, ArrayAccess { public function __construct( protected Component $component, protected array $slots, ) {} public function __invoke($name = 'default') { return $this->get($name); } public function find($name) { foreach ($this->slots as $slot) { if ($slot->getName() === $name) { return $slot; } } return null; } public function get($name = 'default') { return $this->find($name) ?? new Slot($name, '', $this->component->getId()); } public function has($name): bool { return $this->find($name) !== null; } public function toHtml(): string { return $this->__toString(); } public function __toString(): string { return $this->get('default')->toHtml(); } public function offsetExists($offset): bool { return $this->has($offset); } public function offsetGet($offset): mixed { return $this->get($offset); } public function offsetSet($offset, $value): void { // } public function offsetUnset($offset): void { // } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSlots/PlaceholderSlot.php
src/Features/SupportSlots/PlaceholderSlot.php
<?php namespace Livewire\Features\SupportSlots; use Illuminate\Contracts\Support\Htmlable; class PlaceholderSlot implements Htmlable { public function __construct( public string $name, public string $componentId, public ?string $parentComponentId = null, ) {} public function getName(): string { return $this->name; } public function getComponentId(): string { return $this->componentId; } public function getParentId(): ?string { return $this->parentComponentId; } public function toHtml(): string { $parentPart = $this->parentComponentId ? ['parent' => $this->parentComponentId] : []; return $this->wrapWithFragmentMarkers('', [ 'name' => $this->name, 'type' => 'slot', 'id' => $this->componentId, // This is here for JS to match opening and close markers... 'token' => crc32($this->name . $this->componentId . $this->parentComponentId ?? ''), 'mode' => 'skip', ...$parentPart, ]); } protected function wrapWithFragmentMarkers($output, $metadata) { $startFragment = "<!--[if FRAGMENT:{$this->encodeFragmentMetadata($metadata)}]><![endif]-->"; $endFragment = "<!--[if ENDFRAGMENT:{$this->encodeFragmentMetadata($metadata)}]><![endif]-->"; return $startFragment . $output . $endFragment; } protected function encodeFragmentMetadata($metadata) { $output = ''; foreach ($metadata as $key => $value) { $output .= "{$key}={$value}|"; } return rtrim($output, '|'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSlots/BrowserTest.php
src/Features/SupportSlots/BrowserTest.php
<?php namespace Livewire\Features\SupportSlots; use Tests\BrowserTestCase; use Livewire\Livewire; use Livewire\Component; class BrowserTest extends BrowserTestCase { public function test_default_slots() { Livewire::visit([ new class extends Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> <h1>Parent Component</h1> <span dusk="outer-count">{{ $count }}</span> <livewire:modal> <button dusk="outer-slot-button" wire:click="increment">Increment</button> <span dusk="outer-slot-count">{{ $count }}</span> <livewire:slot name="header"> <button dusk="outer-header-slot-button" wire:click="increment">Increment</button> <span dusk="outer-header-slot-count">{{ $count }}</span> </livewire:slot> </livewire:modal> </div> HTML; } }, 'modal' => new class extends Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div dusk="modal"> <span dusk="inner-count">{{ $count }}</span> <button dusk="inner-count-button" wire:click="increment">Increment</button> <div class="modal-header"> {{ $slot('header') }} </div> <div class="modal-body"> {{ $slot }} </div> <div x-text="'loaded'"></div> </div> HTML; } } ]) ->assertSeeIn('@outer-count', '0') ->assertSeeIn('@outer-slot-count', '0') ->assertSeeIn('@outer-header-slot-count', '0') ->assertSeeIn('@inner-count', '0') ->waitForLivewire()->click('@outer-slot-button') ->assertSeeIn('@outer-count', '1') ->assertSeeIn('@outer-slot-count', '1') ->assertSeeIn('@outer-header-slot-count', '1') ->assertSeeIn('@inner-count', '0') ->waitForLivewire()->click('@outer-header-slot-button') ->assertSeeIn('@outer-count', '2') ->assertSeeIn('@outer-slot-count', '2') ->assertSeeIn('@outer-header-slot-count', '2') ->assertSeeIn('@inner-count', '0') ->waitForLivewire()->click('@inner-count-button') ->assertSeeIn('@outer-count', '2') ->assertSeeIn('@outer-slot-count', '2') ->assertSeeIn('@outer-header-slot-count', '2') ->assertSeeIn('@inner-count', '1') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSlots/UnitTest.php
src/Features/SupportSlots/UnitTest.php
<?php namespace Livewire\Features\SupportSlots; use Livewire\Livewire; class UnitTest extends \Tests\TestCase { public function test_named_slot() { Livewire::test([ new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <livewire:child> <livewire:slot name="header"> Header </livewire:slot> Hello world </livewire:child> </div> HTML; } }, 'child' => new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> @if ($slots->has('header')) {{ $slots->get('header') }} @endif {{ $slots['default'] }} </div> HTML; } }, ]) ->assertSee('Header') ->assertSee('Hello world') ; } public function test_slot_with_short_attribute_syntax() { Livewire::test([ new class extends \Livewire\Component { public $foo = 'foo'; public function render() { return <<<'HTML' <div> @foreach (range(1, 3) as $i) <livewire:child :$foo>Hello world</livewire:child> @endforeach </div> HTML; } }, 'child' => new class extends \Livewire\Component { public $foo; public function render() { return <<<'HTML' <div {{ $attributes->class('child') }}>{{ $slot }}</div> HTML; } }, ]) ->assertSee([ 'Hello world', ]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSlots/HandlesSlots.php
src/Features/SupportSlots/HandlesSlots.php
<?php namespace Livewire\Features\SupportSlots; trait HandlesSlots { /** * Parent concerns... */ protected array $slotsForSkippedChildRenders = []; public function getSlotsForSkippedChildRenders() { return $this->slotsForSkippedChildRenders; } public function withChildSlots(array $slots, $childId) { foreach ($slots as $name => $content) { $this->slotsForSkippedChildRenders[] = (new Slot($name, $content, $childId, $this->getId()))->toHtml(); } } /** * Child concerns... */ protected array $slots = []; public function getSlots() { return $this->slots; } public function withSlots(array $slots, $parent = null): self { $parentId = $parent && method_exists($parent, 'getId') ? $parent->getId() : null; foreach ($slots as $name => $content) { $this->slots[] = new Slot($name, $content, $this->getId(), $parentId); } return $this; } public function withPlaceholderSlots(array $slots): self { foreach ($slots as $slot) { $this->slots[] = new PlaceholderSlot( $slot['name'], $slot['componentId'], $slot['parentId'], ); } return $this; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEvents/TestsEvents.php
src/Features/SupportEvents/TestsEvents.php
<?php namespace Livewire\Features\SupportEvents; use PHPUnit\Framework\Assert as PHPUnit; trait TestsEvents { public function dispatch($event, ...$parameters) { return $this->call('__dispatch', $event, $parameters); } public function fireEvent($event, ...$parameters) { return $this->dispatch($event, ...$parameters); } public function assertDispatched($event, ...$params) { $result = $this->testDispatched($event, $params); PHPUnit::assertTrue($result['test'], "Failed asserting that an event [{$event}] was fired{$result['assertionSuffix']}"); return $this; } public function assertNotDispatched($event, ...$params) { $result = $this->testDispatched($event, $params); PHPUnit::assertFalse($result['test'], "Failed asserting that an event [{$event}] was not fired{$result['assertionSuffix']}"); return $this; } public function assertDispatchedTo($target, $event, ...$params) { $this->assertDispatched($event, ...$params); $result = $this->testDispatchedTo($target, $event); PHPUnit::assertTrue($result, "Failed asserting that an event [{$event}] was fired to {$target}."); return $this; } protected function testDispatched($value, $params) { $assertionSuffix = '.'; if (empty($params)) { $test = collect(data_get($this->effects, 'dispatches'))->contains('name', '=', $value); } elseif (isset($params[0]) && ! is_string($params[0]) && is_callable($params[0])) { $event = collect(data_get($this->effects, 'dispatches'))->first(function ($item) use ($value) { return $item['name'] === $value; }); $test = $event && $params[0]($event['name'], $event['params']); } else { $test = (bool) collect(data_get($this->effects, 'dispatches'))->first(function ($item) use ($value, $params) { $commonParams = array_intersect_key($item['params'], $params); ksort($commonParams); ksort($params); return $item['name'] === $value && $commonParams === $params; }); $encodedParams = json_encode($params); $assertionSuffix = " with parameters: {$encodedParams}"; } return [ 'test' => $test, 'assertionSuffix' => $assertionSuffix, ]; } protected function testDispatchedTo($target, $value) { $name = app('livewire.factory')->resolveComponentName($target); return (bool) collect(data_get($this->effects, 'dispatches'))->first(function ($item) use ($name, $value) { return $item['name'] === $value && $item['component'] === $name; }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEvents/BaseOn.php
src/Features/SupportEvents/BaseOn.php
<?php namespace Livewire\Features\SupportEvents; use Attribute; use Illuminate\Support\Arr; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; use function Livewire\store; #[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)] class BaseOn extends LivewireAttribute { public function __construct(public $event) {} public function boot() { foreach (Arr::wrap($this->event) as $event) { store($this->component)->push( 'listenersFromAttributes', $this->getName() ?? '$refresh', $event, ); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEvents/BrowserTest.php
src/Features/SupportEvents/BrowserTest.php
<?php namespace Livewire\Features\SupportEvents; use Illuminate\Support\Facades\Blade; use Livewire\Attributes\On; use Livewire\Attributes\Renderless; use Tests\BrowserTestCase; use Livewire\Component; use Livewire\Livewire; class BrowserTest extends BrowserTestCase { public function test_can_listen_for_component_event_with_this_on_in_javascript() { Livewire::visit(new class extends Component { function foo() { $this->dispatch('foo'); } function render() { return <<<'HTML' <div> <button wire:click="foo" dusk="button">Dispatch "foo"</button> <span x-init="@this.on('foo', () => { $el.textContent = 'bar' })" dusk="target" wire:ignore></span> </div> HTML; } }) ->assertDontSeeIn('@target', 'bar') ->waitForLivewire()->click('@button') ->assertSeeIn('@target', 'bar'); } public function test_dont_call_render_on_renderless_event_handler() { Livewire::visit(new class extends Component { public $count = 0; protected $listeners = ['foo' => 'onFoo']; #[Renderless] function onFoo() { } function render() { $this->count++; return Blade::render(<<<'HTML' <div> <button @click="$dispatch('foo')" dusk="button">{{ $count }}</button> </div> HTML, ['count' => $this->count]); } }) ->assertSeeIn('@button', '1') ->waitForLivewire()->click('@button') ->assertSeeIn('@button', '1'); } public function test_event_handler_with_single_parameter() { Livewire::visit(new class extends Component { public $button = 'Text'; protected $listeners = ['foo' => 'onFoo']; function onFoo($param) { $this->button = $param; } function bar() { $this->dispatch('foo', 'Bar set text'); } function render() { return Blade::render(<<<'HTML' <div> <button @click="Livewire.dispatch('foo', 'Param Set Text')" dusk="button">{{ $button }}</button> <button wire:click="bar" dusk="bar-button">Bar</button> </div> HTML, ['button' => $this->button]); } }) ->assertSeeIn('@button', 'Text') ->waitForLivewire()->click('@button') ->assertSeeIn('@button', 'Param Set Text') ->waitForLivewire()->click('@bar-button') ->assertSeeIn('@button', 'Bar set text'); } public function test_can_dispatch_self_inside_script_directive() { Livewire::visit(new class extends Component { public $foo = 'bar'; #[On('trigger')] function changeFoo() { $this->foo = 'baz'; } function render() { return <<<'HTML' <div> <h1 dusk="output">{{ $foo }}</h1> </div> @script <script> $wire.dispatchSelf('trigger') </script> @endscript HTML; } }) ->waitForTextIn('@output', 'baz'); } public function test_dispatch_from_javascript_should_only_be_called_once() { Livewire::visit(new class extends Component { public $count = 0; protected $listeners = ['foo' => 'onFoo']; function onFoo() { $this->count++; } function render() { return Blade::render(<<<'HTML' <div> <button @click="$dispatch('foo')" dusk="button">{{ $count }}</button> </div> HTML, ['count' => $this->count]); } }) ->assertSeeIn('@button', '0') ->waitForLivewire()->click('@button') ->assertSeeIn('@button', '1'); } public function test_can_dispatch_to_another_component_globally() { Livewire::visit([ new class extends Component { public function dispatchToOtherComponent() { $this->dispatch('foo', message: 'baz')->to('child'); } function render() { return <<<'HTML' <div> <button x-on:click="window.Livewire.dispatchTo('child', 'foo', { message: 'bar' })" dusk="button">Dispatch to child from Alpine</button> <button wire:click="dispatchToOtherComponent" dusk="button2">Dispatch to child from Livewire</button> <livewire:child /> </div> HTML; } }, 'child' => new class extends Component { public $message = 'foo'; protected $listeners = ['foo' => 'onFoo']; function onFoo($message) { $this->message = $message; } function render() { return <<<'HTML' <div> <h1 dusk="output">{{ $message }}</h1> </div> HTML; } }, ]) ->assertSeeIn('@output', 'foo') ->waitForLivewire()->click('@button') ->waitForTextIn('@output', 'bar') // For some reason this is flaky? // ->waitForLivewire()->click('@button2') // ->waitForTextIn('@output', 'baz') ; } public function test_can_unregister_global_livewire_listener() { Livewire::visit(new class extends Component { function render() { return Blade::render(<<<'HTML' <div x-data="{ count: 0, listener: null, init() { this.listener = Livewire.on('foo', () => { this.count++ }) }, removeListener() { this.listener() } }"> <span x-text="count" dusk="text"></span> <button @click="Livewire.dispatch('foo')" dusk="dispatch">Dispatch Event</button> <button @click="removeListener" dusk="removeListener">Remove Listener</button> </div> HTML); } }) ->assertSeeIn('@text', '0') ->click('@dispatch') ->assertSeeIn('@text', '1') ->click('@removeListener') ->click('@dispatch') ->assertSeeIn('@text', '1') ; } public function test_can_use_event_data_in_alpine_for_loop_without_throwing_errors() { Livewire::visit(new class extends Component { function fetchItems() { $this->dispatch('items-fetched', items: [ ['id' => 1, 'name' => 'test 1'], ['id' => 2, 'name' => 'test 2'], ['id' => 3, 'name' => 'test 3'], ]); } function render() { return Blade::render(<<<'HTML' <div x-data="{ items: [] }" @items-fetched.window="items = $event.detail.items"> <button wire:click="fetchItems" dusk="button">Fetch Items</button> <div dusk="text" x-text="items"></div> <div id="root"> <h1 dusk="texst" x-text="items"></h1> <template x-for="item in items" :key="item.id"> <div x-text="item.name"></div> </template> </div> </div> HTML); } }) ->waitForLivewire()->click('@button') ->assertSeeIn('@text', '[object Object],[object Object],[object Object]') ->assertScript('document.getElementById(\'root\').querySelectorAll(\'div\').length', 3) ->assertConsoleLogMissingWarning('item is not defined'); } public function test_nested_components_with_listeners_are_cleaned_up_before_events_are_dispatched() { Livewire::visit([ new class () extends Component { public $test = 1; public function change() { $this->test = $this->test + 1; $this->dispatch("whatever"); } public function render() { return <<<'HTML' <div> <button wire:click="change" dusk="change">change</button> <livewire:child1 :data="$test" :key="$test"/> </div> HTML; } }, 'child1' => new class () extends Component { public $data; #[On('whatever')] public function triggeredEvent() { // } public function render() { return <<<'HTML' <div> <p>Child : {{ $data }} <br/>ID: {{ $this->__id }}</p> <livewire:child2 :data="$data" :key="$data"/> </div> HTML; } }, 'child2' => new class () extends Component { public $data; public function render() { return <<<'HTML' <p> Child 2: {{ $data }}<br/>ID :{{ $this->__id }} </p> HTML; } }, ]) ->waitForLivewireToLoad() ->waitForLivewire()->click('@change') ->assertConsoleLogHasNoErrors(); } public function test_empty_wire_expression_does_not_throw_errors() { Livewire::visit(new class extends Component { function render() { return <<<'HTML' <div> <button wire:click dusk="button">Click me</button> </div> HTML; } }) ->waitForLivewireToLoad() ->click('@button') ->pause(100) ->assertConsoleLogHasNoErrors(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEvents/EchoBrowserTest.php
src/Features/SupportEvents/EchoBrowserTest.php
<?php namespace Livewire\Features\SupportEvents; use Tests\BrowserTestCase; use Livewire\Livewire; use Livewire\Drawer\Utils; use Livewire\Component; use Livewire\Attributes\On; use Illuminate\Support\Facades\Route; class EchoBrowserTest extends BrowserTestCase { public function test_can_listen_for_echo_event() { Route::get('/dusk/fake-echo', function () { return Utils::pretendResponseIsFile(__DIR__.'/fake-echo.js'); }); Livewire::visit(new class extends Component { public $count = 0; #[On('echo:orders,OrderShipped')] function foo() { $this->count++; } function render() { return <<<'HTML' <div> <span dusk="count">{{ $count }}</span> <script src="/dusk/fake-echo"></script> </div> HTML; } }) ->assertSeeIn('@count', '0') ->waitForLivewire(function ($b) { $b->script("window.Echo.fakeTrigger({ channel: 'orders', event: 'OrderShipped' })"); }) ->assertSeeIn('@count', '1'); } public function test_can_listen_for_echo_event_with_payload() { Route::get('/dusk/fake-echo', function () { return Utils::pretendResponseIsFile(__DIR__.'/fake-echo.js'); }); Livewire::visit(new class extends Component { public $orderId = 0; #[On('echo:orders,OrderShipped')] function foo($event) { $this->orderId = $event['order_id']; } function render() { return <<<'HTML' <div> <span dusk="orderId">{{ $orderId }}</span> <script src="/dusk/fake-echo"></script> </div> HTML; } }) ->assertSeeIn('@orderId', '0') ->waitForLivewire(function ($b) { $b->script("window.Echo.fakeTrigger({ channel: 'orders', event: 'OrderShipped', payload: { order_id : 1234 }})"); }) ->assertSeeIn('@orderId', '1234'); } // This test asserts agains a scenario that fails silently. Therefore I can't easily make a test for it. // I'm leaving it here as a playground for the issue (that has been mostly resolved)... // public function test_echo_listeners_are_torn_down_when_navigating_pages_using_wire_navigate() // { // Route::get('/dusk/fake-echo', function () { // return Utils::pretendResponseIsFile(__DIR__.'/fake-echo.js'); // }); // Route::get('/second-page', function (){ // return Blade::render(<<<'HTML' // <x-layouts.app> // Second page // @livewireScripts // </x-layouts.app> // HTML); // })->middleware('web'); // Livewire::visit(new class extends Component { // public $count = 0; // #[On('echo:orders,OrderShipped')] // function foo() { // $this->count++; // } // function render() // { // return <<<'HTML' // <div> // <span dusk="count">{{ $count }}</span> // <a href="/second-page" wire:navigate>yoyoyo</a> // <script src="/dusk/fake-echo"></script> // </div> // HTML; // } // }) // ->tinker() // ; // } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEvents/UnitTest.php
src/Features/SupportEvents/UnitTest.php
<?php namespace Livewire\Features\SupportEvents; use Livewire\Component; use Livewire\Livewire; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_receive_event_with_attribute() { $component = Livewire::test(new class extends TestComponent { public $foo = 'bar'; #[BaseOn('bar')] public function onBar($param) { $this->foo = $param; } }); $component->dispatch('bar', 'baz'); $this->assertEquals($component->get('foo'), 'baz'); } public function test_listen_for_dynamic_event_name() { $component = Livewire::test(new class extends TestComponent { public $post = ['id' => 2]; public $foo = 'bar'; #[BaseOn('bar.{post.id}')] public function onBar($param) { $this->foo = $param; } }); $component->dispatch('bar.2', 'baz'); $this->assertEquals($component->get('foo'), 'baz'); } public function test_listens_for_event_with_named_params() { $component = Livewire::test(new class extends TestComponent { public $foo = 'bar'; #[BaseOn('bar')] public function onBar($name, $game) { $this->foo = $name . $game; } }); $component->dispatch('bar', game: 'shmaz', name: 'baz'); $this->assertEquals($component->get('foo'), 'bazshmaz'); } public function test_dispatches_event_with_named_params() { Livewire::test(new class extends TestComponent { public function dispatchFoo() { $this->dispatch('foo', name: 'bar', game: 'baz'); } }) ->call('dispatchFoo') ->assertDispatched('foo') ->assertDispatched('foo', name: 'bar') ->assertDispatched('foo', name: 'bar', game: 'baz') ->assertDispatched('foo', game: 'baz', name: 'bar') ->assertNotDispatched('foo', games: 'baz') ->assertNotDispatched('foo', name: 'baz') ; } public function test_it_can_register_multiple_listeners_via_attribute(): void { Livewire::test(new class extends TestComponent { public $counter = 0; #[BaseOn('foo'), BaseOn('bar')] public function add(): void { $this->counter++; } }) ->dispatch('foo') ->assertSetStrict('counter', 1) ->dispatch('bar') ->assertSetStrict('counter', 2); } public function test_it_can_register_multiple_listeners_via_attribute_userland(): void { Livewire::test(new class extends TestComponent { public $counter = 0; #[\Livewire\Attributes\On('foo'), \Livewire\Attributes\On('bar')] public function add(): void { $this->counter++; } }) ->dispatch('foo') ->assertSetStrict('counter', 1) ->dispatch('bar') ->assertSetStrict('counter', 2); } public function test_receive_event() { $component = Livewire::test(ReceivesEvents::class); $component->dispatch('bar', 'baz'); $this->assertEquals($component->get('foo'), 'baz'); } public function test_receive_event_with_single_value_listener() { $component = Livewire::test(ReceivesEventsWithSingleValueListener::class); $component->dispatch('bar', 'baz'); $this->assertEquals($component->get('foo'), 'baz'); } public function test_receive_event_with_multiple_parameters() { $component = Livewire::test(ReceivesEvents::class); $component->dispatch('bar', 'baz', 'blab'); $this->assertEquals($component->get('foo'), 'bazblab'); } public function test_listeners_are_provided_to_frontend() { $component = Livewire::test(ReceivesEvents::class); $this->assertTrue(in_array('bar', $component->effects['listeners'])); } public function test_server_dispatched_events_are_provided_to_frontend() { $component = Livewire::test(ReceivesEvents::class); $component->call('dispatchGoo'); $this->assertTrue(in_array(['name' => 'goo', 'params' => ['car']], $component->effects['dispatches'])); } public function test_server_dispatched_self_events_are_provided_to_frontend() { $component = Livewire::test(ReceivesEvents::class); $component->call('dispatchSelfGoo'); $this->assertTrue(in_array(['self' => true, 'name' => 'goo', 'params' => ['car']], $component->effects['dispatches'])); } public function test_component_can_set_dynamic_listeners() { Livewire::test(ReceivesEventsWithDynamicListeners::class, ['listener' => 'bob']) ->dispatch('bob', 'lob') ->assertSetStrict('foo', 'lob'); } public function test_component_receives_events_dispatched_using_classname() { $component = Livewire::test(ReceivesEvents::class); $component->call('dispatchToComponentUsingClassname'); $this->assertTrue(in_array(['component' => 'livewire.features.support-events.it-can-receive-event-using-classname', 'name' => 'foo', 'params' => ['test']], $component->effects['dispatches'])); } public function test_receive_event_with_refresh_attribute() { $component = Livewire::test(ReceivesEventUsingRefreshAttribute::class); $this->assertEquals(1, ReceivesEventUsingRefreshAttribute::$counter); $component->dispatch('bar'); $this->assertEquals(2, ReceivesEventUsingRefreshAttribute::$counter); } public function test_it_can_register_multiple_listeners_via_refresh_attribute(): void { Livewire::test(ReceivesMultipleEventsUsingMultipleRefreshAttributes::class) ->tap(fn () => $this->assertEquals(1, ReceivesMultipleEventsUsingMultipleRefreshAttributes::$counter)) ->dispatch('foo') ->tap(fn () => $this->assertEquals(2, ReceivesMultipleEventsUsingMultipleRefreshAttributes::$counter)) ->dispatch('bar') ->tap(fn () => $this->assertEquals(3, ReceivesMultipleEventsUsingMultipleRefreshAttributes::$counter)); } public function test_it_can_register_multiple_listeners_via_single_refresh_attribute(): void { Livewire::test(ReceivesMultipleEventsUsingSingleRefreshAttribute::class) ->tap(fn () => $this->assertEquals(1, ReceivesMultipleEventsUsingSingleRefreshAttribute::$counter)) ->dispatch('foo') ->tap(fn () => $this->assertEquals(2, ReceivesMultipleEventsUsingSingleRefreshAttribute::$counter)) ->dispatch('bar') ->tap(fn () => $this->assertEquals(3, ReceivesMultipleEventsUsingSingleRefreshAttribute::$counter)); } public function test_it_can_register_multiple_listeners_via_refresh_attribute_userland(): void { Livewire::test(ReceivesMultipleEventsUsingMultipleUserlandRefreshAttributes::class) ->tap(fn () => $this->assertEquals(1, ReceivesMultipleEventsUsingMultipleUserlandRefreshAttributes::$counter)) ->dispatch('foo') ->tap(fn () => $this->assertEquals(2, ReceivesMultipleEventsUsingMultipleUserlandRefreshAttributes::$counter)) ->dispatch('bar') ->tap(fn () => $this->assertEquals(3, ReceivesMultipleEventsUsingMultipleUserlandRefreshAttributes::$counter)); } } class ReceivesEvents extends TestComponent { public $foo; protected $listeners = ['bar' => 'onBar']; public function onBar($value, $otherValue = '') { $this->foo = $value.$otherValue; } public function dispatchGoo() { $this->dispatch('goo', 'car'); } public function dispatchSelfGoo() { $this->dispatch('goo', 'car')->self(); } public function dispatchToGooGone() { $this->dispatch('gone', 'car')->to('goo'); } public function dispatchToComponentUsingClassname() { $this->dispatch('foo', 'test')->to(ItCanReceiveEventUsingClassname::class); } } class ReceivesEventsWithSingleValueListener extends TestComponent { public $foo; protected $listeners = ['bar']; public function bar($value) { $this->foo = $value; } } class ReceivesEventsWithDynamicListeners extends TestComponent { public $listener; public $foo = ''; public function mount($listener) { $this->listener = $listener; } protected function getListeners() { return [$this->listener => 'handle']; } public function handle($value) { $this->foo = $value; } } class ItCanReceiveEventUsingClassname extends TestComponent { public $bar; public $listeners = [ 'foo' => 'bar' ]; public function onBar($value) { $this->bar = $value; } } #[BaseOn('bar')] class ReceivesEventUsingRefreshAttribute extends Component { public static $counter = 0; public function render() { static::$counter++; return '<div></div>'; } } #[BaseOn('foo'), BaseOn('bar')] class ReceivesMultipleEventsUsingMultipleRefreshAttributes extends Component { public static $counter = 0; public function render() { static::$counter++; return '<div></div>'; } } #[BaseOn(['foo', 'bar'])] class ReceivesMultipleEventsUsingSingleRefreshAttribute extends Component { public static $counter = 0; public function render() { static::$counter++; return '<div></div>'; } } #[\Livewire\Attributes\On('foo'), \Livewire\Attributes\On('bar')] class ReceivesMultipleEventsUsingMultipleUserlandRefreshAttributes extends Component { public static $counter = 0; public function render() { static::$counter++; return '<div></div>'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEvents/SupportEvents.php
src/Features/SupportEvents/SupportEvents.php
<?php namespace Livewire\Features\SupportEvents; use function Livewire\wrap; use function Livewire\store; use function Livewire\invade; use Livewire\Features\SupportAttributes\AttributeLevel; use Livewire\ComponentHook; use Livewire\Exceptions\EventHandlerDoesNotExist; use Livewire\Mechanisms\HandleComponents\BaseRenderless; class SupportEvents extends ComponentHook { function call($method, $params, $returnEarly) { if ($method === '__dispatch') { [$name, $params] = $params; $names = static::getListenerEventNames($this->component); if (! in_array($name, $names)) { throw new EventHandlerDoesNotExist($name); } $method = static::getListenerMethodName($this->component, $name); $returnEarly( wrap($this->component)->$method(...$params) ); // Here we have to manually check to see if the event listener method // is "renderless" as it's normal "call" hook doesn't get run when // the method is called as an event listener... $isRenderless = $this->component->getAttributes() ->filter(fn ($i) => is_subclass_of($i, BaseRenderless::class)) ->filter(fn ($i) => $i->getName() === $method) ->filter(fn ($i) => $i->getLevel() === AttributeLevel::METHOD) ->count() > 0; if ($isRenderless) $this->component->skipRender(); } } function dehydrate($context) { if ($context->mounting) { $listeners = static::getListenerEventNames($this->component); $listeners && $context->addEffect('listeners', $listeners); } $dispatches = $this->getServerDispatchedEvents($this->component); $dispatches && $context->addEffect('dispatches', $dispatches); } static function getListenerEventNames($component) { $listeners = static::getComponentListeners($component); return collect($listeners) ->map(fn ($value, $key) => is_numeric($key) ? $value : $key) ->values() ->toArray(); } static function getListenerMethodName($component, $name) { $listeners = static::getComponentListeners($component); foreach ($listeners as $event => $method) { if (is_numeric($event)) $event = $method; if ($name === $event) return $method; } throw new \Exception('Event method not found'); } static function getComponentListeners($component) { $fromClass = invade($component)->getListeners(); $fromAttributes = store($component)->get('listenersFromAttributes', []); $listeners = array_merge($fromClass, $fromAttributes); return static::replaceDynamicEventNamePlaceholders($listeners, $component); } function getServerDispatchedEvents($component) { return collect(store($component)->get('dispatched', [])) ->map(fn ($event) => $event->serialize()) ->toArray(); } static function replaceDynamicEventNamePlaceholders($listeners, $component) { foreach ($listeners as $event => $method) { if (is_numeric($event)) continue; $replaced = static::replaceDynamicPlaceholders($event, $component); unset($listeners[$event]); $listeners[$replaced] = $method; } return $listeners; } static function replaceDynamicPlaceholders($event, $component) { return preg_replace_callback('/\{(.*)\}/U', function ($matches) use ($component) { return data_get($component, $matches[1], function () use ($matches) { throw new \Exception('Unable to evaluate dynamic event name placeholder: '.$matches[0]); }); }, $event); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEvents/Event.php
src/Features/SupportEvents/Event.php
<?php namespace Livewire\Features\SupportEvents; class Event { protected $name; protected $ref; protected $params; protected $self; protected $component; protected $el; public function __construct($name, $params) { $this->name = $name; if (isset($params['ref'])) { $this->ref($params['ref']); unset($params['ref']); } if (isset($params['component'])) { $this->component($params['component']); unset($params['component']); } if (isset($params['el'])) { $this->el($params['el']); unset($params['el']); } if (isset($params['self'])) { $this->self(); unset($params['self']); } // Handle legacy 'to' parameter for backward compatibility if (isset($params['to'])) { $this->component($params['to']); unset($params['to']); } $this->params = $params; } public function self() { $this->self = true; return $this; } public function component($name) { $this->component = $name; return $this; } public function ref($ref) { $this->ref = $ref; return $this; } public function el($selector) { $this->el = $selector; return $this; } public function to($component = null, $ref = null, $el = null, $self = null) { if ($self) { return $this->self(); } if ($ref) { return $this->ref($ref); } if ($el) { return $this->el($el); } return $this->component($component); } public function serialize() { $output = [ 'name' => $this->name, 'params' => $this->params, ]; if ($this->self) $output['self'] = true; if ($this->component) $output['component'] = app('livewire.factory')->resolveComponentName($this->component); if ($this->ref) $output['ref'] = $this->ref; if ($this->el) $output['el'] = $this->el; return $output; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEvents/HandlesEvents.php
src/Features/SupportEvents/HandlesEvents.php
<?php namespace Livewire\Features\SupportEvents; use function Livewire\store; trait HandlesEvents { protected $listeners = []; protected function getListeners() { return $this->listeners; } public function dispatch($event, ...$params) { $event = new Event($event, $params); store($this)->push('dispatched', $event); return $event; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEntangle/BrowserTest.php
src/Features/SupportEntangle/BrowserTest.php
<?php namespace Livewire\Features\SupportEntangle; use Livewire\Component; use Livewire\Livewire; use Tests\BrowserTestCase; class BrowserTest extends BrowserTestCase { public function test_can_persist_entangled_data() { Livewire::visit(new class extends Component { public $input; public function render() { return <<<'BLADE' <div> <div x-data="{ value: $persist(@entangle('input')) }"> <input dusk="input" x-model="value" /> </div> </div> BLADE; } }) ->type('@input', 'Hello World') ->assertScript('localStorage.getItem("_x_value") == \'"Hello World"\'') ->tap(fn ($b) => $b->refresh()) ->assertScript("localStorage.getItem('_x_value')", '"Hello World"') ; } public function test_is_not_live_by_default() { Livewire::visit(new class extends Component { public $foo = 'foo'; function render() { return <<<'HTML' <div> <div x-data="{ state: $wire.$entangle('foo') }"> <button dusk="set" x-on:click="state = 'bar'" type="button"> Set to bar </button> </div> <div dusk="state">{{ $foo }}</div> <button dusk="refresh" x-on:click="$wire.$refresh()" type="button"> Refresh </button> </div> HTML; } }) ->assertSeeIn('@state', 'foo') ->waitForNoLivewire()->click('@set') ->assertSeeIn('@state', 'foo') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@state', 'bar'); } public function test_can_be_forced_to_not_be_live() { Livewire::visit(new class extends Component { public $foo = 'foo'; function render() { return <<<'HTML' <div> <div x-data="{ state: $wire.$entangle('foo', false) }"> <button dusk="set" x-on:click="state = 'bar'" type="button"> Set to bar </button> </div> <div dusk="state">{{ $foo }}</div> <button dusk="refresh" x-on:click="$wire.$refresh()" type="button"> Refresh </button> </div> HTML; } }) ->assertSeeIn('@state', 'foo') ->waitForNoLivewire()->click('@set') ->assertSeeIn('@state', 'foo') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@state', 'bar'); } public function test_can_be_live() { Livewire::visit(new class extends Component { public $foo = 'foo'; function render() { return <<<'HTML' <div> <div x-data="{ state: $wire.$entangle('foo', true) }"> <button dusk="set" x-on:click="state = 'bar'" type="button"> Set to bar </button> </div> <div dusk="state">{{ $foo }}</div> </div> HTML; } }) ->assertSeeIn('@state', 'foo') ->waitForLivewire()->click('@set') ->assertSeeIn('@state', 'bar'); } public function test_can_remove_entangled_components_from_dom_without_side_effects() { Livewire::visit(new class extends Component { public $items = []; public function add() { $this->items[] = [ 'value' => null, ]; } public function remove($key) { unset($this->items[$key]); } function render() { return <<<'HTML' <div> <ul> @foreach ($items as $itemKey => $item) <li dusk="item{{ $itemKey }}" wire:key="{{ $itemKey }}"> <div x-data="{ value: $wire.entangle('items.{{ $itemKey }}.value') }"></div> {{ $itemKey }} <button type="button" dusk="remove{{ $itemKey }}" wire:click="remove('{{ $itemKey }}')"> Remove </button> </li> @endforeach </ul> <button dusk="add" type="button" wire:click="add"> Add </button> <div dusk="json"> {{ json_encode($items) }} </div> </div> HTML; } }) ->assertSeeIn('@json', '[]') ->waitForLivewire()->click('@add') ->assertSeeIn('@item0', '0') ->waitForLivewire()->click('@add') ->assertSeeIn('@item1', '1') ->waitForLivewire()->click('@add') ->assertSeeIn('@item2', '2') ->waitForLivewire()->click('@add') ->assertSeeIn('@item3', '3') ->waitForLivewire()->click('@remove3') ->assertPresent('@item0') ->assertPresent('@item1') ->assertPresent('@item2') ->assertMissing('@item3') ->waitForLivewire()->click('@remove2') ->assertPresent('@item0') ->assertPresent('@item1') ->assertMissing('@item2') ->assertMissing('@item3') ->waitForLivewire()->click('@remove1') ->assertPresent('@item0') ->assertMissing('@item1') ->assertMissing('@item2') ->assertMissing('@item3') ->waitForLivewire()->click('@remove0') ->assertMissing('@item0') ->assertMissing('@item1') ->assertMissing('@item2') ->assertMissing('@item3'); } public function test_can_remove_dollar_sign_entangled_components_from_dom_without_side_effects() { Livewire::visit(new class extends Component { public $items = []; public function add() { $this->items[] = [ 'value' => null, ]; } public function remove($key) { unset($this->items[$key]); } function render() { return <<<'HTML' <div> <ul> @foreach ($items as $itemKey => $item) <li dusk="item{{ $itemKey }}" wire:key="{{ $itemKey }}"> <div x-data="{ value: $wire.$entangle('items.{{ $itemKey }}.value') }"></div> {{ $itemKey }} <button type="button" dusk="remove{{ $itemKey }}" wire:click="remove('{{ $itemKey }}')"> Remove </button> </li> @endforeach </ul> <button dusk="add" type="button" wire:click="add"> Add </button> <div dusk="json"> {{ json_encode($items) }} </div> </div> HTML; } }) ->assertSeeIn('@json', '[]') ->waitForLivewire()->click('@add') ->assertSeeIn('@item0', '0') ->waitForLivewire()->click('@add') ->assertSeeIn('@item1', '1') ->waitForLivewire()->click('@add') ->assertSeeIn('@item2', '2') ->waitForLivewire()->click('@add') ->assertSeeIn('@item3', '3') ->waitForLivewire()->click('@remove3') ->assertPresent('@item0') ->assertPresent('@item1') ->assertPresent('@item2') ->assertMissing('@item3') ->waitForLivewire()->click('@remove2') ->assertPresent('@item0') ->assertPresent('@item1') ->assertMissing('@item2') ->assertMissing('@item3') ->waitForLivewire()->click('@remove1') ->assertPresent('@item0') ->assertMissing('@item1') ->assertMissing('@item2') ->assertMissing('@item3') ->waitForLivewire()->click('@remove0') ->assertMissing('@item0') ->assertMissing('@item1') ->assertMissing('@item2') ->assertMissing('@item3'); } public function test_can_removed_nested_items_without_multiple_requests_when_entangled_items_are_present() { Livewire::visit(new class extends Component { public $components = []; public $filters = [ 'name' => 'bob', 'phone' => '123', 'address' => 'street', ]; public $counter = 0; public function boot() { $this->counter++; } public function removeFilter($filter) { $this->filters[$filter] = null; } public function addBackFiltersWithEntangled() { $this->filters = [ 'name' => 'bob', 'phone' => '123', 'address' => 'street', 'entangled' => 'hello world', // This filter will be entangled, ]; } public function addBackFiltersWithoutEntangled() { // Add back the same non entangled filters to show that // removing/adding non entangled items is not the issue. $this->filters = [ 'name' => 'bob', 'phone' => '123', 'address' => 'street', ]; } function render() { return <<<'HTML' <div> <div>Page</div> <div dusk="counter">Boot counter: {{ $counter }}</div> @foreach ($filters as $filter => $value) @if ($filter === 'entangled') <div x-data="{ value: $wire.entangle('filters.{{ $filter }}') }"> <span x-text="'Entangled: ' + value" ></span> </div> <div> <button dusk="remove-{{ $filter }}" wire:click="removeFilter('{{ $filter }}')">Remove {{ $filter }}</button> </div> @else <div> Normal: {{ $value }} </div> <div> <button dusk="remove-{{ $filter }}" wire:click="removeFilter('{{ $filter }}')">Remove {{ $filter }}</button> </div> @endif @endforeach <button dusk="add-entangled-filter" wire:click="addEntangledFilter()">Add entangled filter</button> <button dusk="add-back-filters-without-entangled" wire:click="addBackFiltersWithoutEntangled()">Add back filters without entangled</button> <button dusk="add-back-filters-with-entangled" wire:click="addBackFiltersWithEntangled()">Add back filters with entangled</button> </div> HTML; } }) ->assertSeeIn('@counter', '1') ->waitForLivewire()->click('@remove-name') ->assertSeeIn('@counter', '2') ->waitForLivewire()->click('@remove-phone') ->assertSeeIn('@counter', '3') ->waitForLivewire()->click('@remove-address') ->assertSeeIn('@counter', '4') ->waitForLivewire()->click('@add-back-filters-without-entangled') ->assertSeeIn('@counter', '5') ->waitForLivewire()->click('@remove-name') ->assertSeeIn('@counter', '6') ->waitForLivewire()->click('@remove-phone') ->assertSeeIn('@counter', '7') ->waitForLivewire()->click('@remove-address') ->assertSeeIn('@counter', '8') ->waitForLivewire()->click('@add-back-filters-with-entangled') ->assertSeeIn('@counter', '9') ->waitForLivewire()->click('@remove-name') ->assertSeeIn('@counter', '10') // This test will fail here since there will be duplicate requests ->waitForLivewire()->click('@remove-phone') ->assertSeeIn('@counter', '11') ->waitForLivewire()->click('@remove-address') ->assertSeeIn('@counter', '12') ->waitForLivewire()->click('@remove-entangled') ->assertSeeIn('@counter', '13'); } public function test_can_reorder_entangled_keys() { Livewire::visit(new class extends Component { public $test = [ 'one' => 'One', 'two' => 'Two', 'three' => 'Three', ]; function render() { return <<<'HTML' <div> <div dusk="output">Test: {{ json_encode($test) }}</div> <div> <button dusk="set" wire:click="$set('test', { one: 'One', three: 'Three', two: 'Two' })" type="button"> Set test to {"one":"One","three":"Three","two":"Two"} </button> </div> <div> <button dusk="set-add" wire:click="$set('test', { one: 'One', three: 'Three', two: 'Two', four: 'Four' })" type="button"> Set test to {"one":"One","three":"Three","two":"Two","four":"Four"} </button> </div> <!-- This is meant to fail for now... We're only tackling key preservance for $wire.$set()... --> <!-- <div x-data="{ test: $wire.entangle('test', true) }"> <div> <button dusk="set-alpine" x-on:click="test = { one: 'One', three: 'Three', two: 'Two' }" type="button"> Set test to {"one":"One","three":"Three","two":"Two"} with Alpine </button> </div> <div> <button dusk="set-add-alpine" x-on:click="test = { one: 'One', three: 'Three', two: 'Two', four: 'Four' }" type="button"> Set test to {"one":"One","three":"Three","two":"Two","four":"Four"} with Alpine </button> </div> </div> --> </div> HTML; } }) ->assertSeeIn('@output', json_encode(['one' => 'One', 'two' => 'Two', 'three' => 'Three'])) ->waitForLivewire()->click('@set') ->assertSeeIn('@output', json_encode(['one' => 'One', 'three' => 'Three', 'two' => 'Two'])) ->waitForLivewire()->click('@set-add') ->assertSeeIn('@output', json_encode(['one' => 'One', 'three' => 'Three', 'two' => 'Two', 'four' => 'Four'])) // This is meant to fail for now... We're only tackling key preservance for $wire.$set()... // ->waitForLivewire()->click('@set-alpine') // ->assertSeeIn('@output', json_encode(['one' => 'One', 'three' => 'Three', 'two' => 'Two'])) // ->waitForLivewire()->click('@set-add-alpine') // ->assertSeeIn('@output', json_encode(['one' => 'One', 'three' => 'Three', 'two' => 'Two', 'four' => 'Four'])); ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEntangle/UnitTest.php
src/Features/SupportEntangle/UnitTest.php
<?php namespace Livewire\Features\SupportEntangle; class UnitTest extends \Tests\TestCase { public function test_can_() { $this->assertTrue(true); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportEntangle/SupportEntangle.php
src/Features/SupportEntangle/SupportEntangle.php
<?php namespace Livewire\Features\SupportEntangle; use Livewire\ComponentHook; use Illuminate\Support\Facades\Blade; class SupportEntangle extends ComponentHook { public static function provide() { Blade::directive('entangle', function ($expression) { return <<<EOT <?php if ((object) ({$expression}) instanceof \Livewire\WireDirective) : ?>window.Livewire.find('{{ \$__livewire->getId() }}').entangle('{{ {$expression}->value() }}'){{ {$expression}->hasModifier('live') ? '.live' : '' }}<?php else : ?>window.Livewire.find('{{ \$__livewire->getId() }}').entangle('{{ {$expression} }}')<?php endif; ?> EOT; }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportStreaming/HandlesStreaming.php
src/Features/SupportStreaming/HandlesStreaming.php
<?php namespace Livewire\Features\SupportStreaming; use Livewire\ComponentHookRegistry; trait HandlesStreaming { function stream($content = null, $replace = false, $name = null, $el = null, $ref = null, $to = null) { // Handle legacy 'to' parameter for backward compatibility... if ($to) $name = $to; $hook = ComponentHookRegistry::getHook($this, SupportStreaming::class); $stream = new StreamManager($this, $hook); if (! $content) { return $stream; } if (! $el && ! $ref && ! $name) { return $stream->content($content, $replace); } return $stream->content($content, $replace)->to($name, $el, $ref); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportStreaming/StreamManager.php
src/Features/SupportStreaming/StreamManager.php
<?php namespace Livewire\Features\SupportStreaming; class StreamManager { protected $component; protected $hook; protected $name; protected $el; protected $ref; protected $content; protected $replace; public function __construct($component, $hook) { $this->component = $component; $this->hook = $hook; } public function content($content, $replace = false) { $this->content = $content; $this->replace = $replace; return $this; } public function to($name = null, $el = null, $ref = null) { $this->name = $name; $this->el = $el; $this->ref = $ref; $this->hook->stream($this->content, $this->replace, $this->name, $this->el, $this->ref); return $this; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportStreaming/SupportStreaming.php
src/Features/SupportStreaming/SupportStreaming.php
<?php namespace Livewire\Features\SupportStreaming; use Livewire\ComponentHook; class SupportStreaming extends ComponentHook { protected static $response; public function stream($content, $replace = false, $name = null, $el = null, $ref = null) { static::ensureStreamResponseStarted(); $hasName = $name !== null; $hasEl = $el !== null; $hasRef = $ref !== null; $type = match (true) { $hasName => 'directive', $hasEl => 'element', $hasRef => 'ref', }; static::streamContent([ 'id' => $this->component->getId(), 'type' => $type, 'content' => $content, 'mode' => $replace ? 'replace' : 'default', 'name' => $name, 'el' => $el, 'ref' => $ref, ]); } public static function ensureStreamResponseStarted() { if (static::$response) return; static::$response = response()->stream(fn () => null , 200, [ 'Cache-Control' => 'no-cache', 'Content-Type' => 'text/event-stream', 'X-Accel-Buffering' => 'no', 'X-Livewire-Stream' => true, ]); static::$response->sendHeaders(); } public static function streamContent($body) { echo json_encode(['stream' => true, 'body' => $body, 'endStream' => true]); if (ob_get_level() > 0) { ob_flush(); } flush(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportHtmlAttributeForwarding/BrowserTest.php
src/Features/SupportHtmlAttributeForwarding/BrowserTest.php
<?php namespace Livewire\Features\SupportHtmlAttributeForwarding; use Tests\BrowserTestCase; use Livewire\Livewire; use Livewire\Component; class BrowserTest extends BrowserTestCase { public function test_html_attributes_are_forwarded_to_component() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <h1>Parent Component</h1> <livewire:alert type="error" class="mb-4" id="error-alert" data-testid="my-alert" dusk="alert-component" wire:sort:item="1" > Something went wrong! </livewire:alert> </div> HTML; } }, 'alert' => new class extends Component { public string $type = 'info'; public function render() { return <<<'HTML' <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}> {{ $slot }} <button type="button" wire:click="$refresh" dusk="refresh">Refresh</button> </div> HTML; } } ]) ->assertSeeIn('@alert-component', 'Something went wrong!') ->assertAttribute('@alert-component', 'class', 'alert alert-error mb-4') ->assertAttribute('@alert-component', 'id', 'error-alert') ->assertAttribute('@alert-component', 'data-testid', 'my-alert') ->assertAttribute('@alert-component', 'wire:sort:item', '1') ->waitForLivewire()->click('@refresh') ->assertAttribute('@alert-component', 'class', 'alert alert-error mb-4') ->assertAttribute('@alert-component', 'id', 'error-alert') ->assertAttribute('@alert-component', 'data-testid', 'my-alert') ->assertAttribute('@alert-component', 'wire:sort:item', '1'); } public function test_html_attributes_are_forwarded_to_a_lazy_component() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div dusk="parent-component"> <h1>Parent Component</h1> <livewire:alert type="error" class="mb-4" id="error-alert" data-testid="my-alert" dusk="alert-component" wire:sort:item="1" lazy > Something went wrong! </livewire:alert> </div> HTML; } }, 'alert' => new class extends Component { public string $type = 'info'; public function mount() { usleep(200 * 1000); // 200ms } public function render() { return <<<'HTML' <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}> <h2>Alert Component</h2> {{ $slot }} <button type="button" wire:click="$refresh" dusk="refresh">Refresh</button> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertDontSee('Alert Component') ->assertAttribute('@parent-component > div', 'class', '') ->assertAttribute('@parent-component > div', 'id', '') ->assertAttributeMissing('@parent-component > div', 'data-testid') ->assertAttributeMissing('@parent-component > div', 'wire:sort:item') ->waitForText('Alert Component') // Wait for the lazy component to load ->assertAttribute('@parent-component > div', 'class', 'alert alert-error mb-4') ->assertAttribute('@parent-component > div', 'id', 'error-alert') ->assertAttribute('@parent-component > div', 'data-testid', 'my-alert') ->assertAttribute('@parent-component > div', 'wire:sort:item', '1') ->waitForLivewire()->click('@refresh') ->assertAttribute('@parent-component > div', 'class', 'alert alert-error mb-4') ->assertAttribute('@parent-component > div', 'id', 'error-alert') ->assertAttribute('@parent-component > div', 'data-testid', 'my-alert') ->assertAttribute('@parent-component > div', 'wire:sort:item', '1'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportHtmlAttributeForwarding/UnitTest.php
src/Features/SupportHtmlAttributeForwarding/UnitTest.php
<?php namespace Livewire\Features\SupportHtmlAttributeForwarding; use Tests\TestCase; use Livewire\Livewire; use Livewire\Component; class UnitTest extends TestCase { public function test_html_attributes_are_forwarded_to_component() { Livewire::test([ new class extends Component { public function render() { return <<<'HTML' <div> <!-- ... --> <livewire:alert type="error" class="mb-4" id="error-alert" data-testid="my-alert" /> </div> HTML; } }, 'alert' => new class extends Component { public string $type = 'info'; public function render() { return <<<'HTML' <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}> <!-- ... --> </div> HTML; } } ]) ->assertDontSeeHtml('type="error"') ->assertSeeHtml('class="alert alert-error mb-4"') ->assertSeeHtml('id="error-alert"') ->assertSeeHtml('data-testid="my-alert"') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php
src/Features/SupportHtmlAttributeForwarding/HandlesHtmlAttributeForwarding.php
<?php namespace Livewire\Features\SupportHtmlAttributeForwarding; trait HandlesHtmlAttributeForwarding { protected array $htmlAttributes = []; public function withHtmlAttributes(array $attributes): self { $this->htmlAttributes = $attributes; return $this; } public function getHtmlAttributes(): array { return $this->htmlAttributes; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php
src/Features/SupportHtmlAttributeForwarding/SupportHtmlAttributeForwarding.php
<?php namespace Livewire\Features\SupportHtmlAttributeForwarding; use Livewire\ComponentHook; use Illuminate\View\ComponentAttributeBag; class SupportHtmlAttributeForwarding extends ComponentHook { public function render($view, $properties) { $attributes = $this->component->getHtmlAttributes(); $view->with(['attributes' => new ComponentAttributeBag($attributes)]); } public function renderIsland($name, $view, $properties) { $attributes = $this->component->getHtmlAttributes(); $view->with(['attributes' => new ComponentAttributeBag($attributes)]); } function hydrate($memo) { $attributes = $memo['attributes'] ?? []; if (! empty($attributes)) { $this->component->withHtmlAttributes($attributes); } } public function dehydrate($context) { $attributes = $this->component->getHtmlAttributes(); if (! empty($attributes)) { $context->addMemo('attributes', $attributes); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportComputed/BaseComputed.php
src/Features/SupportComputed/BaseComputed.php
<?php namespace Livewire\Features\SupportComputed; use function Livewire\invade; use function Livewire\on; use function Livewire\off; use Livewire\Features\SupportAttributes\Attribute; use Illuminate\Support\Facades\Cache; #[\Attribute] class BaseComputed extends Attribute { protected $requestCachedValue; function __construct( public $persist = false, public $seconds = 3600, // 1 hour... public $cache = false, public $key = null, public $tags = null, ) {} function boot() { off('__get', $this->handleMagicGet(...)); on('__get', $this->handleMagicGet(...)); off('__unset', $this->handleMagicUnset(...)); on('__unset', $this->handleMagicUnset(...)); } function call() { throw new CannotCallComputedDirectlyException( $this->component->getName(), $this->getName(), ); } protected function handleMagicGet($target, $property, $returnValue) { if ($target !== $this->component) return; if ($this->generatePropertyName($property) !== $this->getName()) return; if ($this->persist) { $returnValue($this->handlePersistedGet()); return; } if ($this->cache) { $returnValue($this->handleCachedGet()); return; } $returnValue( $this->requestCachedValue ??= $this->evaluateComputed() ); } protected function handleMagicUnset($target, $property) { if ($target !== $this->component) return; if ($property !== $this->getName()) return; if ($this->persist) { $this->handlePersistedUnset(); return; } if ($this->cache) { $this->handleCachedUnset(); return; } unset($this->requestCachedValue); } protected function handlePersistedGet() { $key = $this->generatePersistedKey(); $closure = fn () => $this->evaluateComputed(); return match(Cache::supportsTags() && !empty($this->tags)) { true => Cache::tags($this->tags)->remember($key, $this->seconds, $closure), default => Cache::remember($key, $this->seconds, $closure) }; } protected function handleCachedGet() { $key = $this->generateCachedKey(); $closure = fn () => $this->evaluateComputed(); return match(Cache::supportsTags() && !empty($this->tags)) { true => Cache::tags($this->tags)->remember($key, $this->seconds, $closure), default => Cache::remember($key, $this->seconds, $closure) }; } protected function handlePersistedUnset() { $key = $this->generatePersistedKey(); Cache::forget($key); } protected function handleCachedUnset() { $key = $this->generateCachedKey(); Cache::forget($key); } protected function generatePersistedKey() { if ($this->key) return $this->key; return 'lw_computed.'.$this->component->getId().'.'.$this->getName(); } protected function generateCachedKey() { if ($this->key) return $this->key; return 'lw_computed.'.$this->component->getName().'.'.$this->getName(); } protected function evaluateComputed() { return invade($this->component)->{parent::getName()}(); } public function getName() { return $this->generatePropertyName(parent::getName()); } private function generatePropertyName($value) { return str($value)->camel()->toString(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportComputed/CannotCallComputedDirectlyException.php
src/Features/SupportComputed/CannotCallComputedDirectlyException.php
<?php namespace Livewire\Features\SupportComputed; use Exception; class CannotCallComputedDirectlyException extends Exception { function __construct($componentName, $methodName) { parent::__construct( "Cannot call [{$methodName}()] computed property method directly on component: {$componentName}" ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportComputed/BrowserTest.php
src/Features/SupportComputed/BrowserTest.php
<?php namespace Livewire\Features\SupportComputed; use Livewire\Attributes\Computed; use Livewire\Component; use Livewire\Livewire; use Tests\BrowserTestCase; class BrowserTest extends BrowserTestCase { public function test_can_persist_computed_between_requests_and_bust_them() { Livewire::visit(new class extends Component { public $count = 0; protected $thing = 'hey'; #[Computed(persist: true)] public function foo() { $this->count++; return 'bar'; } function unset() { unset($this->foo); } function render() { $noop = $this->foo; return <<<'HTML' <div> <button wire:click="$refresh" dusk="refresh">refresh</button> <button wire:click="unset" dusk="unset">unset</button> <div dusk="count">{{ $count }}</div> </div> HTML; } }) ->assertSeeIn('@count', '1') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@count', '1') ->waitForLivewire()->click('@unset') ->assertSeeIn('@count', '2') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@count', '2'); } public function test_can_cache_computed_properties_for_all_components_and_bust_them() { Livewire::visit(new class extends Component { public $count = 0; #[Computed(cache: true)] public function foo() { return $this->count; } function increment() { $this->count++; unset($this->foo); } function render() { $noop = $this->foo; return <<<'HTML' <div> <button wire:click="$refresh" dusk="refresh">refresh</button> <button wire:click="increment" dusk="increment">unset</button> <div dusk="count">{{ $this->foo }}</div> </div> HTML; } }) ->assertSeeIn('@count', '0') ->waitForLivewire()->click('@increment') ->assertSeeIn('@count', '1') ->refresh() ->assertSeeIn('@count', '1'); } public function test_computed_properties_cannot_be_set_on_front_end() { Livewire::visit(new class extends Component { public $count = 0; #[Computed] public function foo() { return 'bar'; } function render() { return <<<'HTML' <div> <p>Foo: <span dusk="foo">{{ $this->foo }}</span></p> <button wire:click="$set('foo', 'other')" dusk="change-foo">Change Foo</button> </div> HTML; } }) ->assertSeeIn('@foo', 'bar') ->waitForLivewire()->click('@change-foo') ->assertSeeIn('@foo', 'bar') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportComputed/UnitTest.php
src/Features/SupportComputed/UnitTest.php
<?php namespace Livewire\Features\SupportComputed; use Illuminate\Support\Facades\Cache; use Tests\TestComponent; use Tests\TestCase; use Livewire\Livewire; use Livewire\Component; use Livewire\Attributes\Computed; use Livewire\Features\SupportEvents\BaseOn; class UnitTest extends TestCase { function test_can_make_method_a_computed() { Livewire::test(new class extends TestComponent { #[Computed] function foo() { return 'bar'; } }) ->assertSetStrict('foo', 'bar'); } function test_can_access_computed_properties_inside_views() { Livewire::test(new class extends TestComponent { #[Computed] function foo() { return 'bar'; } function render() { return <<<'HTML' <div>foo{{ $this->foo }}</div> HTML; } }) ->assertSee('foobar'); } function test_computed_properties_only_get_accessed_once_per_request() { Livewire::test(new class extends TestComponent { public $count = 0; #[Computed] function foo() { $this->count++; return 'bar'; } function render() { $noop = $this->foo; $noop = $this->foo; $noop = $this->foo; return <<<'HTML' <div>foo{{ $this->foo }}</div> HTML; } }) ->assertSee('foobar') ->assertSetStrict('count', 1) ->call('$refresh') ->assertSetStrict('count', 2); } function test_can_bust_computed_cache_using_unset() { Livewire::test(new class extends TestComponent { public $count = 0; #[Computed] function foo() { $this->count++; return 'bar'; } function render() { $noop = $this->foo; unset($this->foo); $noop = $this->foo; return <<<'HTML' <div>foo{{ $this->foo }}</div> HTML; } }) ->assertSee('foobar') ->assertSetStrict('count', 2) ->call('$refresh') ->assertSetStrict('count', 4); } function test_can_tag_cached_computed_property() { // need to set a cache driver, which can handle tags Cache::setDefaultDriver('array'); Livewire::test(new class extends TestComponent { public $count = 0; #[Computed(cache: true, tags: ['foo'])] function foo() { $this->count++; return 'bar'; } function deleteCachedTags() { if (Cache::supportsTags()) { Cache::tags(['foo'])->flush(); } } function render() { $noop = $this->foo; return <<<'HTML' <div>foo{{ $this->foo }}</div> HTML; } }) ->assertSee('foobar') ->call('$refresh') ->assertSetStrict('count', 1) ->call('deleteCachedTags') ->assertSetStrict('count', 2); } function test_can_tag_persisten_computed_property() { // need to set a cache driver, which can handle tags Cache::setDefaultDriver('array'); Livewire::test(new class extends TestComponent { public $count = 0; #[Computed(persist: true, tags: ['foo'])] function foo() { $this->count++; return 'bar'; } function deleteCachedTags() { if (Cache::supportsTags()) { Cache::tags(['foo'])->flush(); } } function render() { $noop = $this->foo; return <<<'HTML' <div>foo{{ $this->foo }}</div> HTML; } }) ->assertSee('foobar') ->call('$refresh') ->assertSetStrict('count', 1) ->call('deleteCachedTags') ->assertSetStrict('count', 2); } function test_can_tag_persisted_computed_with_custom_key_property() { Cache::setDefaultDriver('array'); Livewire::test(new class extends TestComponent { public $count = 0; #[Computed(persist: true, key: 'baz')] function foo() { $this->count++; return 'bar'; } function render() { $noop = $this->foo; return <<<'HTML' <div>foo{{ $this->foo }}</div> HTML; } }) ->assertSee('foobar') ->call('$refresh') ->assertSetStrict('count', 1); $this->assertTrue(Cache::has('baz')); } function test_cant_call_a_computed_directly() { $this->expectException(CannotCallComputedDirectlyException::class); Livewire::test(new class extends TestComponent { #[Computed] function foo() { return 'bar'; } function render() { return <<<'HTML' <div>foo{{ $this->foo }}</div> HTML; } }) ->assertSee('foobar') ->call('foo'); } function test_can_use_multiple_computed_properties_for_different_properties() { Livewire::test(new class extends TestComponent { public $count = 0; #[Computed] function foo() { $this->count++; return 'bar'; } #[Computed] function bob() { $this->count++; return 'lob'; } function render() { $noop = $this->foo; $noop = $this->foo; $noop = $this->bob; $noop = $this->bob; return <<<'HTML' <div> <div>foo{{ $this->foo }}</div> <div>bob{{ $this->bob }}</div> </div> HTML; } }) ->assertSee('foobar') ->assertSee('boblob') ->assertSetStrict('count', 2) ->call('$refresh') ->assertSetStrict('count', 4); } function test_parses_computed_properties() { $this->assertEquals( ['foo' => 'bar', 'bar' => 'baz', 'bobLobLaw' => 'blog'], SupportLegacyComputedPropertySyntax::getComputedProperties(new class { public function getFooProperty() { return 'bar'; } public function getBarProperty() { return 'baz'; } public function getBobLobLawProperty() { return 'blog'; } }) ); } function test_computed_property_is_accessible_using_snake_case() { Livewire::test(new class extends TestComponent { public $upperCasedFoo = 'FOO_BAR'; #[Computed] public function fooBar() { return strtolower($this->upperCasedFoo); } public function render() { return <<<'HTML' <div> {{ var_dump($this->foo_bar) }} </div> HTML; } }) ->assertSee('foo_bar'); } function test_computed_property_is_accessible_when_using_snake_case_or_camel_case_in_the_method_name_in_the_class() { Livewire::test(new class extends TestComponent { public $upperCasedFoo = 'FOO_BAR'; #[Computed] public function foo_bar_snake_case_in_component_class() { return strtolower($this->upperCasedFoo); } #[Computed] public function fooBarCamelCaseInComponentClass() { return strtolower($this->upperCasedFoo); } public function render() { return <<<'HTML' <div> <!-- Snake Case in Component Class --> snake_case_in_component_class_{{ $this->foo_bar_snake_case_in_component_class }} <!-- Camel Case in Blade View --> camelCaseInBladeView_snake_case_method_{{ $this->fooBarCamelCaseInComponentClass }} <!-- Camel Case in Component Class --> camel_case_in_component_class_{{ $this->foo_bar_camel_case_in_component_class }} <!-- Camel Case in Blade View --> camelCaseInBladeView_camel_case_method_{{ $this->fooBarCamelCaseInComponentClass }} </div> HTML; } }) ->assertSeeInOrder([ 'snake_case_in_component_class_foo_bar', 'camelCaseInBladeView_snake_case_method_foo_bar', 'camel_case_in_component_class_foo_bar', 'camelCaseInBladeView_camel_case_method_foo_bar' ]); } public function test_computed_property_is_accessable_within_blade_view() { Livewire::test(ComputedPropertyStub::class) ->assertSee('foo'); } public function test_injected_computed_property_is_accessable_within_blade_view() { Livewire::test(InjectedComputedPropertyStub::class) ->assertSee('bar'); } public function test_computed_property_is_memoized_after_its_accessed() { Livewire::test(MemoizedComputedPropertyStub::class) ->assertSee('int(2)'); } public function test_isset_is_true_on_existing_computed_property() { Livewire::test(IssetComputedPropertyStub::class) ->assertSee('true'); } public function test_isset_is_false_on_non_existing_computed_property() { Livewire::test(FalseIssetComputedPropertyStub::class) ->assertSee('false'); } public function test_isset_is_false_on_null_computed_property() { Livewire::test(NullIssetComputedPropertyStub::class) ->assertSee('false'); } public function test_it_supports_legacy_computed_properties() { Livewire::test(new class extends TestComponent { public function getFooProperty() { return 'bar'; } }) ->assertSetStrict('foo', 'bar'); } public function test_it_supports_unsetting_legacy_computed_properties() { Livewire::test(new class extends TestComponent { public $changeFoo = false; public function getFooProperty() { return $this->changeFoo ? 'baz' : 'bar'; } public function save() { // Access foo to ensure it is memoized. $this->foo; $this->changeFoo = true; unset($this->foo); } }) ->assertSetStrict('foo', 'bar') ->call('save') ->assertSetStrict('foo', 'baz'); } public function test_it_supports_unsetting_legacy_computed_properties_for_events() { Livewire::test(new class extends TestComponent { public $changeFoo = false; public function getFooProperty() { return $this->changeFoo ? 'baz' : 'bar'; } #[BaseOn('bar')] public function onBar() { $this->changeFoo = true; unset($this->foo); } }) ->assertSetStrict('foo', 'bar') ->dispatch('bar', 'baz') ->assertSetStrict('foo', 'baz'); } } class ComputedPropertyStub extends Component { public $upperCasedFoo = 'FOO_BAR'; public function getFooBarProperty() { return strtolower($this->upperCasedFoo); } public function render() { return <<<'HTML' <div> {{ var_dump($this->foo_bar) }} </div> HTML; } } class FooDependency { public $baz = 'bar'; } class InjectedComputedPropertyStub extends Component { public function getFooBarProperty(FooDependency $foo) { return $foo->baz; } public function render() { return <<<'HTML' <div> {{ var_dump($this->foo_bar) }} </div> HTML; } } class MemoizedComputedPropertyStub extends Component { public $count = 1; public function getFooProperty() { return $this->count += 1; } public function render() { // Access foo once here to start the cache. $this->foo; return <<<'HTML' <div> {{ var_dump($this->foo) }} </div> HTML; } } class IssetComputedPropertyStub extends Component{ public $upperCasedFoo = 'FOO_BAR'; public function getFooBarProperty() { return strtolower($this->upperCasedFoo); } public function render() { return <<<'HTML' <div> {{ var_dump(isset($this->foo_bar)) }} </div> HTML; } } class FalseIssetComputedPropertyStub extends Component{ public $upperCasedFoo = 'FOO_BAR'; public function getFooBarProperty() { return strtolower($this->upperCasedFoo); } public function render() { return <<<'HTML' <div> {{ var_dump(isset($this->foo)) }} </div> HTML; } } class NullIssetComputedPropertyStub extends Component{ public $upperCasedFoo = 'FOO_BAR'; public function getFooProperty() { return null; } public function render() { return <<<'HTML' <div> {{ var_dump(isset($this->foo)) }} </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportComputed/SupportLegacyComputedPropertySyntax.php
src/Features/SupportComputed/SupportLegacyComputedPropertySyntax.php
<?php namespace Livewire\Features\SupportComputed; use Livewire\ComponentHook; use Livewire\Drawer\Utils as SyntheticUtils; use function Livewire\on; use function Livewire\store; use function Livewire\wrap; class SupportLegacyComputedPropertySyntax extends ComponentHook { protected static array $computedPropertyNamesCache = []; static function provide() { on('__get', function ($target, $property, $returnValue) { if (static::hasComputedProperty($target, $property)) { $returnValue(static::getComputedProperty($target, $property)); } }); on('__unset', function ($target, $property) { if (static::hasComputedProperty($target, $property)) { store($target)->unset('computedProperties', $property); } }); on('flush-state', function () { static::$computedPropertyNamesCache = []; }); } public static function getComputedProperties($target) { return collect(static::getComputedPropertyNames($target)) ->mapWithKeys(function ($property) use ($target) { return [$property => static::getComputedProperty($target, $property)]; }) ->all(); } public static function hasComputedProperty($target, $property) { return in_array((string) str($property)->camel(), static::getComputedPropertyNames($target), true); } public static function getComputedProperty($target, $property) { if (! static::hasComputedProperty($target, $property)) { throw new \Exception('No computed property found: $'.$property); } $method = 'get'.str($property)->studly().'Property'; store($target)->push( 'computedProperties', $value = store($target)->find('computedProperties', $property, fn() => wrap($target)->$method()), $property, ); return $value; } public static function getComputedPropertyNames($target) { $className = get_class($target); if (isset(static::$computedPropertyNamesCache[$className])) { return static::$computedPropertyNamesCache[$className]; } $methodNames = SyntheticUtils::getPublicMethodsDefinedBySubClass($target); $computedPropertyNames = collect($methodNames) ->filter(function ($method) { return str($method)->startsWith('get') && str($method)->endsWith('Property'); }) ->map(function ($method) { return (string) str($method)->between('get', 'Property')->camel(); }) ->all(); static::$computedPropertyNamesCache[$className] = $computedPropertyNames; return $computedPropertyNames; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/CannotBindToModelDataWithoutValidationRuleException.php
src/Features/SupportLegacyModels/CannotBindToModelDataWithoutValidationRuleException.php
<?php namespace Livewire\Features\SupportLegacyModels; use Livewire\Exceptions\BypassViewHandler; class CannotBindToModelDataWithoutValidationRuleException extends \Exception { use BypassViewHandler; public function __construct($key, $component) { parent::__construct( "Cannot bind property [$key] without a validation rule present in the [\$rules] array on Livewire component: [{$component}]." ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/EloquentModelSynth.php
src/Features/SupportLegacyModels/EloquentModelSynth.php
<?php namespace Livewire\Features\SupportLegacyModels; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Database\ClassMorphViolationException; use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Relation; class EloquentModelSynth extends Synth { public static $key = 'elmdl'; public static function match($target) { return $target instanceof Model; } public function dehydrate($target, $dehydrateChild) { $class = $target::class; try { // If no alias is found, this just returns the class name $alias = $target->getMorphClass(); } catch (ClassMorphViolationException $e) { // If the model is not using morph classes, this exception is thrown $alias = $class; } $meta = []; if ($target->exists) { $meta['key'] = $target->getKey(); } $meta['class'] = $alias; if ($target->getConnectionName() !== $class::make()->getConnectionName()) { $meta['connection'] = $target->getConnectionName(); } $relations = $target->getQueueableRelations(); if (count($relations)) { $meta['relations'] = $relations; } $rules = $this->getRules($this->context); if (empty($rules)) return [[], $meta]; $data = $this->getDataFromModel($target, $rules); foreach ($data as $key => $child) { $data[$key] = $dehydrateChild($key, $child); } return [$data, $meta]; } public function hydrate($data, $meta, $hydrateChild) { if (! is_iterable($data)) return null; if (isset($meta['__child_from_parent'])) { $model = $meta['__child_from_parent']; unset($meta['__child_from_parent']); } else { $model = $this->loadModel($meta); } if (isset($meta['relations'])) { foreach($meta['relations'] as $relationKey) { if (! isset($data[$relationKey])) continue; $data[$relationKey][1]['__child_from_parent'] = $model->getRelation($relationKey); $model->setRelation($relationKey, $hydrateChild($relationKey, $data[$relationKey])); unset($data[$relationKey]); } } foreach ($data as $key => $child) { $data[$key] = $hydrateChild($key, $child); } $this->setDataOnModel($model, $data); return $model; } public function get(&$target, $key) { return $target->$key; } public function set(Model &$target, $key, $value, $pathThusFar, $fullPath) { if (SupportLegacyModels::missingRuleFor($this->context->component, $fullPath)) { throw new CannotBindToModelDataWithoutValidationRuleException($fullPath, $this->context->component->getName()); } if ($target->relationLoaded($key)) { return $target->setRelation($key, $value); } if (array_key_exists($key, $target->getCasts()) && enum_exists($target->getCasts()[$key]) && $value === '') { $value = null; } $target->$key = $value; } public function methods($target) { return []; } public function call($target, $method, $params, $addEffect) { } protected function getRules($context) { $key = $this->path ?? null; if (is_null($key)) return []; if ($context->component) { return SupportLegacyModels::getRulesFor($this->context->component, $key); } } protected function getDataFromModel(Model $model, $rules) { return [ ...$this->filterAttributes($this->getAttributes($model), $rules), ...$this->filterRelations($model->getRelations(), $rules), ]; } protected function getAttributes($model) { $attributes = $model->attributesToArray(); foreach ($model->getCasts() as $key => $cast) { if (! class_exists($cast)) continue; if ( in_array(CastsAttributes::class, class_implements($cast)) && isset($attributes[$key]) ) { $attributes[$key] = $model->getAttributes()[$key]; } } return $attributes; } protected function filterAttributes($data, $rules) { $filteredAttributes = []; foreach($rules as $key => $rule) { // If the rule is an array, take the key instead if (is_array($rule)) { $rule = $key; } // If someone has created an empty model, the attribute may not exist // yet, so use data_get so it will still be sent to the front end. $filteredAttributes[$rule] = data_get($data, $rule); } return $filteredAttributes; } protected function filterRelations($data, $rules) { return array_filter($data, function ($key) use ($rules) { return array_key_exists($key, $rules) || in_array($key, $rules); }, ARRAY_FILTER_USE_KEY); } protected function loadModel($meta): ?Model { $class = $meta['class']; // If no alias found, this returns `null` $aliasClass = Relation::getMorphedModel($class); if (! is_null($aliasClass)) { $class = $aliasClass; } if (isset($meta['key'])) { $model = new $class; if (isset($meta['connection'])) { $model->setConnection($meta['connection']); } $query = $model->newQueryForRestoration($meta['key']); if (isset($meta['relations'])) { $query->with($meta['relations']); } $model = $query->first(); } else { $model = new $class(); } return $model; } protected function setDataOnModel(Model $model, $data) { foreach ($data as $key => $value) { $model->$key = $value; } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/EloquentCollectionSynth.php
src/Features/SupportLegacyModels/EloquentCollectionSynth.php
<?php namespace Livewire\Features\SupportLegacyModels; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; use LogicException; class EloquentCollectionSynth extends Synth { public static $key = 'elcl'; public static function match($target) { return $target instanceof EloquentCollection; } public function dehydrate(EloquentCollection $target, $dehydrateChild) { $class = $target::class; $modelClass = $target->getQueueableClass(); $meta = []; $meta['keys'] = $target->modelKeys(); $meta['class'] = $class; $meta['modelClass'] = $modelClass; if ($modelClass && ($connection = $this->getConnection($target)) !== $modelClass::make()->getConnectionName()) { $meta['connection'] = $connection; } $relations = $target->getQueueableRelations(); if (count($relations)) { $meta['relations'] = $relations; } $rules = $this->getRules($this->context); if (empty($rules)) return [[], $meta]; $data = $this->getDataFromCollection($target, $rules); foreach ($data as $key => $child) { $data[$key] = $dehydrateChild($key, $child); } return [ $data, $meta ]; } public function hydrate($data, $meta, $hydrateChild) { if (isset($meta['__child_from_parent'])) { $collection = $meta['__child_from_parent']; unset($meta['__child_from_parent']); } else { $collection = $this->loadCollection($meta); } if (isset($meta['relations'])) { $collection->loadMissing($meta['relations']); } if (count($data)) { foreach ($data as $key => $childData) { $childData[1]['__child_from_parent'] = $collection->get($key); $data[$key] = $hydrateChild($key, $childData); } return $collection::wrap($data); } return $collection; } public function get(&$target, $key) { return $target->get($key); } public function set(&$target, $key, $value, $pathThusFar, $fullPath) { if (SupportLegacyModels::missingRuleFor($this->context->component, $fullPath)) { throw new CannotBindToModelDataWithoutValidationRuleException($fullPath, $this->context->component->getName()); } $target->put($key, $value); } public function methods($target) { return []; } public function call($target, $method, $params, $addEffect) { } protected function getRules($context) { $key = $this->path ?? null; if (is_null($key)) return []; return SupportLegacyModels::getRulesFor($context->component, $key); } protected function getConnection(EloquentCollection $collection) { if ($collection->isEmpty()) { return; } $connection = $collection->first()->getConnectionName(); $collection->each(function ($model) use ($connection) { // If there is no connection name, it must be a new model so continue. if (is_null($model->getConnectionName())) { return; } if ($model->getConnectionName() !== $connection) { throw new LogicException('Livewire can\'t dehydrate an Eloquent Collection with models from different connections.'); } }); return $connection; } protected function getDataFromCollection(EloquentCollection $collection, $rules) { return $this->filterData($collection->all(), $rules); } protected function filterData($data, $rules) { return array_filter($data, function ($key) use ($rules) { return array_key_exists('*', $rules); }, ARRAY_FILTER_USE_KEY); } protected function loadCollection($meta) { if (isset($meta['keys']) && count($meta['keys']) >= 0 && ! empty($meta['modelClass'])) { $model = new $meta['modelClass']; if (isset($meta['connection'])) { $model->setConnection($meta['connection']); } $query = $model->newQueryForRestoration($meta['keys']); if (isset($meta['relations'])) { $query->with($meta['relations']); } $query->useWritePdo(); $collection = $query->get(); $collection = $collection->keyBy->getKey(); return new $meta['class']( collect($meta['keys'])->map(function ($id) use ($collection) { return $collection[$id] ?? null; })->filter() ); } return new $meta['class'](); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/SupportLegacyModels.php
src/Features/SupportLegacyModels/SupportLegacyModels.php
<?php namespace Livewire\Features\SupportLegacyModels; use Livewire\ComponentHook; use function Livewire\on; /** * Depends on: SupportValidation for ->missingRuleFor() method on component. (inside ModelSynth) */ class SupportLegacyModels extends ComponentHook { protected static $rules; static function provide() { // Only enable this feature if config option is set to `true`. if (config('livewire.legacy_model_binding', false) !== true) return; app('livewire')->propertySynthesizer([ EloquentModelSynth::class, EloquentCollectionSynth::class, ]); on('flush-state', function() { static::flushRules(); }); } static function flushRules() { static::$rules = null; } static function hasRuleFor($component, $path) { $path = str($path)->explode('.'); $has = false; $end = false; $segmentRules = static::getRules($component); foreach ($path as $key => $segment) { if ($end) { throw new \LogicException('Something went wrong'); } if (!is_numeric($segment) && array_key_exists($segment, $segmentRules)) { $segmentRules = $segmentRules[$segment]; $has = true; continue; } if (is_numeric($segment) && array_key_exists('*', $segmentRules)) { $segmentRules = $segmentRules['*']; $has = true; continue; } if (is_numeric($segment) && in_array('*', $segmentRules, true)) { $has = true; $end = true; continue; } if (in_array($segment, $segmentRules, true)) { $has = true; $end = true; continue; } $has = false; } return $has; } static function missingRuleFor($component, $path) { return ! static::hasRuleFor($component, $path); } static function getRules($component) { return static::$rules[$component->getId()] ??= static::processRules($component); } static function getRulesFor($component, $key) { $rules = static::getRules($component); $propertyWithStarsInsteadOfNumbers = static::ruleWithNumbersReplacedByStars($key); return static::dataGetWithoutWildcardSupport( $rules, $propertyWithStarsInsteadOfNumbers, data_get($rules, $key, []), ); } static function dataGetWithoutWildcardSupport($array, $key, $default) { $segments = explode('.', $key); $first = array_shift($segments); if (! isset($array[$first])) { return value($default); } $value = $array[$first]; if (count($segments) > 0) { return static::dataGetWithoutWildcardSupport($value, implode('.', $segments), $default); } return $value; } static function ruleWithNumbersReplacedByStars($dotNotatedProperty) { // Convert foo.0.bar.1 -> foo.*.bar.* return (string) str($dotNotatedProperty) // Replace all numeric indexes with an array wildcard: (.0., .10., .007.) => .*. // In order to match overlapping numerical indexes (foo.1.2.3.4.name), // We need to use a positive look-behind, that's technically all the magic here. // For better understanding, see: https://regexr.com/5d1n3 ->replaceMatches('/(?<=(\.))\d+\./', '*.') // Replace all numeric indexes at the end of the name with an array wildcard // (Same as the previous regex, but ran only at the end of the string) // For better undestanding, see: https://regexr.com/5d1n6 ->replaceMatches('/\.\d+$/', '.*'); } protected static function processRules($component) { $rules = array_keys($component->getRules()); return static::convertDotNotationToArrayNotation($rules); } protected static function convertDotNotationToArrayNotation($rules) { return static::recusivelyProcessDotNotation($rules); } protected static function recusivelyProcessDotNotation($rules) { $singleRules = []; $groupedRules = []; foreach ($rules as $key => $value) { $value = str($value); if (!$value->contains('.')) { $singleRules[] = (string) $value; continue; } $groupedRules[(string) $value->before('.')][] = (string) $value->after('.'); } foreach ($groupedRules as $key => $value) { $groupedRules[$key] = static::recusivelyProcessDotNotation($value); } return $singleRules + $groupedRules; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/ModelAttributesCanBeCastUnitTest.php
src/Features/SupportLegacyModels/Tests/ModelAttributesCanBeCastUnitTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Illuminate\Contracts\Database\Eloquent\CastsAttributes; use Illuminate\Validation\Rule; use Livewire\Livewire; use Sushi\Sushi; use Tests\TestComponent; class ModelAttributesCanBeCastUnitTest extends \Tests\TestCase { use Concerns\EnableLegacyModels; public function setUp(): void { parent::setUp(); } public function test_can_cast_normal_date_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSet('model.normal_date', new \DateTime('2000-08-12')) ->assertSnapshotSetStrict('model.normal_date', '2000-08-12T00:00:00.000000Z') ->set('model.normal_date', '2019-10-12') ->call('validateAttribute', 'model.normal_date') ->assertHasNoErrors('model.normal_date') ->assertSet('model.normal_date', new \DateTime('2019-10-12')) ->assertSnapshotSetStrict('model.normal_date', '2019-10-12T00:00:00.000000Z'); } public function test_can_cast_formatted_date_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSet('model.formatted_date', new \DateTime('2020-03-03')) ->assertSnapshotSetStrict('model.formatted_date', '03-03-2020') ->set('model.formatted_date', '03-03-1999') ->call('validateAttribute', 'model.formatted_date') ->assertHasNoErrors('model.formatted_date') ->assertSet('model.formatted_date', new \DateTime('1999-03-03')) ->assertSnapshotSetStrict('model.formatted_date', '03-03-1999') ->set('model.formatted_date', '2020-03-03') ->call('validateAttribute', 'model.formatted_date') ->assertHasNoErrors('model.formatted_date') ->assertSet('model.formatted_date', new \DateTime('2020-03-03')) ->assertSnapshotSetStrict('model.formatted_date', '03-03-2020'); } public function test_can_cast_datetime_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSet('model.date_with_time', new \DateTime('2015-10-21 00:00:00')) ->assertSnapshotSetStrict('model.date_with_time', '2015-10-21T00:00:00.000000Z') ->set('model.date_with_time', '1985-10-26 01:20') ->call('validateAttribute', 'model.date_with_time') ->assertHasNoErrors('model.date_with_time') ->assertSet('model.date_with_time', new \DateTime('1985-10-26 01:20')) ->assertSnapshotSetStrict('model.date_with_time', '1985-10-26T01:20:00.000000Z'); } public function test_can_cast_timestamp_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.timestamped_date', 1030665600) ->assertSnapshotSetStrict('model.timestamped_date', 1030665600) ->set('model.timestamped_date', 1538110800) ->call('validateAttribute', 'model.timestamped_date') ->assertHasNoErrors('model.timestamped_date') ->assertSetStrict('model.timestamped_date', 1538110800) ->assertSnapshotSetStrict('model.timestamped_date', 1538110800); } public function test_can_cast_integer_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.integer_number', 1) ->assertSnapshotSetStrict('model.integer_number', 1) ->set('model.integer_number', 1.9999999999999) ->call('validateAttribute', 'model.integer_number') ->assertHasNoErrors('model.integer_number') ->assertSetStrict('model.integer_number', 1) ->assertSnapshotSetStrict('model.integer_number', 1) ->set('model.integer_number', '1.9999999999') ->call('validateAttribute', 'model.integer_number') ->assertHasNoErrors('model.integer_number') ->assertSetStrict('model.integer_number', 1) ->assertSnapshotSetStrict('model.integer_number', 1); } public function test_can_cast_real_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.real_number', 2.0) ->assertSnapshotSetStrict('model.real_number', 2) ->set('model.real_number', 2.9999999999) ->call('validateAttribute', 'model.real_number') ->assertHasNoErrors('model.real_number') ->assertSetStrict('model.real_number', 2.9999999999) ->assertSnapshotSetStrict('model.real_number', 2.9999999999) ->set('model.real_number', '2.345') ->call('validateAttribute', 'model.real_number') ->assertHasNoErrors('model.real_number') ->assertSetStrict('model.real_number', 2.345) ->assertSnapshotSetStrict('model.real_number', 2.345); } public function test_can_cast_float_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.float_number', 3.0) ->assertSnapshotSetStrict('model.float_number', 3) ->set('model.float_number', 3.9999999998) ->call('validateAttribute', 'model.float_number') ->assertHasNoErrors('model.float_number') ->assertSetStrict('model.float_number', 3.9999999998) ->assertSnapshotSetStrict('model.float_number', 3.9999999998) ->set('model.float_number', '3.399') ->call('validateAttribute', 'model.float_number') ->assertHasNoErrors('model.float_number') ->assertSetStrict('model.float_number', 3.399) ->assertSnapshotSetStrict('model.float_number', 3.399); } public function test_can_cast_double_precision_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.double_precision_number', 4.0) ->assertSnapshotSetStrict('model.double_precision_number', 4) ->set('model.double_precision_number', 4.9999999997) ->call('validateAttribute', 'model.double_precision_number') ->assertHasNoErrors('model.double_precision_number') ->assertSetStrict('model.double_precision_number', 4.9999999997) ->assertSnapshotSetStrict('model.double_precision_number', 4.9999999997) ->set('model.double_precision_number', '4.20') ->call('validateAttribute', 'model.double_precision_number') ->assertHasNoErrors('model.double_precision_number') ->assertSetStrict('model.double_precision_number', 4.20) ->assertSnapshotSetStrict('model.double_precision_number', 4.20); } public function test_can_cast_decimal_attributes_with_one_digit_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.decimal_with_one_digit', '5.0') ->assertSnapshotSetStrict('model.decimal_with_one_digit', '5.0') ->set('model.decimal_with_one_digit', 5.120983) ->call('validateAttribute', 'model.decimal_with_one_digit') ->assertHasNoErrors('model.decimal_with_one_digit') ->assertSetStrict('model.decimal_with_one_digit', '5.1') ->assertSnapshotSetStrict('model.decimal_with_one_digit', '5.1') ->set('model.decimal_with_one_digit', '5.55') ->call('validateAttribute', 'model.decimal_with_one_digit') ->assertHasNoErrors('model.decimal_with_one_digit') ->assertSetStrict('model.decimal_with_one_digit', '5.6') ->assertSnapshotSetStrict('model.decimal_with_one_digit', '5.6'); } public function test_can_cast_decimal_attributes_with_two_digits_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.decimal_with_two_digits', '6.00') ->assertSnapshotSetStrict('model.decimal_with_two_digits', '6.00') ->set('model.decimal_with_two_digits', 6.4567) ->call('validateAttribute', 'model.decimal_with_two_digits') ->assertHasNoErrors('model.decimal_with_two_digits') ->assertSetStrict('model.decimal_with_two_digits', '6.46') ->assertSnapshotSetStrict('model.decimal_with_two_digits', '6.46') ->set('model.decimal_with_two_digits', '6.212') ->call('validateAttribute', 'model.decimal_with_two_digits') ->assertHasNoErrors('model.decimal_with_two_digits') ->assertSetStrict('model.decimal_with_two_digits', '6.21') ->assertSnapshotSetStrict('model.decimal_with_two_digits', '6.21'); } public function test_can_cast_string_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.string_name', 'Gladys') ->assertSnapshotSetStrict('model.string_name', 'Gladys') ->set('model.string_name', 'Elena') ->call('validateAttribute', 'model.string_name') ->assertHasNoErrors('model.string_name') ->assertSetStrict('model.string_name', 'Elena') ->assertSnapshotSetStrict('model.string_name', 'Elena') ->set('model.string_name', 123) ->call('validateAttribute', 'model.string_name') ->assertHasNoErrors('model.string_name') ->assertSetStrict('model.string_name', '123') ->assertSnapshotSetStrict('model.string_name', '123'); } public function test_can_cast_boolean_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.boolean_value', false) ->assertSnapshotSetStrict('model.boolean_value', false) ->set('model.boolean_value', true) ->call('validateAttribute', 'model.boolean_value') ->assertHasNoErrors('model.boolean_value') ->assertSetStrict('model.boolean_value', true) ->assertSnapshotSetStrict('model.boolean_value', true) ->set('model.boolean_value', 0) ->call('validateAttribute', 'model.boolean_value') ->assertHasNoErrors('model.boolean_value') ->assertSetStrict('model.boolean_value', false) ->assertSnapshotSetStrict('model.boolean_value', false) ->set('model.boolean_value', 1) ->call('validateAttribute', 'model.boolean_value') ->assertHasNoErrors('model.boolean_value') ->assertSetStrict('model.boolean_value', true) ->assertSnapshotSetStrict('model.boolean_value', true) ->set('model.boolean_value', 'true') ->call('validateAttribute', 'model.boolean_value') ->assertHasNoErrors('model.boolean_value') ->assertSetStrict('model.boolean_value', true) ->assertSnapshotSetStrict('model.boolean_value', true) ->set('model.boolean_value', '') ->call('validateAttribute', 'model.boolean_value') ->assertHasNoErrors('model.boolean_value') ->assertSetStrict('model.boolean_value', false) ->assertSnapshotSetStrict('model.boolean_value', false); } public function test_can_cast_array_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.array_list', []) ->assertSnapshotSetStrict('model.array_list', []) ->set('model.array_list', ['foo', 'bar']) ->call('validateAttribute', 'model.array_list') ->assertHasNoErrors('model.array_list') ->assertSetStrict('model.array_list', ['foo', 'bar']) ->assertSnapshotSetStrict('model.array_list', ['foo', 'bar']); } public function test_can_cast_json_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.json_list', [1, 2, 3]) ->assertSnapshotSetStrict('model.json_list', [1, 2, 3]) ->set('model.json_list', [4, 5, 6]) ->call('validateAttribute', 'model.json_list') ->assertHasNoErrors('model.json_list') ->assertSetStrict('model.json_list', [4, 5, 6]) ->assertSnapshotSetStrict('model.json_list', [4, 5, 6]); } public function test_can_cast_collection_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSet('model.collected_list', collect([true, false])) ->assertSnapshotSetStrict('model.collected_list', [true, false]) ->set('model.collected_list', [false, true]) ->call('validateAttribute', 'model.collected_list') ->assertHasNoErrors('model.collected_list') ->assertSet('model.collected_list', collect([false, true])) ->assertSnapshotSetStrict('model.collected_list', [false, true]); } public function test_can_cast_object_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSet('model.object_value', (object) ['name' => 'Marian', 'email' => 'marian@likes.pizza']) ->assertSnapshotSetStrict('model.object_value', (array) ['name' => 'Marian', 'email' => 'marian@likes.pizza']) ->set('model.object_value', (object) ['name' => 'Marian', 'email' => 'marian@my-company.rocks']) ->call('validateAttribute', 'model.object_value') ->assertHasNoErrors('model.object_value') ->assertSetStrict('model.object_value.name', 'Marian') ->assertSnapshotSetStrict('model.object_value.name', 'Marian') ->assertSetStrict('model.object_value.email', 'marian@my-company.rocks') ->assertSnapshotSetStrict('model.object_value.email', 'marian@my-company.rocks'); } public function test_can_cast_attributes_with_custom_caster_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSet('model.custom_caster', QuizAnswer::make('dumb answer')) ->assertSnapshotSetStrict('model.custom_caster', 'dumb answer') ->set('model.custom_caster', 'e=mc2') ->call('validateAttribute', 'model.custom_caster') ->assertHasNoErrors('model.custom_caster') ->assertSet('model.custom_caster', QuizAnswer::make('e=mc2')) ->assertSnapshotSetStrict('model.custom_caster', 'e=mc2'); } public function test_can_cast_enum_attributes_from_model_casts_definition() { Livewire::test(ComponentForModelAttributeCasting::class) ->assertSetStrict('model.enum', null) ->assertSnapshotSetStrict('model.enum', null) ->set('model.enum', TestingEnum::FOO->value) ->call('validateAttribute', 'model.enum') ->assertHasNoErrors('model.enum') ->assertSetStrict('model.enum', TestingEnum::FOO) ->assertSnapshotSetStrict('model.enum', TestingEnum::FOO->value) ->set('model.enum', '') ->call('validateAttribute', 'model.enum') ->assertHasNoErrors('model.enum') ->assertSetStrict('model.enum', null) ->assertSnapshotSetStrict('model.enum', null); } } class ModelForAttributeCasting extends \Illuminate\Database\Eloquent\Model { use Sushi; protected $guarded = []; protected $casts = [ 'normal_date' => 'date', 'formatted_date' => 'date:d-m-Y', 'date_with_time' => 'datetime', 'timestamped_date' => 'timestamp', 'integer_number' => 'integer', 'real_number' => 'real', 'float_number' => 'float', 'double_precision_number' => 'double', 'decimal_with_one_digit' => 'decimal:1', 'decimal_with_two_digits' => 'decimal:2', 'string_name' => 'string', 'boolean_value' => 'boolean', 'array_list' => 'array', 'json_list' => 'json', 'collected_list' => 'collection', 'object_value' => 'object', 'custom_caster' => QuizAnswerCaster::class, 'enum' => TestingEnum::class, ]; public function getRows() { return [ [ 'normal_date' => new \DateTime('2000-08-12'), 'formatted_date' => new \DateTime('2020-03-03'), 'date_with_time' => new \DateTime('2015-10-21'), 'timestamped_date' => new \DateTime('2002-08-30'), 'integer_number' => 1, 'real_number' => 2, 'float_number' => 3, 'double_precision_number' => 4, 'decimal_with_one_digit' => 5, 'decimal_with_two_digits' => 6, 'string_name' => 'Gladys', 'boolean_value' => false, 'array_list' => json_encode([]), 'json_list' => json_encode([1, 2, 3]), 'collected_list' => json_encode([true, false]), 'object_value' => json_encode(['name' => 'Marian', 'email' => 'marian@likes.pizza']), 'custom_caster' => 'dumb answer', 'enum' => null, ] ]; } } class QuizAnswer { protected $answer; public static function make(string $answer): self { $new = new static(); $new->answer = $answer; return $new; } public function getAnswer(): string { return $this->answer; } public function matches($givenAnswer): bool { return $this->answer === $givenAnswer; } public function __toString() { return $this->getAnswer(); } } class QuizAnswerCaster implements CastsAttributes { public function get($model, string $key, $value, array $attributes) { return QuizAnswer::make((string) $value); } public function set($model, string $key, $value, array $attributes) { if ($value instanceof QuizAnswer) { $value = $value->getAnswer(); } return $value; } } enum TestingEnum: string { case FOO = 'bar'; } class ComponentForModelAttributeCasting extends TestComponent { public $model; public function rules(): array { return [ 'model.normal_date' => ['required', 'date'], 'model.formatted_date' => ['required', 'date'], 'model.date_with_time' => ['required', 'date'], 'model.timestamped_date' => ['required', 'integer'], 'model.integer_number' => ['required', 'integer'], 'model.real_number' => ['required', 'numeric'], 'model.float_number' => ['required', 'numeric'], 'model.double_precision_number' => ['required', 'numeric'], 'model.decimal_with_one_digit' => ['required', 'numeric'], 'model.decimal_with_two_digits' => ['required', 'numeric'], 'model.string_name' => ['required', 'string'], 'model.boolean_value' => ['required', 'boolean'], 'model.array_list' => ['required', 'array'], 'model.array_list.*' => ['required', 'string'], 'model.json_list' => ['required', 'array'], 'model.json_list.*' => ['required', 'numeric'], 'model.collected_list' => ['required'], 'model.collected_list.*' => ['required', 'boolean'], 'model.object_value' => ['required'], 'model.object_value.name' => ['required'], 'model.object_value.email' => ['required', 'email'], 'model.custom_caster' => ['required'], 'model.enum' => ['nullable', Rule::enum(TestingEnum::class)] ]; } public function mount() { $this->model = ModelForAttributeCasting::first(); } public function validateAttribute(string $attribute) { $this->validateOnly($attribute); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/PublicPropertyHydrationAndDehydrationUnitTest.php
src/Features/SupportLegacyModels/Tests/PublicPropertyHydrationAndDehydrationUnitTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Livewire\Livewire; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Model; use Tests\TestComponent; class PublicPropertyHydrationAndDehydrationUnitTest extends \Tests\TestCase { use Concerns\EnableLegacyModels; public function setUp(): void { parent::setUp(); Schema::create('authors', function ($table) { $table->bigIncrements('id'); $table->string('title'); $table->string('name'); $table->string('email'); $table->timestamps(); }); Schema::create('posts', function ($table) { $table->bigIncrements('id'); $table->string('title'); $table->string('description'); $table->string('content'); $table->foreignId('author_id')->nullable(); $table->timestamps(); }); Schema::create('comments', function ($table) { $table->bigIncrements('id'); $table->string('comment'); $table->foreignId('post_id'); $table->foreignId('author_id'); $table->timestamps(); }); Schema::create('other_comments', function ($table) { $table->bigIncrements('id'); $table->string('comment'); $table->foreignId('post_id'); $table->foreignId('author_id'); $table->timestamps(); }); } public function test_it_uses_class_name_if_laravels_morph_map_not_available_when_dehydrating() { Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content']); $component = Livewire::test(PostComponent::class); $this->assertEquals('Livewire\Features\SupportLegacyModels\Tests\Post', $component->snapshot['data']['post'][1]['class']); } public function test_it_uses_class_name_if_laravels_morph_map_not_available_when_hydrating() { $post = Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content']); $post = $post->fresh(); Livewire::test(PostComponent::class) ->call('$refresh') ->assertSet('post', $post); } public function test_it_uses_laravels_morph_map_instead_of_class_name_if_available_when_dehydrating() { $post = Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content']); Relation::morphMap([ 'post' => Post::class, ]); $component = Livewire::test(PostComponent::class); $this->assertEquals('post', $component->snapshot['data']['post'][1]['class']); } public function test_it_uses_laravels_morph_map_instead_of_class_name_if_available_when_hydrating() { $post = Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content']); $post = $post->fresh(); Relation::morphMap([ 'post' => Post::class, ]); Livewire::test(PostComponent::class) ->call('$refresh') ->assertSet('post', $post); } public function test_it_does_not_trigger_ClassMorphViolationException_when_morh_map_is_enforced() { Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content']); // reset morph Relation::morphMap([], false); Relation::requireMorphMap(); $component = Livewire::test(PostComponent::class); $this->assertEquals('Livewire\Features\SupportLegacyModels\Tests\Post', $component->snapshot['data']['post'][1]['class']); Relation::requireMorphMap(false); } public function test_an_eloquent_model_properties_with_deep_relations_and_single_relations_can_have_dirty_data_reapplied() { Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); Author::create(['id' => 2, 'title' => 'sample', 'name' => 'thing', 'email' => 'todo']); Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'author_id' => 1]); Post::create(['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'author_id' => 1]); Comment::create(['id' => 1, 'comment' => 'Comment 1', 'post_id' => 1, 'author_id' => 1]); Comment::create(['id' => 2, 'comment' => 'Comment 2', 'post_id' => 1, 'author_id' => 2]); $model = Author::with(['posts', 'posts.comments', 'posts.comments.author'])->first(); $component = Livewire::test(ModelsComponent::class, ['model' => $model]) ->set('model.title', 'oof') ->set('model.name', 'rab') ->set('model.email', 'zab') ->set('model.posts.0.title', '1 Post') ->set('model.posts.0.description', 'Description 1 Post') ->set('model.posts.0.content', 'Content 1 Post') ->set('model.posts.0.comments.1.comment', '2 Comment') ->set('model.posts.0.comments.1.author.name', 'gniht'); $updatedModel = $component->get('model'); $this->assertEquals('oof', $updatedModel->title); $this->assertEquals('rab', $updatedModel->name); $this->assertEquals('zab', $updatedModel->email); $this->assertEquals('1 Post', $updatedModel->posts[0]->title,); $this->assertEquals('Description 1 Post', $updatedModel->posts[0]->description); $this->assertEquals('Content 1 Post', $updatedModel->posts[0]->content); $this->assertEquals('2 Comment', $updatedModel->posts[0]->comments[1]->comment); $this->assertEquals('gniht', $updatedModel->posts[0]->comments[1]->author->name); } public function test_an_eloquent_model_properties_with_deep_relations_and_multiword_relations_can_have_dirty_data_reapplied() { Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); Author::create(['id' => 2, 'title' => 'sample', 'name' => 'thing', 'email' => 'todo']); Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'author_id' => 1]); Post::create(['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'author_id' => 1]); Comment::create(['id' => 1, 'comment' => 'Comment 1', 'post_id' => 1, 'author_id' => 1]); Comment::create(['id' => 2, 'comment' => 'Comment 2', 'post_id' => 1, 'author_id' => 2]); OtherComment::create(['id' => 1, 'comment' => 'Other Comment 1', 'post_id' => 1, 'author_id' => 1]); OtherComment::create(['id' => 2, 'comment' => 'Other Comment 2', 'post_id' => 1, 'author_id' => 2]); $model = Author::with(['posts', 'posts.comments', 'posts.comments.author', 'posts.otherComments', 'posts.otherComments.author'])->first(); $component = Livewire::test(ModelsComponent::class, ['model' => $model]) ->set('model.title', 'oof') ->set('model.name', 'rab') ->set('model.email', 'zab') ->set('model.posts.0.title', '1 Post') ->set('model.posts.0.description', 'Description 1 Post') ->set('model.posts.0.content', 'Content 1 Post') ->set('model.posts.0.comments.1.comment', '2 Comment') ->set('model.posts.0.comments.1.author.name', 'gniht') ->set('model.posts.0.otherComments.1.comment', '2 Other Comment'); $updatedModel = $component->get('model'); $this->assertEquals('oof', $updatedModel->title); $this->assertEquals('rab', $updatedModel->name); $this->assertEquals('zab', $updatedModel->email); $this->assertEquals('1 Post', $updatedModel->posts[0]->title,); $this->assertEquals('Description 1 Post', $updatedModel->posts[0]->description); $this->assertEquals('Content 1 Post', $updatedModel->posts[0]->content); $this->assertEquals('2 Comment', $updatedModel->posts[0]->comments[1]->comment); $this->assertEquals('gniht', $updatedModel->posts[0]->comments[1]->author->name); $this->assertEquals('2 Other Comment', $updatedModel->posts[0]->otherComments[1]->comment); } public function test_an_eloquent_model_with_a_properties_dirty_data_set_to_an_empty_array_gets_hydrated_properly() { $model = new Author(); $component = Livewire::test(ModelsComponent::class, ['model' => $model]) ->set('model.name', []); $updatedModel = $component->get('model'); $this->assertEquals([], $updatedModel->name); } public function test_an_eloquent_model_properties_can_be_serialised() { $model = Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); $rules = [ 'model.title' => '', 'model.email' => '', ]; $expected = [ 'title' => 'foo', 'email' => 'baz', ]; $component = Livewire::test(ModelsComponent::class, ['model' => $model, 'rules' => $rules]); $results = $component->snapshot['data']['model'][0]; $this->assertEquals($expected, $results); } public function test_an_eloquent_model_properties_with_deep_relations_and_single_relations_can_be_serialised() { Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); Author::create(['id' => 2, 'title' => 'sample', 'name' => 'thing', 'email' => 'todo']); Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'author_id' => 1]); Post::create(['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'author_id' => 1]); Comment::create(['id' => 1, 'comment' => 'Comment 1', 'post_id' => 1, 'author_id' => 1]); Comment::create(['id' => 2, 'comment' => 'Comment 2', 'post_id' => 1, 'author_id' => 2]); $model = Author::with(['posts', 'posts.comments', 'posts.comments.author'])->first(); $rules = [ 'model.title' => '', 'model.email' => '', 'model.posts.*.title' => '', 'model.posts.*.comments.*.comment' => '', 'model.posts.*.comments.*.author.name' => '', ]; $expected = [ 'title' => 'foo', 'email' => 'baz', 'posts' => [ [ 'title' => 'Post 1', 'comments' => [ [ 'comment' => 'Comment 1', 'author' => [ 'name' => 'bar' ], ], [ 'comment' => 'Comment 2', 'author' => [ 'name' => 'thing' ], ], ], ], [ 'title' => 'Post 2', 'comments' => [], ], ], ]; $component = Livewire::test(ModelsComponent::class, ['model' => $model, 'rules' => $rules]); $results = $component->snapshot['data']['model'][0]; $this->assertEquals($expected['title'], $results['title']); $this->assertEquals($expected['email'], $results['email']); $this->assertEquals($expected['posts'][0]['title'], $results['posts'][0][0][0]['title']); $this->assertEquals($expected['posts'][0]['comments'][0]['comment'], $results['posts'][0][0][0]['comments'][0][0][0]['comment']); $this->assertEquals($expected['posts'][0]['comments'][0]['author']['name'], $results['posts'][0][0][0]['comments'][0][0][0]['author'][0]['name']); $this->assertEquals($expected['posts'][1]['title'], $results['posts'][0][1][0]['title']); $this->assertEquals($expected['posts'][1]['comments'], $results['posts'][0][1][0]['comments'][0]); } public function test_an_eloquent_model_properties_with_deep_relations_and_multiword_relations_can_be_serialised() { Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); Author::create(['id' => 2, 'title' => 'sample', 'name' => 'thing', 'email' => 'todo']); Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'author_id' => 1]); Post::create(['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'author_id' => 1]); Comment::create(['id' => 1, 'comment' => 'Comment 1', 'post_id' => 1, 'author_id' => 1]); Comment::create(['id' => 2, 'comment' => 'Comment 2', 'post_id' => 1, 'author_id' => 2]); OtherComment::create(['id' => 1, 'comment' => 'Other Comment 1', 'post_id' => 1, 'author_id' => 1]); OtherComment::create(['id' => 2, 'comment' => 'Other Comment 2', 'post_id' => 1, 'author_id' => 2]); $model = Author::with(['posts', 'posts.comments', 'posts.comments.author', 'posts.otherComments', 'posts.otherComments.author'])->first(); $rules = [ 'model.title' => '', 'model.email' => '', 'model.posts.*.title' => '', 'model.posts.*.comments.*.comment' => '', 'model.posts.*.comments.*.author.name' => '', 'model.posts.*.otherComments.*.comment' => '', 'model.posts.*.otherComments.*.author.name' => '', ]; $expected = [ 'title' => 'foo', 'email' => 'baz', 'posts' => [ [ 'title' => 'Post 1', 'comments' => [ [ 'comment' => 'Comment 1', 'author' => [ 'name' => 'bar' ], ], [ 'comment' => 'Comment 2', 'author' => [ 'name' => 'thing' ], ], ], 'otherComments' => [ [ 'comment' => 'Other Comment 1', 'author' => [ 'name' => 'bar' ], ], [ 'comment' => 'Other Comment 2', 'author' => [ 'name' => 'thing' ], ], ], ], [ 'title' => 'Post 2', 'comments' => [], 'otherComments' => [], ], ], ]; $component = Livewire::test(ModelsComponent::class, ['model' => $model, 'rules' => $rules]); $results = $component->snapshot['data']['model'][0]; $this->assertEquals($expected['title'], $results['title']); $this->assertEquals($expected['email'], $results['email']); $this->assertEquals($expected['posts'][0]['title'], $results['posts'][0][0][0]['title']); $this->assertEquals($expected['posts'][0]['comments'][0]['comment'], $results['posts'][0][0][0]['comments'][0][0][0]['comment']); $this->assertEquals($expected['posts'][0]['comments'][0]['author']['name'], $results['posts'][0][0][0]['comments'][0][0][0]['author'][0]['name']); $this->assertEquals($expected['posts'][0]['otherComments'][0]['comment'], $results['posts'][0][0][0]['otherComments'][0][0][0]['comment']); $this->assertEquals($expected['posts'][0]['otherComments'][0]['author']['name'], $results['posts'][0][0][0]['otherComments'][0][0][0]['author'][0]['name']); $this->assertEquals($expected['posts'][1]['title'], $results['posts'][0][1][0]['title']); $this->assertEquals($expected['posts'][1]['comments'], $results['posts'][0][1][0]['comments'][0]); } public function test_an_eloquent_collection_properties_can_be_serialised() { Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); Author::create(['id' => 2, 'title' => 'sample', 'name' => 'thing', 'email' => 'todo']); $models = Author::all(); $rules = [ 'models.*.title' => '', 'models.*.email' => '', ]; $expected = [ [ 'title' => 'foo', 'email' => 'baz', ], [ 'title' => 'sample', 'email' => 'todo', ], ]; $component = Livewire::test(ModelsComponent::class, ['models' => $models, 'rules' => $rules]); $results = $component->snapshot['data']['models'][0]; $this->assertEquals($expected[0], $results[0][0]); $this->assertEquals($expected[1], $results[1][0]); } public function test_an_eloquent_collection_properties_with_relations_can_be_serialised() { Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); Author::create(['id' => 2, 'title' => 'sample', 'name' => 'thing', 'email' => 'todo']); Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'author_id' => 1]); Post::create(['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'author_id' => 1]); Post::create(['id' => 3, 'title' => 'Post 3', 'description' => 'Post 3 Description', 'content' => 'Post 3 Content', 'author_id' => 2]); Post::create(['id' => 4, 'title' => 'Post 4', 'description' => 'Post 4 Description', 'content' => 'Post 4 Content', 'author_id' => 2]); $models = Author::with('posts')->get(); $rules = [ 'models.*.title' => '', 'models.*.email' => '', 'models.*.posts.*.title' => '', ]; $expected = [ [ 'title' => 'foo', 'email' => 'baz', 'posts' => [ ['title' => 'Post 1'], ['title' => 'Post 2'], ], ], [ 'title' => 'sample', 'email' => 'todo', 'posts' => [ ['title' => 'Post 3'], ['title' => 'Post 4'], ], ], ]; $component = Livewire::test(ModelsComponent::class, ['models' => $models, 'rules' => $rules]); $results = $component->snapshot['data']['models'][0]; $this->assertEquals($expected[0]['title'], $results[0][0]['title']); $this->assertEquals($expected[0]['email'], $results[0][0]['email']); $this->assertEquals($expected[0]['posts'][0]['title'], $results[0][0]['posts'][0][0][0]['title']); $this->assertEquals($expected[0]['posts'][1]['title'], $results[0][0]['posts'][0][1][0]['title']); $this->assertEquals($expected[1]['title'], $results[1][0]['title']); $this->assertEquals($expected[1]['email'], $results[1][0]['email']); $this->assertEquals($expected[1]['posts'][0]['title'], $results[1][0]['posts'][0][0][0]['title']); $this->assertEquals($expected[1]['posts'][1]['title'], $results[1][0]['posts'][0][1][0]['title']); } public function test_an_eloquent_collection_properties_with_deep_relations_can_be_serialised() { Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); Author::create(['id' => 2, 'title' => 'sample', 'name' => 'thing', 'email' => 'todo']); Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'author_id' => 1]); Post::create(['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'author_id' => 1]); Comment::create(['id' => 1, 'comment' => 'Comment 1', 'post_id' => 1, 'author_id' => 1]); Comment::create(['id' => 2, 'comment' => 'Comment 2', 'post_id' => 1, 'author_id' => 2]); Comment::create(['id' => 3, 'comment' => 'Comment 3', 'post_id' => 2, 'author_id' => 1]); Comment::create(['id' => 4, 'comment' => 'Comment 4', 'post_id' => 2, 'author_id' => 2]); $models = Author::with(['posts', 'posts.comments'])->get(); $rules = [ 'models.*.title' => '', 'models.*.email' => '', 'models.*.posts.*.title' => '', 'models.*.posts.*.comments.*.comment' => '', ]; $expected = [ [ 'title' => 'foo', 'email' => 'baz', 'posts' => [ [ 'title' => 'Post 1', 'comments' => [ ['comment' => 'Comment 1'], ['comment' => 'Comment 2'], ], ], [ 'title' => 'Post 2', 'comments' => [ ['comment' => 'Comment 3'], ['comment' => 'Comment 4'], ], ], ], ], [ 'title' => 'sample', 'email' => 'todo', 'posts' => [], ], ]; $component = Livewire::test(ModelsComponent::class, ['models' => $models, 'rules' => $rules]); $results = $component->snapshot['data']['models'][0]; $this->assertEquals($expected[0]['title'], $results[0][0]['title']); $this->assertEquals($expected[0]['email'], $results[0][0]['email']); $this->assertEquals($expected[0]['posts'][0]['title'], $results[0][0]['posts'][0][0][0]['title']); $this->assertEquals($expected[0]['posts'][0]['comments'][0]['comment'], $results[0][0]['posts'][0][0][0]['comments'][0][0][0]['comment']); $this->assertEquals($expected[0]['posts'][0]['comments'][1]['comment'], $results[0][0]['posts'][0][0][0]['comments'][0][1][0]['comment']); $this->assertEquals($expected[0]['posts'][1]['title'], $results[0][0]['posts'][0][1][0]['title']); $this->assertEquals($expected[0]['posts'][1]['comments'][0]['comment'], $results[0][0]['posts'][0][1][0]['comments'][0][0][0]['comment']); $this->assertEquals($expected[0]['posts'][1]['comments'][1]['comment'], $results[0][0]['posts'][0][1][0]['comments'][0][1][0]['comment']); $this->assertEquals($expected[1]['title'], $results[1][0]['title']); $this->assertEquals($expected[1]['email'], $results[1][0]['email']); $this->assertEquals($expected[1]['posts'], $results[1][0]['posts'][0]); } public function test_an_eloquent_collection_properties_with_deep_relations_and_single_relations_can_be_serialised() { Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); Author::create(['id' => 2, 'title' => 'sample', 'name' => 'thing', 'email' => 'todo']); Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'author_id' => 1]); Post::create(['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'author_id' => 1]); Comment::create(['id' => 1, 'comment' => 'Comment 1', 'post_id' => 1, 'author_id' => 1]); Comment::create(['id' => 2, 'comment' => 'Comment 2', 'post_id' => 1, 'author_id' => 2]); $models = Author::with(['posts', 'posts.comments', 'posts.comments.author'])->get(); $rules = [ 'models.*.title' => '', 'models.*.email' => '', 'models.*.posts.*.title' => '', 'models.*.posts.*.comments.*.comment' => '', 'models.*.posts.*.comments.*.author.name' => '', ]; $expected = [ [ 'title' => 'foo', 'email' => 'baz', 'posts' => [ [ 'title' => 'Post 1', 'comments' => [ [ 'comment' => 'Comment 1', 'author' => [ 'name' => 'bar' ], ], [ 'comment' => 'Comment 2', 'author' => [ 'name' => 'thing' ], ], ], ], [ 'title' => 'Post 2', 'comments' => [], ], ], ], [ 'title' => 'sample', 'email' => 'todo', 'posts' => [], ], ]; $component = Livewire::test(ModelsComponent::class, ['models' => $models, 'rules' => $rules]); $results = $component->snapshot['data']['models'][0]; $this->assertEquals($expected[0]['title'], $results[0][0]['title']); $this->assertEquals($expected[0]['email'], $results[0][0]['email']); $this->assertEquals($expected[0]['posts'][0]['title'], $results[0][0]['posts'][0][0][0]['title']); $this->assertEquals($expected[0]['posts'][0]['comments'][0]['comment'], $results[0][0]['posts'][0][0][0]['comments'][0][0][0]['comment']); $this->assertEquals($expected[0]['posts'][0]['comments'][0]['author']['name'], $results[0][0]['posts'][0][0][0]['comments'][0][0][0]['author'][0]['name']); $this->assertEquals($expected[0]['posts'][0]['comments'][1]['comment'], $results[0][0]['posts'][0][0][0]['comments'][0][1][0]['comment']); $this->assertEquals($expected[0]['posts'][0]['comments'][1]['author']['name'], $results[0][0]['posts'][0][0][0]['comments'][0][1][0]['author'][0]['name']); $this->assertEquals($expected[0]['posts'][1]['title'], $results[0][0]['posts'][0][1][0]['title']); $this->assertEquals($expected[0]['posts'][1]['comments'], $results[0][0]['posts'][0][1][0]['comments'][0]); $this->assertEquals($expected[1]['title'], $results[1][0]['title']); $this->assertEquals($expected[1]['email'], $results[1][0]['email']); $this->assertEquals($expected[1]['posts'], $results[1][0]['posts'][0]); } public function test_an_eloquent_collection_properties_with_deep_relations_and_multiword_relations_can_be_serialised() { Author::create(['id' => 1, 'title' => 'foo', 'name' => 'bar', 'email' => 'baz']); Author::create(['id' => 2, 'title' => 'sample', 'name' => 'thing', 'email' => 'todo']); Post::create(['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'author_id' => 1]); Post::create(['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'author_id' => 1]); Comment::create(['id' => 1, 'comment' => 'Comment 1', 'post_id' => 1, 'author_id' => 1]); Comment::create(['id' => 2, 'comment' => 'Comment 2', 'post_id' => 1, 'author_id' => 2]); OtherComment::create(['id' => 1, 'comment' => 'Other Comment 1', 'post_id' => 1, 'author_id' => 1]); OtherComment::create(['id' => 2, 'comment' => 'Other Comment 2', 'post_id' => 1, 'author_id' => 2]); $models = Author::with(['posts', 'posts.comments', 'posts.comments.author', 'posts.otherComments', 'posts.otherComments.author'])->get(); $rules = [ 'models.*.title' => '', 'models.*.email' => '', 'models.*.posts.*.title' => '', 'models.*.posts.*.comments.*.comment' => '', 'models.*.posts.*.comments.*.author.name' => '', 'models.*.posts.*.otherComments.*.comment' => '', 'models.*.posts.*.otherComments.*.author.name' => '', ]; $expected = [ [ 'title' => 'foo', 'email' => 'baz', 'posts' => [ [ 'title' => 'Post 1', 'comments' => [ [ 'comment' => 'Comment 1', 'author' => [ 'name' => 'bar' ], ], [ 'comment' => 'Comment 2', 'author' => [ 'name' => 'thing' ], ], ], 'otherComments' => [ [ 'comment' => 'Other Comment 1', 'author' => [ 'name' => 'bar' ], ], [ 'comment' => 'Other Comment 2', 'author' => [ 'name' => 'thing' ], ], ], ], [ 'title' => 'Post 2', 'comments' => [], 'otherComments' => [], ], ], ], [ 'title' => 'sample', 'email' => 'todo', 'posts' => [], ], ]; $component = Livewire::test(ModelsComponent::class, ['models' => $models, 'rules' => $rules]); $results = $component->snapshot['data']['models'][0]; $this->assertEquals($expected[0]['title'], $results[0][0]['title']); $this->assertEquals($expected[0]['email'], $results[0][0]['email']); $this->assertEquals($expected[0]['posts'][0]['title'], $results[0][0]['posts'][0][0][0]['title']); $this->assertEquals($expected[0]['posts'][0]['comments'][0]['comment'], $results[0][0]['posts'][0][0][0]['comments'][0][0][0]['comment']); $this->assertEquals($expected[0]['posts'][0]['comments'][0]['author']['name'], $results[0][0]['posts'][0][0][0]['comments'][0][0][0]['author'][0]['name']); $this->assertEquals($expected[0]['posts'][0]['comments'][1]['comment'], $results[0][0]['posts'][0][0][0]['comments'][0][1][0]['comment']); $this->assertEquals($expected[0]['posts'][0]['comments'][1]['author']['name'], $results[0][0]['posts'][0][0][0]['comments'][0][1][0]['author'][0]['name']); $this->assertEquals($expected[0]['posts'][0]['otherComments'][0]['comment'], $results[0][0]['posts'][0][0][0]['otherComments'][0][0][0]['comment']); $this->assertEquals($expected[0]['posts'][0]['otherComments'][0]['author']['name'], $results[0][0]['posts'][0][0][0]['otherComments'][0][0][0]['author'][0]['name']); $this->assertEquals($expected[0]['posts'][0]['otherComments'][1]['comment'], $results[0][0]['posts'][0][0][0]['otherComments'][0][1][0]['comment']); $this->assertEquals($expected[0]['posts'][0]['otherComments'][1]['author']['name'], $results[0][0]['posts'][0][0][0]['otherComments'][0][1][0]['author'][0]['name']); $this->assertEquals($expected[0]['posts'][1]['title'], $results[0][0]['posts'][0][1][0]['title']); $this->assertEquals($expected[0]['posts'][1]['comments'], $results[0][0]['posts'][0][1][0]['comments'][0]); $this->assertEquals($expected[1]['title'], $results[1][0]['title']); $this->assertEquals($expected[1]['email'], $results[1][0]['email']); $this->assertEquals($expected[1]['posts'], $results[1][0]['posts'][0]); }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/ModelValidationUnitTest.php
src/Features/SupportLegacyModels/Tests/ModelValidationUnitTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Tests\TestComponent; use function Livewire\invade; use Illuminate\Database\Eloquent\Model; use Livewire\Livewire; use Sushi\Sushi; class ModelValidationUnitTest extends \Tests\TestCase { use Concerns\EnableLegacyModels; public function test_can_validate_uniqueness_on_a_model() { Livewire::test(ComponentWithRulesPropertyAndModelWithUniquenessValidation::class) ->set('foo.name', 'bar') ->call('save') ->assertHasErrors('foo.name') ->set('foo.name', 'blubber') ->call('save') ->assertHasNoErrors('foo.name'); } public function test_can_validate_uniqueness_on_a_model_but_exempt_the_model_itself() { Livewire::test(ComponentWithRulesPropertyAndModelUniquenessValidationWithIdExceptions::class) ->set('foo.email', 'baz@example.com') ->call('save') ->assertHasNoErrors('foo.email') ->set('foo.email', 'baz@example.com') ->call('save') ->assertHasNoErrors('foo.email') ->set('foo.email', 'bar@example.com') ->call('save') ->assertHasErrors('foo.email'); } } class FooModelForUniquenessValidation extends Model { use Sushi; protected $rows = [ ['name' => 'foo', 'email' => 'foo@example.com'], ['name' => 'bar', 'email' => 'bar@example.com'], ]; } class ComponentWithRulesPropertyAndModelWithUniquenessValidation extends TestComponent { public $foo; protected $rules = [ 'foo.name' => 'required|unique:foo-connection.foo_model_for_uniqueness_validations,name', ]; public function mount() { $this->foo = FooModelForUniquenessValidation::first(); } public function save() { // Sorry about this chunk of ridiculousness. It's Sushi's fault. $connection = $this->foo::resolveConnection(); $db = app('db'); $connections = invade($db)->connections; $connections['foo-connection'] = $connection; invade($db)->connections = $connections; $this->validate(); } } class ComponentWithRulesPropertyAndModelUniquenessValidationWithIdExceptions extends TestComponent { public $foo; protected function rules() { return [ 'foo.email' => 'unique:foo-connection.foo_model_for_uniqueness_validations,email,'.$this->foo->id ]; } public function mount() { $this->foo = FooModelForUniquenessValidation::first(); } public function save() { // Sorry about this chunk of ridiculousness. It's Sushi's fault. $connection = $this->foo::resolveConnection(); $db = app('db'); $connections = invade($db)->connections; $connections['foo-connection'] = $connection; invade($db)->connections = $connections; $this->validate(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/EloquentCollectionsBrowserTest.php
src/Features/SupportLegacyModels/Tests/EloquentCollectionsBrowserTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Illuminate\Database\Eloquent\Model; use Laravel\Dusk\Browser; use LegacyTests\Browser\TestCase; use Livewire\Component as BaseComponent; use Sushi\Sushi; class EloquentCollectionsBrowserTest extends TestCase { use Concerns\EnableLegacyModels; public function test_it_displays_all_nested_data() { $this->browse(function (Browser $browser) { $this->visitLivewireComponent($browser, EloquentCollectionsComponent::class) ->assertValue('@authors.0.name', 'Bob') ->assertValue('@authors.0.email', 'bob@bob.com') ->assertValue('@authors.0.posts.0.title', 'Post 1') ->assertValue('@authors.0.posts.0.comments.0.comment', 'Comment 1') ->assertValue('@authors.0.posts.0.comments.0.author.name', 'Bob') ->assertValue('@authors.0.posts.0.comments.1.comment', 'Comment 2') ->assertValue('@authors.0.posts.0.comments.1.author.name', 'John') ->assertValue('@authors.0.posts.1.title', 'Post 2') ->assertValue('@authors.1.name', 'John') ->assertValue('@authors.1.email', 'john@john.com') ; }); } public function test_it_allows_nested_data_to_be_changed() { $this->browse(function (Browser $browser) { $this->visitLivewireComponent($browser, EloquentCollectionsComponent::class) ->waitForLivewire()->type('@authors.0.name', 'Steve') ->assertSeeIn('@output.authors.0.name', 'Steve') ->waitForLivewire()->type('@authors.0.posts.0.title', 'Article 1') ->assertSeeIn('@output.authors.0.posts.0.title', 'Article 1') ->waitForLivewire()->type('@authors.0.posts.0.comments.0.comment', 'Message 1') ->assertSeeIn('@output.authors.0.posts.0.comments.0.comment', 'Message 1') ->waitForLivewire()->type('@authors.0.posts.0.comments.1.author.name', 'Mike') ->assertSeeIn('@output.authors.0.posts.0.comments.1.author.name', 'Mike') ->waitForLivewire()->click('@save') ->waitForLivewire()->type('@authors.1.name', 'Taylor') ->assertSeeIn('@output.authors.1.name', 'Taylor') ; }); $author = EloquentCollectionsAuthor::with(['posts', 'posts.comments', 'posts.comments.author'])->first(); $this->assertEquals('Steve', $author->name); $this->assertEquals('Article 1', $author->posts[0]->title); $this->assertEquals('Message 1', $author->posts[0]->comments[0]->comment); $this->assertEquals('Mike', $author->posts[0]->comments[1]->author->name); // Reset back after finished. $author->name = 'Bob'; $author->posts[0]->title = 'Post 1'; $author->posts[0]->comments[0]->comment = 'Comment 1'; $author->posts[0]->comments[1]->author->name = 'John'; $author->push(); } public function test_hydrate_works_properly_without_rules() { $this->browse(function (Browser $browser) { $this->visitLivewireComponent($browser, EloquentCollectionsWithoutRulesComponent::class) ->waitForLivewire()->click('@something') ->assertSeeIn('@output', 'Ok!'); ; }); } public function test_hydrate_works_properly_when_collection_is_empty() { $this->browse(function (Browser $browser) { $this->visitLivewireComponent($browser, EloquentCollectionsWithoutItemsComponent::class) ->waitForLivewire()->click('@something') ->assertSeeIn('@output', 'Ok!'); ; }); } } class EloquentCollectionsComponent extends BaseComponent { public $authors; protected $rules = [ 'authors.*.name' => '', 'authors.*.email' => '', 'authors.*.posts.*.title' => '', 'authors.*.posts.*.comments.*.comment' => '', 'authors.*.posts.*.comments.*.author.name' => '', ]; public function mount() { $this->authors = EloquentCollectionsAuthor::with(['posts', 'posts.comments', 'posts.comments.author'])->get(); } public function save() { $this->authors->each->push(); } public function render() { return <<<'HTML' <div> <button type="button" wire:click="$refresh">Refresh</button> @foreach($authors as $authorKey => $author) <div> <div> Author Name <input dusk='authors.{{ $authorKey }}.name' wire:model.live='authors.{{ $authorKey }}.name' /> <span dusk='output.authors.{{ $authorKey }}.name'>{{ $author->name }}</span> Author Email <input dusk='authors.{{ $authorKey }}.email' wire:model.live='authors.{{ $authorKey }}.email' /> <span dusk='output.authors.{{ $authorKey }}.email'>{{ $author->email }}</span> </div> <div> @foreach($author->posts as $postKey => $post) <div> Post Title <input dusk='authors.{{ $authorKey }}.posts.{{ $postKey }}.title' wire:model.live="authors.{{ $authorKey }}.posts.{{ $postKey }}.title" /> <span dusk='output.authors.{{ $authorKey }}.posts.{{ $postKey }}.title'>{{ $post->title }}</span> <div> @foreach($post->comments as $commentKey => $comment) <div> Comment Comment <input dusk='authors.{{ $authorKey }}.posts.{{ $postKey }}.comments.{{ $commentKey }}.comment' wire:model.live="authors.{{ $authorKey }}.posts.{{ $postKey }}.comments.{{ $commentKey }}.comment" /> <span dusk='output.authors.{{ $authorKey }}.posts.{{ $postKey }}.comments.{{ $commentKey }}.comment'>{{ $comment->comment }}</span> Commment Author Name <input dusk='authors.{{ $authorKey }}.posts.{{ $postKey }}.comments.{{ $commentKey }}.author.name' wire:model.live="authors.{{ $authorKey }}.posts.{{ $postKey }}.comments.{{ $commentKey }}.author.name" /> <span dusk='output.authors.{{ $authorKey }}.posts.{{ $postKey }}.comments.{{ $commentKey }}.author.name'>{{ optional($comment->author)->name }}</span> </div> @endforeach </div> </div> @endforeach </div> </div> @endforeach <button wire:click="save" type="button" dusk="save">Save</button> </div> HTML; } } class EloquentCollectionsWithoutRulesComponent extends EloquentCollectionsComponent { public $output; protected $rules = []; public function something() { $this->output = 'Ok!'; } public function render() { return <<<'HTML' <div> <div> @foreach($authors as $author) <p>{{ $author->name }}</p> @endforeach </div> <span dusk='output'>{{ $output }}</span> <button dusk='something' wire:click='something'>something</button> </div> HTML; } } class EloquentCollectionsWithoutItemsComponent extends BaseComponent { public $authors; public $output; protected $rules = []; public function mount() { $this->authors = EloquentCollectionsWithoutItems::get(); } public function something() { $this->output = 'Ok!'; } public function render() { return <<<'HTML' <div> <div> @foreach($authors as $author) <p>{{ $author->name }}</p> @endforeach </div> <span dusk='output'>{{ $output }}</span> <button dusk='something' wire:click='something'>something</button> </div> HTML; } } class EloquentCollectionsAuthor extends Model { use Sushi; protected $guarded = []; protected $rows = [ ['id' => 1, 'name' => 'Bob', 'email' => 'bob@bob.com'], ['id' => 2, 'name' => 'John', 'email' => 'john@john.com'], ]; public function posts() { return $this->hasMany(EloquentCollectionsPost::class); } public function comments() { return $this->hasMany(EloquentCollectionsComment::class); } } class EloquentCollectionsPost extends Model { use Sushi; protected $guarded = []; protected $rows = [ ['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'eloquent_collections_author_id' => 1], ['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'eloquent_collections_author_id' => 1], ]; public function author() { return $this->belongsTo(EloquentCollectionsAuthor::class, 'eloquent_collections_author_id'); } public function comments() { return $this->hasMany(EloquentCollectionsComment::class); } } class EloquentCollectionsComment extends Model { use Sushi; protected $guarded = []; protected $rows = [ ['id' => 1, 'comment' => 'Comment 1', 'eloquent_collections_post_id' => 1, 'eloquent_collections_author_id' => 1], ['id' => 2, 'comment' => 'Comment 2', 'eloquent_collections_post_id' => 1, 'eloquent_collections_author_id' => 2], ]; public function author() { return $this->belongsTo(EloquentCollectionsAuthor::class, 'eloquent_collections_author_id'); } public function post() { return $this->belongsTo(EloquentCollectionsPost::class, 'eloquent_collections_post_id'); } } class EloquentCollectionsWithoutItems extends Model { use Sushi; protected $guarded = []; protected $rows = []; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/ModelAttributesCanBeBoundDirectlyUnitTest.php
src/Features/SupportLegacyModels/Tests/ModelAttributesCanBeBoundDirectlyUnitTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Schema; use Livewire\Component; use Livewire\Features\SupportLegacyModels\CannotBindToModelDataWithoutValidationRuleException; use Livewire\Livewire; use Livewire\Mechanisms\HandleComponents\CorruptComponentPayloadException; use Tests\TestComponent; use function Livewire\invade; class ModelAttributesCanBeBoundDirectlyUnitTest extends \Tests\TestCase { use Concerns\EnableLegacyModels; public function setUp(): void { parent::setUp(); Schema::create('model_for_attribute_bindings', function ($table) { $table->bigIncrements('id'); $table->string('title'); $table->timestamps(); }); } public function test_can_set_a_model_attribute_and_save() { $model = ModelForAttributeBinding::create(['id' => 1, 'title' => 'foo']); Livewire::test(ComponentWithModelProperty::class, ['model' => $model]) ->assertSetStrict('model.title', 'foo') ->set('model.title', 'ba') ->assertSetStrict('model.title', 'ba') ->call('refreshModel') ->assertSetStrict('model.title', 'foo') ->set('model.title', 'ba') ->call('save') ->assertHasErrors('model.title') ->set('model.title', 'bar') ->call('save') ->call('refreshModel') ->assertSetStrict('model.title', 'bar'); } public function test_a_non_existant_eloquent_model_can_be_set() { $model = new ModelForAttributeBinding; Livewire::test(ComponentWithModelProperty::class, ['model' => $model]) ->assertNotSet('model.title', 'foo') ->set('model.title', 'i-exist-now') ->assertSetStrict('model.title', 'i-exist-now') ->call('save') ->assertSetStrict('model.title', 'i-exist-now'); $this->assertTrue(ModelForAttributeBinding::whereTitle('i-exist-now')->exists()); } public function test_cant_set_a_model_attribute_that_isnt_present_in_rules_array() { $this->expectException(CannotBindToModelDataWithoutValidationRuleException::class); $model = ModelForAttributeBinding::create(['id' => 1, 'title' => 'foo']); Livewire::test(ComponentWithModelProperty::class, ['model' => $model]) ->set('model.id', 2) ->assertSetStrict('model.id', null); } public function test_an_eloquent_models_meta_cannot_be_hijacked_by_tampering_with_data() { $this->expectException(CorruptComponentPayloadException::class); $model = ModelForAttributeBinding::create(['id' => 1, 'title' => 'foo']); ModelForAttributeBinding::create(['id' => 2, 'title' => 'bar']); $component = Livewire::test(ComponentWithModelProperty::class, ['model' => $model]); invade(invade($component)->lastState)->snapshot['data']['model'][1]['key'] = 2; $component->call('$refresh'); } public function test_an_eloquent_model_property_can_be_set_to_null() { $model = ModelForAttributeBinding::create(['id' => 1, 'title' => 'foo']); Livewire::test(ComponentWithModelProperty::class, ['model' => $model]) ->set('model', null) ->assertSuccessful(); } public function test_an_eloquent_model_property_can_be_set_to_boolean() { $model = ModelForAttributeBinding::create(['id' => 1, 'title' => 'foo']); Livewire::test(ComponentWithModelProperty::class, ['model' => $model]) ->set('model', false) ->assertSuccessful(); } } class ModelForAttributeBinding extends Model { protected $connection = 'testbench'; protected $guarded = []; } class ComponentWithModelProperty extends TestComponent { public $model; protected $rules = [ 'model.title' => 'required|min:3', ]; public function mount(ModelForAttributeBinding $model) { $this->model = $model; } public function save() { $this->validate(); $this->model->save(); } public function refreshModel() { $this->model->refresh(); } } class ComponentWithoutRulesArray extends TestComponent { public $model; public function mount(ModelForAttributeBinding $model) { $this->model = $model; } } class ComponentWithModelsProperty extends Component { public $models; public function mount($models) { $this->models = $models; } public function refresh() {} public function render() { return <<<'HTML' <div> @foreach ($models as $model) {{ $model->title }} @endforeach </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php
src/Features/SupportLegacyModels/Tests/EloquentModelValidationUnitTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Sushi\Sushi; use Livewire\Livewire; use Livewire\Component; use Illuminate\Database\Eloquent\Model; class EloquentModelValidationUnitTest extends \Tests\TestCase { use Concerns\EnableLegacyModels; // @todo: Fix model array keys now legacy models have been implemented public function test_standard_model_property() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.bar', '') ->call('save') ->assertHasErrors('foo.bar') ->set('foo.bar', 'baz') ->call('save') ->assertHasNoErrors(); $this->assertEquals('baz', $foo->fresh()->bar); } public function test_validate_message_doesnt_contain_dot_notation_if_property_is_model() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.bar', '') ->call('save') ->assertHasErrors('foo.bar', 'required') ->assertSee('The bar field is required.'); } public function test_validate_message_doesnt_contain_dot_notation_if_property_is_model_with_snake_cased_attribute() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.bar_baz', '') ->call('save') ->assertHasErrors('foo.bar_baz', 'required') ->assertSee('The bar baz field is required.'); } public function test_validate_message_doesnt_contain_dot_notation_if_property_is_camelcased_model() { Livewire::test(ComponentWithCamelCasedModelProperty::class, [ 'camelFoo' => $foo = CamelFoo::first(), ])->set('camelFoo.bar', '') ->call('save') ->assertHasErrors('camelFoo.bar', 'required') ->assertSee('The bar field is required.'); } public function test_validate_message_still_honors_original_custom_attributes_if_property_is_a_model() { app('translator')->addLines(['validation.required' => 'The :attribute field is required.'], 'en'); app('translator')->addLines(['validation.attributes.foo.bar' => 'plop'], 'en'); Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.bar', '') ->call('save') ->assertSee('The plop field is required.'); } public function test_validate_only_message_doesnt_contain_dot_notation_if_property_is_model() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.bar', '') ->call('performValidateOnly', 'foo.bar') ->assertHasErrors('foo.bar', 'required') ->assertSee('The bar field is required.'); } public function test_array_model_property() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.baz', ['bob']) ->call('save') ->assertHasErrors('foo.baz') ->set('foo.baz', ['bob', 'lob']) ->call('save') ->assertHasNoErrors(); $this->assertEquals(['bob', 'lob'], $foo->fresh()->baz); } public function test_array_wildcard_key_model_property_validation() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.bob', ['b', 'bbo']) ->call('save') ->assertHasErrors('foo.bob.*') ->set('foo.bob', ['bb', 'bbo']) ->call('save') ->assertHasNoErrors(); $this->assertEquals(['bb', 'bbo'], $foo->fresh()->bob); } public function test_array_index_key_model_property_validation() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.bob.0', 'b') ->call('save') ->assertHasErrors('foo.bob.*') ->set('foo.bob.0', 'bbo') ->call('save') ->assertHasNoErrors(); $this->assertEquals(['bbo'], $foo->fresh()->bob); } public function test_array_wildcard_key_with_key_after_model_property_validation() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.lob.law', [['blog' => 'glob']]) ->call('save') ->assertHasErrors('foo.lob.law.*.blog') ->set('foo.lob.law', [['blog' => 'globbbbb']]) ->call('save') ->assertHasNoErrors(); $this->assertEquals(['law' => [['blog' => 'globbbbb']]], $foo->fresh()->lob); } public function test_array_with_numerical_index_key_model_property_validation() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.lob.law.0', ['blog' => 'glob']) ->call('save') ->assertHasErrors(['foo.lob.law.*', 'foo.lob.law.*.blog']) ->set('foo.lob.law.0', ['blog' => 'globbbbb']) ->call('save') ->assertHasNoErrors(); $this->assertEquals(['law' => [['blog' => 'globbbbb']]], $foo->fresh()->lob); } public function test_array_wildcard_key_with_numeric_index_model_property_validation() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.lob.law.0.blog', 'glob') ->call('save') ->assertHasErrors('foo.lob.law.*.blog') ->set('foo.lob.law.0.blog', 'globbbbb') ->call('save') ->assertHasNoErrors(); $this->assertEquals(['law' => [['blog' => 'globbbbb']]], $foo->fresh()->lob); } public function test_array_wildcard_key_with_deep_numeric_index_model_property_validation() { Livewire::test(ComponentForEloquentModelHydrationMiddleware::class, [ 'foo' => $foo = Foo::first(), ])->set('foo.zap.0.0.name', 'ar') ->call('save') ->assertHasErrors('foo.zap.*.*.name') ->set('foo.zap.0.0.name', 'arise') ->call('save') ->assertHasNoErrors(); $this->assertEquals([[['name' => 'arise']]], $foo->fresh()->zap); } public function test_collection_model_property_validation_only_includes_relevant_error() { Livewire::test(ComponentForEloquentModelCollectionHydrationMiddleware::class, [ 'foos' => \collect()->pad(3, Foo::first()), ]) ->call('performValidateOnly', 'foos.0.bar_baz') ->assertHasErrors('foos.0.bar_baz') ->assertHasNoErrors('foos.1.bar_baz'); } public function test_collection_model_property_validation_only_includes_all_errors_when_using_wildcard() { Livewire::test(ComponentForEloquentModelCollectionHydrationMiddleware::class, [ 'foos' => \collect()->pad(3, Foo::first()), ]) ->call('performValidateOnly', 'foos.*.bar_baz') ->assertHasErrors('foos.0.bar_baz') ->assertHasErrors('foos.1.bar_baz'); } public function test_array_with_deep_nested_model_relationship_validation() { Livewire::test(ComponentForEloquentModelNestedHydrationMiddleware::class, [ 'cart' => $cart = Cart::with('items')->first(), ]) ->set('cart.items.0.title', 'sparkling') ->set('cart.items.1.title', 'sparkling') ->call('save') ->assertHasNoErrors(); $this->assertEquals('sparkling', $cart->fresh()->items[0]->title); } } class Foo extends Model { use Sushi; protected $casts = ['baz' => 'array', 'bob' => 'array', 'lob' => 'array', 'zap' => 'array']; protected function getRows() { return [[ 'bar' => 'rab', 'bar_baz' => 'zab_rab', 'baz' => json_encode(['zab', 'azb']), 'bob' => json_encode(['obb']), 'lob' => json_encode(['law' => []]), 'zap' => json_encode([]), ]]; } } class CamelFoo extends Model { use Sushi; protected function getRows() { return [[ 'bar' => 'baz', ]]; } } class ComponentWithCamelCasedModelProperty extends Component { public $camelFoo; protected $rules = [ 'camelFoo.bar' => 'required', ]; public function save() { $this->validate(); } public function render() { return \view('dump-errors'); } } class ComponentForEloquentModelHydrationMiddleware extends Component { public $foo; protected $rules = [ 'foo.bar' => 'required', 'foo.bar_baz' => 'required', 'foo.baz' => 'required|array|min:2', 'foo.bob.*' => 'required|min:2', 'foo.lob.law.*' => 'required|array', 'foo.lob.law.*.blog' => 'required|min:5', 'foo.zap.*.*.name' => 'required|min:3', ]; public function save() { $this->validate(); $this->foo->save(); } public function performValidateOnly($field) { $this->validateOnly($field); } public function render() { return \view('dump-errors'); } } class ComponentForEloquentModelCollectionHydrationMiddleware extends Component { public $foos; protected $rules = [ 'foos' => 'required', 'foos.*' => 'max:20', 'foos.*.bar_baz' => 'required|min:10', 'foos.*.bar' => 'required|min:10', ]; public function performValidateOnly($field) { $this->validateOnly($field); } public function render() { return \view('dump-errors'); } } class Items extends Model { use Sushi; protected $rows = [ ['title' => 'Lawn Mower', 'price' => '226.99', 'cart_id' => 1], ['title' => 'Leaf Blower', 'price' => '134.99', 'cart_id' => 1], ['title' => 'Rake', 'price' => '9.99', 'cart_id' => 1], ['title' => 'Lawn Mower', 'price' => '226.99', 'cart_id' => 2], ['title' => 'Leaf Blower', 'price' => '134.99', 'cart_id' => 2], ['title' => 'Lawn Mower', 'price' => '226.99', 'cart_id' => 3], ['title' => 'Leaf Blower', 'price' => '134.99', 'cart_id' => 3], ['title' => 'Rake', 'price' => '9.99', 'cart_id' => 3], ]; protected $schema = [ 'price' => 'float', ]; } class Cart extends Model { use Sushi; protected $rows = [ ['id' => 1, 'name' => 'Bob'], ['id' => 2, 'name' => 'John'], ['id' => 3, 'name' => 'Mark'], ]; public function items() { return $this->hasMany(Items::class, 'cart_id', 'id'); } } class ComponentForEloquentModelNestedHydrationMiddleware extends Component { public $cart; protected $rules = [ 'cart.items.*.title' => 'required', ]; public function save() { $this->validate(); $this->cart->items->each->save(); } public function render() { return \view('dump-errors'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/ModelCollectionAttributesCanBeBoundDirectlyUnitTest.php
src/Features/SupportLegacyModels/Tests/ModelCollectionAttributesCanBeBoundDirectlyUnitTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; use Livewire\Features\SupportLegacyModels\CannotBindToModelDataWithoutValidationRuleException; use Livewire\Livewire; use Livewire\Mechanisms\HandleComponents\CorruptComponentPayloadException; use Sushi\Sushi; use Tests\TestComponent; use function Livewire\invade; class ModelCollectionAttributesCanBeBoundDirectlyUnitTest extends \Tests\TestCase { use Concerns\EnableLegacyModels; public function test_can_set_a_model_attribute_inside_a_models_collection_and_save() { // Reset Sushi model. (new ModelForBinding)->resolveConnection()->getSchemaBuilder()->drop((new ModelForBinding)->getTable()); (new ModelForBinding)->migrate(); Livewire::test(ComponentWithModelCollectionProperty::class) ->assertSetStrict('models.0.title', 'foo') ->assertSnapshotSetStrict('models.0.title', 'foo') ->set('models.0.title', 'bo') ->assertSetStrict('models.0.title', 'bo') ->call('refreshModels') ->assertSetStrict('models.0.title', 'foo') ->set('models.0.title', 'bo') ->call('save') ->assertHasErrors('models.0.title') ->set('models.0.title', 'boo') ->call('save') ->call('refreshModels') ->assertSetStrict('models.0.title', 'boo'); } public function test_can_set_non_persisted_models_in_model_collection() { // Reset Sushi model. (new ModelForBinding)->resolveConnection()->getSchemaBuilder()->drop((new ModelForBinding)->getTable()); (new ModelForBinding)->migrate(); Livewire::test(ComponentWithModelCollectionProperty::class) ->assertSetStrict('models.2.title', 'baz') ->assertSetStrict('models.3', null) ->assertSnapshotSetStrict('models.3', null) ->call('addModel') ->assertNotSet('models.3', null) ->assertSnapshotNotSet('models.3', null) ->set('models.3.title', 'bob') ->assertSetStrict('models.3.title', 'bob') ->assertSnapshotSetStrict('models.3.title', 'bob') ->set('models.3.title', 'bo') ->call('refreshModels') ->assertSetStrict('models.3', null) ->assertSnapshotSetStrict('models.3', null) ->call('addModel') ->set('models.3.title', 'bo') ->call('save') ->assertHasErrors('models.3.title') ->set('models.3.title', 'boo') ->call('save') ->call('refreshModels') ->assertSetStrict('models.3.title', 'boo'); ; } public function test_can_use_a_custom_model_collection_and_bind_to_values() { // Reset Sushi model. (new ModelWithCustomCollectionForBinding)->resolveConnection()->getSchemaBuilder()->drop((new ModelWithCustomCollectionForBinding)->getTable()); (new ModelWithCustomCollectionForBinding)->migrate(); Livewire::test(ComponentWithModelCollectionProperty::class) ->call('setModelsToCustomCollection') ->assertSetStrict('models.0.title', 'foo') ->assertSnapshotSetStrict('models.0.title', 'foo') ->set('models.0.title', 'bo') ->assertSetStrict('models.0.title', 'bo') ->call('refreshModels') ->assertSetStrict('models.0.title', 'foo') ->set('models.0.title', 'bo') ->call('save') ->assertHasErrors('models.0.title') ->set('models.0.title', 'boo') ->call('save') ->call('refreshModels') ->assertSetStrict('models.0.title', 'boo') ->call('getTypeOfModels') ->assertSetStrict('modelsType', CustomCollection::class); } public function test_cant_set_a_model_attribute_that_isnt_present_in_rules_array() { // Reset Sushi model. (new ModelForBinding)->resolveConnection()->getSchemaBuilder()->drop((new ModelForBinding)->getTable()); (new ModelForBinding)->migrate(); $this->expectException(CannotBindToModelDataWithoutValidationRuleException::class); Livewire::test(ComponentWithModelCollectionProperty::class) ->set('models.1.restricted', 'bar') ->assertSetStrict('models.1.restricted', null); } public function test_an_eloquent_models_meta_cannot_be_hijacked_by_tampering_with_data() { // Reset Sushi model. (new ModelForBinding)->resolveConnection()->getSchemaBuilder()->drop((new ModelForBinding)->getTable()); (new ModelForBinding)->migrate(); $this->expectException(CorruptComponentPayloadException::class); $component = Livewire::test(ComponentWithModelCollectionProperty::class); invade(invade($component)->lastState)->snapshot['data']['models'][0]['id'] = 2; $component->call('$refresh'); } } class ModelForBinding extends Model { use Sushi; protected $rows = [ ['title' => 'foo'], ['title' => 'bar'], ['title' => 'baz'], ]; } class CustomCollection extends EloquentCollection { // } class ModelWithCustomCollectionForBinding extends Model { use Sushi; protected $rows = [ ['title' => 'foo'], ['title' => 'bar'], ['title' => 'baz'], ]; public function newCollection(array $models = []) { return new CustomCollection($models); } } class ComponentWithModelCollectionProperty extends TestComponent { public $models; public $modelsType; protected $rules = [ 'models.*.title' => 'required|min:3', ]; public function mount() { $this->models = ModelForBinding::all(); } public function addModel() { $this->models->push(new ModelForBinding); } public function setModelsToCustomCollection() { $this->models = ModelWithCustomCollectionForBinding::all(); } public function getTypeOfModels() { $this->modelsType = get_class($this->models); } public function save() { $this->validate(); $this->models->each->save(); } public function refreshModels() { $this->models = $this->models->filter->exists->fresh(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/ModelsCanBeFilledUnitTest.php
src/Features/SupportLegacyModels/Tests/ModelsCanBeFilledUnitTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Livewire\Livewire; use Illuminate\Database\Eloquent\Model; use Tests\TestComponent; class ModelsCanBeFilledUnitTest extends \Tests\TestCase { use Concerns\EnableLegacyModels; public function test_can_fill_binded_model_properties() { $component = Livewire::test(ComponentWithFillableProperties::class, ['user' => new UserModel()]); $this->assertInstanceOf(UserModel::class, $component->get('user')); $component ->assertSetStrict('user.name', null) ->call('callFill', [ 'user.name' => 'Caleb', ]) ->assertSetStrict('user.name', 'Caleb'); } } class UserModel extends Model { public $appends = [ 'publicProperty', 'protectedProperty', 'privateProperty', ]; public function getPublicPropertyAttribute() { return 'Caleb'; } public function getProtectedPropertyAttribute() { return 'protected'; } public function getPrivatePropertyAttribute() { return 'private'; } } class ComponentWithFillableProperties extends TestComponent { public $user; public function callFill($values) { $this->fill($values); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/TestableLivewireCanAssertModelUnitTest.php
src/Features/SupportLegacyModels/Tests/TestableLivewireCanAssertModelUnitTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Sushi\Sushi; use Livewire\Livewire; use Illuminate\Database\Eloquent\Model; use Tests\TestComponent; class TestableLivewireCanAssertModelUnitTest extends \Tests\TestCase { public function test_can_assert_model_property_value() { Livewire::test(PropertyTestingComponent::class, [ 'model' => ModelForPropertyTesting::first(), ]) ->assertSetStrict('model.foo.bar', 'baz'); } } class ModelForPropertyTesting extends Model { use Sushi; protected $casts = ['foo' => 'array']; protected function getRows() { return [ ['foo' => json_encode(['bar' => 'baz'])], ]; } } class PropertyTestingComponent extends TestComponent { public $model; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/EagerLoadingBrowserTest.php
src/Features/SupportLegacyModels/Tests/EagerLoadingBrowserTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Illuminate\Database\Eloquent\Model; use Laravel\Dusk\Browser; use LegacyTests\Browser\TestCase; use Livewire\Component as BaseComponent; use Sushi\Sushi; class EagerLoadingBrowserTest extends TestCase { use Concerns\EnableLegacyModels; public function test_it_restores_eloquent_colletion_eager_loaded_relations_on_hydrate() { $this->browse(function (Browser $browser) { $this->visitLivewireComponent($browser, EagerLoadComponent::class) ->assertSeeIn('@posts-comments-relation-loaded', 'true') ->waitForLivewire()->click('@refresh-server') ->assertSeeIn('@posts-comments-relation-loaded', 'true') ; }); } public function test_models_without_eager_loaded_relations_are_not_affected() { $this->browse(function (Browser $browser) { $this->visitLivewireComponent($browser, EagerLoadComponent::class) ->assertSeeIn('@comments-has-no-relations', 'true') ->waitForLivewire()->click('@refresh-server') ->assertSeeIn('@comments-has-no-relations', 'true') ; }); } } class EagerLoadComponent extends BaseComponent { public $posts; public $comments; public function mount() { $this->posts = EagerLoadPost::with('comments')->get(); $this->comments = EagerLoadComment::all(); } public function postsCommentsRelationIsLoaded() { return $this->posts->every(function ($post) { return $post->relationLoaded('comments'); }); } public function commentsHaveNoRelations() { return $this->comments->every(function ($comments) { return $comments->getRelations() === []; }); } public function render() { // ray($this->posts); return <<<'HTML' <div> <div dusk="posts-comments-relation-loaded"> {{ $this->postsCommentsRelationIsLoaded() ? 'true' : 'false' }} </div> <div dusk="comments-has-no-relations"> {{ $this->commentsHaveNoRelations() ? 'true' : 'false' }} </div> <button dusk="refresh-server" type="button" wire:click="$refresh">Refresh Server</button> </div> HTML; } } class EagerLoadPost extends Model { use Sushi; protected $rows = [ ['id' => 1, 'name' => 'post1'], ['id' => 2, 'name' => 'post2'], ]; public function comments() { return $this->hasMany(EagerLoadComment::class); } } class EagerLoadComment extends Model { use Sushi; protected $rows = [ ['comment' => 'comment1', 'eager_load_post_id' => 1], ['comment' => 'comment2', 'eager_load_post_id' => 1], ['comment' => 'comment3', 'eager_load_post_id' => 1], ['comment' => 'comment4', 'eager_load_post_id' => 1], ['comment' => 'comment5', 'eager_load_post_id' => 2], ['comment' => 'comment6', 'eager_load_post_id' => 2], ]; public function post() { return $this->belongsTo(EagerLoadPost::class); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/DataBindingModelsBrowserTest.php
src/Features/SupportLegacyModels/Tests/DataBindingModelsBrowserTest.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests; use Illuminate\Database\Eloquent\Model; use Laravel\Dusk\Browser; use LegacyTests\Browser\TestCase; use Livewire\Component as BaseComponent; use Sushi\Sushi; class DataBindingModelsBrowserTest extends TestCase { use Concerns\EnableLegacyModels; public function test_it_displays_all_nested_data() { $this->browse(function (Browser $browser) { $this->visitLivewireComponent($browser, DataBindingComponent::class) ->assertValue('@author.name', 'Bob') ->assertValue('@author.email', 'bob@bob.com') ->assertValue('@author.posts.0.title', 'Post 1') ->assertValue('@author.posts.0.comments.0.comment', 'Comment 1') ->assertValue('@author.posts.0.comments.0.author.name', 'Bob') ->assertValue('@author.posts.0.comments.1.comment', 'Comment 2') ->assertValue('@author.posts.0.comments.1.author.name', 'John') ->assertValue('@author.posts.1.title', 'Post 2') ; }); } public function test_it_enables_nested_data_to_be_changed() { $this->browse(function (Browser $browser) { $this->visitLivewireComponent($browser, DataBindingComponent::class) ->waitForLivewire()->type('@author.name', 'Steve') ->assertSeeIn('@output.author.name', 'Steve') ->waitForLivewire()->type('@author.posts.0.title', 'Article 1') ->assertSeeIn('@output.author.posts.0.title', 'Article 1') ->waitForLivewire()->type('@author.posts.0.comments.0.comment', 'Message 1') ->assertSeeIn('@output.author.posts.0.comments.0.comment', 'Message 1') ->waitForLivewire()->type('@author.posts.0.comments.1.author.name', 'Mike') ->assertSeeIn('@output.author.posts.0.comments.1.author.name', 'Mike') ->waitForLivewire()->click('@save') ; }); $author = DataBindingAuthor::with(['posts', 'posts.comments', 'posts.comments.author'])->first(); $this->assertEquals('Steve', $author->name); $this->assertEquals('Article 1', $author->posts[0]->title); $this->assertEquals('Message 1', $author->posts[0]->comments[0]->comment); $this->assertEquals('Mike', $author->posts[0]->comments[1]->author->name); // Reset back after finished. $author->name = 'Bob'; $author->posts[0]->title = 'Post 1'; $author->posts[0]->comments[0]->comment = 'Comment 1'; $author->posts[0]->comments[1]->author->name = 'John'; $author->push(); } public function test_it_enables_changing_model_attributes_that_have_not_been_initialized_using_entangle() { $this->browse(function (Browser $browser) { $this->visitLivewireComponent($browser, DataBindingComponent::class) ->waitForLivewire()->type('@post.title', 'Livewire is awesome') ->assertSeeIn('@output.post.title', 'Livewire is awesome'); }); } } class DataBindingComponent extends BaseComponent { public $author; public ?DataBindingPost $thepost; protected $rules = [ 'author.name' => '', 'author.email' => '', 'author.posts.*.title' => '', 'author.posts.*.comments.*.comment' => '', 'author.posts.*.comments.*.author.name' => '', 'thepost.title' => '', ]; public function mount() { $this->author = DataBindingAuthor::with(['posts', 'posts.comments', 'posts.comments.author'])->first(); $this->thepost = new DataBindingPost(); } public function save() { $this->author->push(); } public function render() { return <<<'HTML' <div> <div> Author Name <input dusk='author.name' wire:model.live='author.name' /> <span dusk='output.author.name'>{{ $author->name }}</span> Author Email <input dusk='author.email' wire:model.live='author.email' /> <span dusk='output.author.email'>{{ $author->email }}</span> </div> <div> @foreach($author->posts as $postKey => $post) <div> Post Title <input dusk='author.posts.{{ $postKey }}.title' wire:model.live="author.posts.{{ $postKey }}.title" /> <span dusk='output.author.posts.{{ $postKey }}.title'>{{ $post->title }}</span> <div> @foreach($post->comments as $commentKey => $comment) <div> Comment Comment <input dusk='author.posts.{{ $postKey }}.comments.{{ $commentKey }}.comment' wire:model.live="author.posts.{{ $postKey }}.comments.{{ $commentKey }}.comment" /> <span dusk='output.author.posts.{{ $postKey }}.comments.{{ $commentKey }}.comment'>{{ $comment->comment }}</span> Commment Author Name <input dusk='author.posts.{{ $postKey }}.comments.{{ $commentKey }}.author.name' wire:model.live="author.posts.{{ $postKey }}.comments.{{ $commentKey }}.author.name" /> <span dusk='output.author.posts.{{ $postKey }}.comments.{{ $commentKey }}.author.name'>{{ optional($comment->author)->name }}</span> </div> @endforeach </div> </div> @endforeach </div> <button wire:click="save" type="button" dusk="save">Save</button> <div x-data="{ title: @entangle('thepost.title').live }"> Post Title <input dusk='post.title' x-model='title' /> <span dusk='output.post.title'>{{ $thepost->title }}</span> </div> </div> HTML; } } class DataBindingAuthor extends Model { use Sushi; protected $guarded = []; protected $rows = [ ['id' => 1, 'name' => 'Bob', 'email' => 'bob@bob.com'], ['id' => 2, 'name' => 'John', 'email' => 'john@john.com'] ]; public function posts() { return $this->hasMany(DataBindingPost::class); } public function comments() { return $this->hasMany(DataBindingComment::class); } } class DataBindingPost extends Model { use Sushi; protected $guarded = []; protected $rows = [ ['id' => 1, 'title' => 'Post 1', 'description' => 'Post 1 Description', 'content' => 'Post 1 Content', 'data_binding_author_id' => 1], ['id' => 2, 'title' => 'Post 2', 'description' => 'Post 2 Description', 'content' => 'Post 2 Content', 'data_binding_author_id' => 1] ]; public function author() { return $this->belongsTo(DataBindingAuthor::class, 'data_binding_author_id'); } public function comments() { return $this->hasMany(DataBindingComment::class); } } class DataBindingComment extends Model { use Sushi; protected $guarded = []; protected $rows = [ ['id' => 1, 'comment' => 'Comment 1', 'data_binding_post_id' => 1, 'data_binding_author_id' => 1], ['id' => 2, 'comment' => 'Comment 2', 'data_binding_post_id' => 1, 'data_binding_author_id' => 2] ]; public function author() { return $this->belongsTo(DataBindingAuthor::class, 'data_binding_author_id'); } public function post() { return $this->belongsTo(DataBindingPost::class, 'data_binding_post_id'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportLegacyModels/Tests/Concerns/EnableLegacyModels.php
src/Features/SupportLegacyModels/Tests/Concerns/EnableLegacyModels.php
<?php namespace Livewire\Features\SupportLegacyModels\Tests\Concerns; trait EnableLegacyModels { // Enable model binding for these tests protected function getEnvironmentSetUp($app) { parent::getEnvironmentSetUp($app); $app['config']->set('livewire.legacy_model_binding', true); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportReleaseTokens/HandlesReleaseTokens.php
src/Features/SupportReleaseTokens/HandlesReleaseTokens.php
<?php namespace Livewire\Features\SupportReleaseTokens; trait HandlesReleaseTokens { // 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. public static function releaseToken(): string { return 'a'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportReleaseTokens/SupportReleaseTokens.php
src/Features/SupportReleaseTokens/SupportReleaseTokens.php
<?php namespace Livewire\Features\SupportReleaseTokens; use Livewire\ComponentHook; use function Livewire\on; class SupportReleaseTokens extends ComponentHook { public static function provide() { on('dehydrate', function ($component, $context) { $context->addMemo('release', ReleaseToken::generate($component)); }); // Use `snapshot-verified` to run the check before any component properties are hydrated // but after the snapshot has been verified to ensure it hasn't been tampered with... on('snapshot-verified', function ($snapshot) { ReleaseToken::verify($snapshot); }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportReleaseTokens/BrowserTest.php
src/Features/SupportReleaseTokens/BrowserTest.php
<?php namespace Livewire\Features\SupportReleaseTokens; use Livewire\Component; use Livewire\Livewire; use function Livewire\on; class BrowserTest extends \Tests\BrowserTestCase { public static function tweakApplicationHook() { return function () { on('request', function ($request) { ReleaseToken::$LIVEWIRE_RELEASE_TOKEN = 'bob'; }); }; } public function test_if_release_token_has_changed_it_should_show_the_page_expired_dialog() { Livewire::visit(new class extends Component { public function render() { return <<<'HTML' <div> <button wire:click="$refresh" dusk="refresh">Refresh</button> </div> HTML; } }) ->waitForLivewireToLoad() ->click('@refresh') // Wait for Livewire to respond, but dusk helper won't // work as dialog box is stopping further execution ->pause(300) ->assertDialogOpened("This page has expired.\nWould you like to refresh the page?") // Dismiss dialog so next tests run ->dismissDialog() ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportReleaseTokens/UnitTest.php
src/Features/SupportReleaseTokens/UnitTest.php
<?php namespace Livewire\Features\SupportReleaseTokens; use Livewire\Component; use Livewire\Exceptions\LivewireReleaseTokenMismatchException; use Livewire\Livewire; class UnitTest extends \Tests\TestCase { public function test_release_token_is_added_to_the_snapshot() { ReleaseToken::$LIVEWIRE_RELEASE_TOKEN = 'foo'; app('config')->set('livewire.release_token', 'bar'); $component = Livewire::test(ComponentWithReleaseToken::class); $this->assertEquals('foo-bar-baz', $component->snapshot['memo']['release']); } public function test_release_token_is_checked_on_subsequent_requests_and_passes_if_the_release_token_matches() { $this->withoutExceptionHandling(); ReleaseToken::$LIVEWIRE_RELEASE_TOKEN = 'foo'; app('config')->set('livewire.release_token', 'bar'); $component = Livewire::test(ComponentWithReleaseToken::class); $component->refresh() ->assertSuccessful(); } public function test_release_token_is_checked_on_subsequent_requests_and_fails_if_the_internal_livewire_release_token_does_not_match() { $this->withoutExceptionHandling(); $this->expectException(LivewireReleaseTokenMismatchException::class); ReleaseToken::$LIVEWIRE_RELEASE_TOKEN = 'foo'; app('config')->set('livewire.release_token', 'bar'); $component = Livewire::test(ComponentWithReleaseToken::class); ReleaseToken::$LIVEWIRE_RELEASE_TOKEN = 'bob'; $component->refresh() ->assertStatus(419); } public function test_release_token_is_checked_on_subsequent_requests_and_fails_if_the_application_release_token_does_not_match() { $this->withoutExceptionHandling(); $this->expectException(LivewireReleaseTokenMismatchException::class); ReleaseToken::$LIVEWIRE_RELEASE_TOKEN = 'foo'; app('config')->set('livewire.release_token', 'bar'); $component = Livewire::test(ComponentWithReleaseToken::class); ComponentWithReleaseToken::$releaseToken = 'bob'; $component->refresh() ->assertStatus(419); } } class ComponentWithReleaseToken extends Component { public static $releaseToken = 'baz'; public static function releaseToken(): string { return static::$releaseToken; } 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/src/Features/SupportReleaseTokens/ReleaseToken.php
src/Features/SupportReleaseTokens/ReleaseToken.php
<?php namespace Livewire\Features\SupportReleaseTokens; use Livewire\Exceptions\LivewireReleaseTokenMismatchException; class ReleaseToken { // 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. public static $LIVEWIRE_RELEASE_TOKEN = 'a'; static function verify($snapshot): void { $componentClass = app('livewire.factory')->resolveComponentClass($snapshot['memo']['name']); if (!isset($snapshot['memo']['release']) || $snapshot['memo']['release'] !== static::generate($componentClass)) { throw new LivewireReleaseTokenMismatchException; } } static function generate($componentOrComponentClass): string { $livewireReleaseToken = static::$LIVEWIRE_RELEASE_TOKEN; $appReleaseToken = app('config')->get('livewire.release_token', ''); $componentReleaseToken = method_exists($componentOrComponentClass, 'releaseToken') ? $componentOrComponentClass::releaseToken() : ''; return $livewireReleaseToken . '-' . $appReleaseToken . '-' . $componentReleaseToken; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportMultipleRootElementDetection/UnitTest.php
src/Features/SupportMultipleRootElementDetection/UnitTest.php
<?php namespace Livewire\Features\SupportMultipleRootElementDetection; use Tests\TestCase; use Livewire\Livewire; use Livewire\Component; class UnitTest extends TestCase { public function setUp(): void { \Livewire\LivewireManager::$v4 = false; parent::setUp(); } function test_two_or_more_root_elements_throws_an_error() { config()->set('app.debug', true); $this->expectException(MultipleRootElementsDetectedException::class); Livewire::test(new class extends Component { function render() { return <<<'HTML' <div> First element </div> <div> Second element </div> HTML; } }); } function test_allow_script_tags_as_second_element() { config()->set('app.debug', true); Livewire::test(new class extends Component { function render() { return <<<'HTML' <div> First element </div> <script> let foo = 'bar' </script> HTML; } })->assertSuccessful(); } function test_dont_throw_error_in_production_so_that_there_is_no_perf_penalty() { config()->set('app.debug', false); Livewire::test(new class extends Component { function render() { return <<<'HTML' <div> First element </div> <div> Second element </div> HTML; } })->assertSuccessful(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportMultipleRootElementDetection/SupportMultipleRootElementDetection.php
src/Features/SupportMultipleRootElementDetection/SupportMultipleRootElementDetection.php
<?php namespace Livewire\Features\SupportMultipleRootElementDetection; use Livewire\ComponentHook; use function Livewire\on; class SupportMultipleRootElementDetection extends ComponentHook { static function provide() { on('mount', function ($component) { if (! config('app.debug')) return; return function ($html) use ($component) { (new static)->warnAgainstMoreThanOneRootElement($component, $html); }; }); } function warnAgainstMoreThanOneRootElement($component, $html) { $count = $this->getRootElementCount($html); if ($count > 1) { throw new MultipleRootElementsDetectedException($component); } } function getRootElementCount($html) { $dom = new \DOMDocument(); @$dom->loadHTML($html); $body = $dom->getElementsByTagName('body')->item(0); $count = 0; foreach ($body->childNodes as $child) { if ($child->nodeType == XML_ELEMENT_NODE) { if ($child->tagName === 'script') continue; $count++; } } return $count; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportMultipleRootElementDetection/MultipleRootElementsDetectedException.php
src/Features/SupportMultipleRootElementDetection/MultipleRootElementsDetectedException.php
<?php namespace Livewire\Features\SupportMultipleRootElementDetection; use Livewire\Exceptions\BypassViewHandler; class MultipleRootElementsDetectedException extends \Exception { use BypassViewHandler; function __construct($component) { parent::__construct('Livewire only supports one HTML element per component. Multiple root elements detected for component: [' . $component->getName() . ']'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRedirects/TestsRedirects.php
src/Features/SupportRedirects/TestsRedirects.php
<?php namespace Livewire\Features\SupportRedirects; use Illuminate\Support\Str; use Livewire\Component; use PHPUnit\Framework\Assert as PHPUnit; trait TestsRedirects { public function assertRedirect($uri = null) { if (is_subclass_of($uri, Component::class)) { $uri = url()->action($uri); } if (! app('livewire')->isLivewireRequest()) { $this->lastState->getResponse()->assertRedirect($uri); return $this; } PHPUnit::assertArrayHasKey( 'redirect', $this->effects, 'Component did not perform a redirect.' ); if (! is_null($uri)) { PHPUnit::assertSame(url($uri), url($this->effects['redirect'])); } return $this; } public function assertRedirectContains($uri) { if (is_subclass_of($uri, Component::class)) { $uri = url()->action($uri); } if (! app('livewire')->isLivewireRequest()) { $this->lastState->getResponse()->assertRedirectContains($uri); return $this; } PHPUnit::assertArrayHasKey( 'redirect', $this->effects, 'Component did not perform a redirect.' ); PHPUnit::assertTrue( Str::contains($this->effects['redirect'], $uri), 'Redirect location ['.$this->effects['redirect'].'] does not contain ['.$uri.'].' ); return $this; } public function assertRedirectToRoute($name, $parameters = []) { $uri = route($name, $parameters); return $this->assertRedirect($uri); } public function assertNoRedirect() { PHPUnit::assertTrue(! isset($this->effects['redirect'])); return $this; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRedirects/Redirector.php
src/Features/SupportRedirects/Redirector.php
<?php namespace Livewire\Features\SupportRedirects; use Livewire\Component; use Illuminate\Routing\Redirector as BaseRedirector; class Redirector extends BaseRedirector { protected $component; public function to($path, $status = 302, $headers = [], $secure = null) { $this->component->redirect($this->generator->to($path, [], $secure)); return $this; } public function away($path, $status = 302, $headers = []) { return $this->to($path, $status, $headers); } public function with($key, $value = null) { $key = is_array($key) ? $key : [$key => $value]; foreach ($key as $k => $v) { $this->session->flash($k, $v); } return $this; } public function component(Component $component) { $this->component = $component; return $this; } public function response($to) { return $this->createRedirect($to, 302, []); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRedirects/HandlesRedirects.php
src/Features/SupportRedirects/HandlesRedirects.php
<?php namespace Livewire\Features\SupportRedirects; use function Livewire\store; trait HandlesRedirects { public function redirect($url, $navigate = false) { store($this)->set('redirect', $url); if ($navigate) store($this)->set('redirectUsingNavigate', true); $shouldSkipRender = ! config('livewire.render_on_redirect', false); $shouldSkipRender && $this->skipRender(); } public function redirectRoute($name, $parameters = [], $absolute = true, $navigate = false) { $this->redirect(route($name, $parameters, $absolute), $navigate); } public function redirectIntended($default = '/', $navigate = false) { $url = session()->pull('url.intended', $default); $this->redirect($url, $navigate); } public function redirectAction($name, $parameters = [], $absolute = true, $navigate = false) { $this->redirect(action($name, $parameters, $absolute), $navigate); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRedirects/BrowserTest.php
src/Features/SupportRedirects/BrowserTest.php
<?php namespace Livewire\Features\SupportRedirects; use Livewire\Attributes\On; use Tests\BrowserTestCase; use Livewire\Livewire; use Livewire\Component; use Livewire\Attributes\Reactive; use Illuminate\Support\Facades\Route; class BrowserTest extends BrowserTestCase { public function test_can_redirect() { Livewire::visit([new class extends Component { public function redirectToWebsite() { $this->redirect('https://livewire.laravel.com'); } public function render() { return <<<HTML <div> <button type="button" dusk="button" wire:click="redirectToWebsite">Redirect to Livewire</button> </div> HTML; } }]) ->waitForText('Redirect to Livewire') ->waitForLivewire()->click('@button') ->assertUrlIs('https://livewire.laravel.com/') ; } public function test_session_flash_persists_when_redirecting_from_request_with_multiple_components_in_the_same_request() { config()->set('session.driver', 'file'); Route::get('/redirect', RedirectComponent::class)->middleware('web'); Livewire::visit([ new class extends Component { public $foo = 0; public function doRedirect() { session()->flash('alert', 'Session flash data'); $this->redirect('/redirect'); } public function render() { return <<<'HTML' <div> <h1>Parent</h1> <button wire:click="doRedirect" dusk="button">Do redirect</button> <livewire:child :$foo /> </div> HTML; } }, 'child' => new class extends Component { #[Reactive] public $foo; public function render() { return <<<'HTML' <div> <label>Child</label> </div> HTML; } } ]) ->click('@button') ->waitForTextIn('@session-message', 'Session flash data'); } public function test_session_flash_clearing_on_subsequent_requests() { config()->set('session.driver', 'file'); Livewire::visit([ new class extends Component { public $foo = 0; public function mount() { session()->flash('alert', 'Session flash data'); } #[On('rerender')] public function rerender() { $this->foo++; } public function render() { return <<<'HTML' <div> <h1>Parent</h1> <div dusk="foo">{{$foo}}</div> <livewire:child /> <div dusk="session-message"> @if(session()->has('alert')) Flash exists @else Flash cleared @endif </div> </div> HTML; } }, 'child' => new class extends Component { public function rerenderParent() { $this->dispatch('rerender'); } public function render() { return <<<'HTML' <div> <button wire:click="rerenderParent" dusk="button">Make subsequent request</button> </div> HTML; } } ]) ->waitForTextIn('@foo', '0') ->waitForTextIn('@session-message', 'Flash exists') ->waitForLivewire()->click('@button') ->waitForTextIn('@foo', '1') ->waitForTextIn('@session-message', 'Flash cleared'); } } class RedirectComponent extends Component { public function render() { return <<<'HTML' <div> <h1>Redirected page</h1> <div dusk="session-message"> @session('alert') {{ $value }} @endsession </div> </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false