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/Drawer/ImplicitRouteBinding.php
src/Drawer/ImplicitRouteBinding.php
<?php namespace Livewire\Drawer; use Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException; use BackedEnum; use ReflectionClass; use ReflectionMethod; use Livewire\Component; use Illuminate\Support\Reflector; use Illuminate\Support\Collection; use Illuminate\Routing\Route; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Contracts\Routing\UrlRoutable; /** * This class mirrors the functionality of Laravel's Illuminate\Routing\ImplicitRouteBinding class. */ class ImplicitRouteBinding { protected $container; public function __construct($container) { $this->container = $container; } public function resolveAllParameters(Route $route, Component $component) { $params = $this->resolveMountParameters($route, $component); $props = $this->resolveComponentProps($route, $component); return $params->merge($props)->all(); } public function resolveMountParameters(Route $route, Component $component) { if (! method_exists($component, 'mount')) { return new Collection(); } // Cache the current route action (this callback actually), just to be safe. $cache = $route->getAction(); // We'll set the route action to be the "mount" method from the chosen // Livewire component, to get the proper implicit bindings. $route->uses(get_class($component).'@mount'); try { // This is normally handled in the "SubstituteBindings" middleware, but // because that middleware has already ran, we need to run them again. $this->container['router']->substituteImplicitBindings($route); $parameters = $route->resolveMethodDependencies($route->parameters(), new ReflectionMethod($component, 'mount')); // Restore the original route action... $route->setAction($cache); } catch(\Exception $e) { // Restore the original route action before an exception is thrown... $route->setAction($cache); throw $e; } return new Collection($parameters); } public function resolveComponentProps(Route $route, Component $component) { return $this->getPublicPropertyTypes($component) ->intersectByKeys($route->parametersWithoutNulls()) ->map(function ($className, $propName) use ($route) { // If typed public property, resolve the class if ($className) { $resolved = $this->resolveParameter($route, $propName, $className); // We'll also pass the resolved model back to the route // so that it can be used for any depending on bindings $route->setParameter($propName, $resolved); return $resolved; } // Otherwise, just return the route parameter return $route->parameter($propName); }); } public function getPublicPropertyTypes($component) { return collect(Utils::getPublicPropertiesDefinedOnSubclass($component)) ->map(function ($value, $name) use ($component) { return Reflector::getParameterClassName(new \ReflectionProperty($component, $name)); }); } protected function resolveParameter($route, $parameterName, $parameterClassName) { $parameterValue = $route->parameter($parameterName); if ($parameterValue instanceof UrlRoutable) { return $parameterValue; } if($enumValue = $this->resolveEnumParameter($parameterValue, $parameterClassName)) { return $enumValue; } $instance = $this->container->make($parameterClassName); $parent = $route->parentOfParameter($parameterName); if ($parent instanceof UrlRoutable && ($route->enforcesScopedBindings() || array_key_exists($parameterName, $route->bindingFields()))) { $model = $parent->resolveChildRouteBinding($parameterName, $parameterValue, $route->bindingFieldFor($parameterName)); } else { if ($route->allowsTrashedBindings()) { $model = $instance->resolveSoftDeletableRouteBinding($parameterValue, $route->bindingFieldFor($parameterName)); } else { $model = $instance->resolveRouteBinding($parameterValue, $route->bindingFieldFor($parameterName)); } } if (! $model) { throw (new ModelNotFoundException())->setModel(get_class($instance), [$parameterValue]); } return $model; } protected function resolveEnumParameter($parameterValue, $parameterClassName) { if ($parameterValue instanceof BackedEnum) { return $parameterValue; } if ((new ReflectionClass($parameterClassName))->isEnum()) { $enumValue = $parameterClassName::tryFrom($parameterValue); if (is_null($enumValue)) { throw new BackedEnumCaseNotFoundException($parameterClassName, $parameterValue); } return $enumValue; } return null; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Drawer/UnitTest.php
src/Drawer/UnitTest.php
<?php namespace Livewire\Drawer; use Livewire\Component; use Livewire\Exceptions\RootTagMissingFromViewException; use Livewire\Livewire; class UnitTest extends \Tests\TestCase { public function test_root_element_has_id_and_component_data() { $component = Livewire::test(ComponentRootHasIdAndDataStub::class); $this->assertTrue( str($component->html())->containsAll([$component->id(), 'foo']) ); } public function test_root_element_exists() { $this->expectException(RootTagMissingFromViewException::class); Livewire::test(ComponentRootExists::class); } public function test_component_data_stored_in_html_is_escaped() { $component = Livewire::test(ComponentRootHasIdAndDataStub::class); $this->assertStringContainsString( <<<EOT {&quot;string&quot;:&quot;foo&quot;,&quot;array&quot;:[[&quot;foo&quot;],{&quot;s&quot;:&quot;arr&quot;}],&quot;object&quot;:[{&quot;foo&quot;:&quot;bar&quot;},{&quot;s&quot;:&quot;arr&quot;}],&quot;number&quot;:1,&quot;quote&quot;:&quot;\&quot;&quot;,&quot;singleQuote&quot;:&quot;&#039;&quot;} EOT , $component->html() ); } public function test_if_element_is_a_comment_it_is_skipped_and_id_and_data_inserted_on_next_elemenet() { $component = Livewire::test(ComponentRootHasIdAndDataStub::class); // Test that HTML comment is preserved and span has wire:snapshot (attribute order agnostic) $html = $component->html(); $this->assertStringContainsString('<!-- Test comment <div>Commented out code</div> -->', $html); $this->assertStringContainsString('<span', $html); $this->assertStringContainsString('wire:snapshot', $html); } public function test_if_element_is_a_comment_and_contains_html_it_is_skipped_and_id_and_data_inserted_on_next_elemenet() { $component = Livewire::test(ComponentRootHasIdAndDataStub::class); // Test that HTML comment with HTML is preserved and span has wire:snapshot (attribute order agnostic) $html = $component->html(); $this->assertStringContainsString('<!-- Test comment <div>Commented out code</div> -->', $html); $this->assertStringContainsString('<span', $html); $this->assertStringContainsString('wire:snapshot', $html); } public function test_on_subsequent_renders_root_element_has_id_but_not_component_id() { $component = Livewire::test(ComponentRootHasIdAndDataStub::class); $component->call('$refresh'); $this->assertStringContainsString($component->id(), $component->html()); $this->assertStringNotContainsString('foo', $component->html()); } } class ComponentRootHasIdAndDataStub extends Component { public $string = 'foo'; public $array = ['foo']; public $object = ['foo' => 'bar']; public $number = 1; public $quote = '"'; public $singleQuote = "'"; public function render() { return app('view')->make('show-name', ['name' => str()->random(5)]); } } class ComponentRootExists extends Component { public function render() { return 'This all you got?!'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Drawer/Utils.php
src/Drawer/Utils.php
<?php namespace Livewire\Drawer; use Illuminate\Http\Request; use Livewire\Exceptions\RootTagMissingFromViewException; use Livewire\Features\SupportFileUploads\FileUploadConfiguration; use function Livewire\invade; class Utils extends BaseUtils { static function insertAttributesIntoHtmlRoot($html, $attributes) { $attributesFormattedForHtmlElement = static::stringifyHtmlAttributes($attributes); preg_match('/(?:\n\s*|^\s*)<([a-zA-Z0-9\-]+)/', $html, $matches, PREG_OFFSET_CAPTURE); throw_unless( count($matches), new RootTagMissingFromViewException ); $tagName = $matches[1][0]; $lengthOfTagName = strlen($tagName); $positionOfFirstCharacterInTagName = $matches[1][1]; return substr_replace( $html, ' '.$attributesFormattedForHtmlElement, $positionOfFirstCharacterInTagName + $lengthOfTagName, 0 ); } static function stringifyHtmlAttributes($attributes) { return collect($attributes) ->mapWithKeys(function ($value, $key) { return [$key => static::escapeStringForHtml($value)]; })->map(function ($value, $key) { return sprintf('%s="%s"', $key, $value); })->implode(' '); } static function escapeStringForHtml($subject) { if (is_string($subject) || is_numeric($subject)) { return htmlspecialchars($subject, ENT_QUOTES|ENT_SUBSTITUTE); } return htmlspecialchars(json_encode($subject), ENT_QUOTES|ENT_SUBSTITUTE); } static function pretendResponseIsFile($file, $contentType = 'application/javascript; charset=utf-8') { $lastModified = filemtime($file); return static::cachedFileResponse($file, $contentType, $lastModified, fn ($headers) => response()->file($file, $headers)); } static function pretendResponseIsFileFromString($content, $filemtime, $filename = 'generated', $contentType = 'application/javascript; charset=utf-8') { return static::cachedFileResponse($filename, $contentType, $filemtime, fn ($headers) => response($content, 200, $headers)); } static function pretendPreviewResponseIsPreviewFile($filename) { $file = FileUploadConfiguration::path($filename); $storage = FileUploadConfiguration::storage(); $mimeType = FileUploadConfiguration::mimeType($filename); $lastModified = FileUploadConfiguration::lastModified($file); return self::cachedFileResponse($filename, $mimeType, $lastModified, fn ($headers) => $storage->download($file, $filename, $headers)); } static private function cachedFileResponse($filename, $contentType, $lastModified, $downloadCallback) { $expires = strtotime('+1 year'); $cacheControl = 'public, max-age=31536000'; if (static::matchesCache($lastModified)) { return response('', 304, [ 'Expires' => static::httpDate($expires), 'Cache-Control' => $cacheControl, ]); } $headers = [ 'Content-Type' => $contentType, 'Expires' => static::httpDate($expires), 'Cache-Control' => $cacheControl, 'Last-Modified' => static::httpDate($lastModified), ]; if (str($filename)->endsWith('.br')) { $headers['Content-Encoding'] = 'br'; } return $downloadCallback($headers); } static function matchesCache($lastModified) { $ifModifiedSince = app(Request::class)->header('if-modified-since'); return $ifModifiedSince !== null && @strtotime($ifModifiedSince) === $lastModified; } static function httpDate($timestamp) { return sprintf('%s GMT', gmdate('D, d M Y H:i:s', $timestamp)); } static function containsDots($subject) { return str_contains($subject, '.'); } static function dotSegments($subject) { return explode('.', $subject); } static function beforeFirstDot($subject) { return head(explode('.', $subject)); } static function afterFirstDot($subject) : string { return str($subject)->after('.'); } static public function hasProperty($target, $property) { return property_exists($target, static::beforeFirstDot($property)); } static public function shareWithViews($name, $value) { $old = app('view')->shared($name, 'notfound'); app('view')->share($name, $value); return $revert = function () use ($name, $old) { if ($old === 'notfound') { unset(invade(app('view'))->shared[$name]); } else { app('view')->share($name, $old); } }; } static function generateBladeView($subject, $data = []) { if (! is_string($subject)) { return tap($subject)->with($data); } $component = new class($subject) extends \Illuminate\View\Component { protected $template; public function __construct($template) { $this->template = $template; } public function render() { return $this->template; } }; $view = app('view')->make($component->resolveView(), $data); return $view; } static function applyMiddleware(\Illuminate\Http\Request $request, $middleware = []) { $response = (new \Illuminate\Pipeline\Pipeline(app())) ->send($request) ->through($middleware) ->then(function() { return new \Illuminate\Http\Response(); }); if ($response instanceof \Illuminate\Http\RedirectResponse) { abort($response); } return $response; } static function extractAttributeDataFromHtml($html, $attribute) { $data = (string) str($html)->betweenFirst($attribute.'="', '"'); return json_decode( htmlspecialchars_decode($data, ENT_QUOTES|ENT_SUBSTITUTE), associative: true, ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Drawer/Regexes.php
src/Drawer/Regexes.php
<?php namespace Livewire\Drawer; class Regexes { static $livewireOpeningTag = " < \s* livewire[-\:]([\w\-\:\.]*) (?<attributes> (?: \s+ (?: (?: @(?:class)(\( (?: (?>[^()]+) | (?-1) )* \)) ) | (?: @(?:style)(\( (?: (?>[^()]+) | (?-1) )* \)) ) | (?: \{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\} ) | (?: (\:\\\$)(\w+) ) | (?: [\w\-:.@%]+ ( = (?: \\\"[^\\\"]*\\\" | \'[^\']*\' | [^\'\\\"=<>]+ ) )? ) ) )* \s* ) (?<![\/=\-]) > "; static $livewireOpeningTagOrSelfClosingTag = " < \s* livewire[-\:]([\w\-\:\.]*) (?<attributes> (?: \s+ (?: (?: @(?:class)(\( (?: (?>[^()]+) | (?-1) )* \)) ) | (?: @(?:style)(\( (?: (?>[^()]+) | (?-1) )* \)) ) | (?: \{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\} ) | (?: (\:\\\$)(\w+) ) | (?: [\w\-:.@%]+ ( = (?: \\\"[^\\\"]*\\\" | \'[^\']*\' | [^\'\\\"=<>]+ ) )? ) ) )* \s* ) \/?> "; static $livewireSelfClosingTag = " < \s* livewire[-\:]([\w\-\:\.]*) \s* (?<attributes> (?: \s+ (?: (?: @(?:class)(\( (?: (?>[^()]+) | (?-1) )* \)) ) | (?: @(?:style)(\( (?: (?>[^()]+) | (?-1) )* \)) ) | (?: \{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\} ) | (?: (\:\\\$)(\w+) ) | (?: [\w\-:.@%]+ ( = (?: \\\"[^\\\"]*\\\" | \'[^\']*\' | [^\'\\\"=<>]+ ) )? ) ) )* \s* ) \/> "; static $livewireClosingTag = '<\/\s*livewire[-\:][\w\-\:\.]*\s*>'; static $slotOpeningTag = " < \s* livewire[\-\:]slot (?:\:(?<inlineName>\w+(?:-\w+)*))? (?:\s+(:?)name=(?<name>(\"[^\"]+\"|\\\'[^\\\']+\\\'|[^\s>]+)))? (?<attributes> (?: \s+ (?: (?: @(?:class)(\( (?: (?>[^()]+) | (?-1) )* \)) ) | (?: @(?:style)(\( (?: (?>[^()]+) | (?-1) )* \)) ) | (?: \{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\} ) | (?: (\:\\\$)(\w+) ) | (?: [\w\-:.@%]+ ( = (?: \\\"[^\\\"]*\\\" | \'[^\']*\' | [^\'\\\"=<>]+ ) )? ) ) )* \s* ) (?<![\/=\-]) > "; static $slotClosingTag = '<\/\s*livewire[\-\:]slot[^>]*>'; static $bladeDirective = "\B@(@?\w+(?:::\w+)?)([ \t]*)(\( ( (?>[^()]+) | (?3) )* \))?"; static function specificBladeDirective($directive) { return "(@?$directive(?:::\w+)?)([ \t]*)(\( ( (?>[^()]+) | (?3) )* \))"; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Drawer/BaseUtils.php
src/Drawer/BaseUtils.php
<?php namespace Livewire\Drawer; class BaseUtils { protected static $reflectionCache = []; static function isSyntheticTuple($payload) { return is_array($payload) && count($payload) === 2 && isset($payload[1]['s']); } static function isAPrimitive($target) { return is_numeric($target) || is_string($target) || is_bool($target) || is_null($target); } static function getPublicPropertiesDefinedOnSubclass($target) { $class = get_class($target); if (!isset(static::$reflectionCache[$class])) { static::$reflectionCache[$class] = static::reflectAndCachePropertyMetadata($target, function ($property) { return $property->getDeclaringClass()->getName() !== \Livewire\Component::class && $property->getDeclaringClass()->getName() !== \Livewire\Volt\Component::class; }); } return static::extractPropertyValuesFromInstance($target, static::$reflectionCache[$class]); } protected static function reflectAndCachePropertyMetadata($target, $filter = null) { return collect((new \ReflectionObject($target))->getProperties()) ->filter(function ($property) { return $property->isPublic() && ! $property->isStatic() && $property->isDefault(); }) ->filter($filter ?? fn () => true) ->mapWithKeys(function ($property) { $type = null; if (method_exists($property, 'getType') && $property->getType()) { $type = method_exists($property->getType(), 'getName') ? $property->getType()->getName() : null; } return [$property->getName() => [ 'name' => $property->getName(), 'type' => $type, ]]; }) ->all(); } protected static function extractPropertyValuesFromInstance($target, $cachedMetadata) { $properties = []; $reflection = new \ReflectionObject($target); // One reflection object for all properties foreach ($cachedMetadata as $propertyName => $meta) { $property = $reflection->getProperty($propertyName); if (method_exists($property, 'isInitialized') && !$property->isInitialized($target)) { $value = ($meta['type'] === 'array') ? [] : null; } else { $value = $property->getValue($target); } $properties[$propertyName] = $value; } return $properties; } static function getPublicProperties($target, $filter = null) { return collect((new \ReflectionObject($target))->getProperties()) ->filter(function ($property) { return $property->isPublic() && ! $property->isStatic() && $property->isDefault(); }) ->filter($filter ?? fn () => true) ->mapWithKeys(function ($property) use ($target) { // Ensures typed property is initialized in PHP >=7.4, if so, return its value, // if not initialized, return null (as expected in earlier PHP Versions) if (method_exists($property, 'isInitialized') && !$property->isInitialized($target)) { // If a type of `array` is given with no value, let's assume users want // it prefilled with an empty array... $value = (method_exists($property, 'getType') && $property->getType() && method_exists($property->getType(), 'getName') && $property->getType()->getName() === 'array') ? [] : null; } else { $value = $property->getValue($target); } return [$property->getName() => $value]; }) ->all(); } static function getPublicMethodsDefinedBySubClass($target) { $methods = array_filter((new \ReflectionObject($target))->getMethods(), function ($method) { $isInBaseComponentClass = $method->getDeclaringClass()->getName() === \Livewire\Component::class || $method->getDeclaringClass()->getName() === \Livewire\Volt\Component::class; return $method->isPublic() && ! $method->isStatic() && ! $isInBaseComponentClass; }); return array_map(function ($method) { return $method->getName(); }, $methods); } static function hasAttribute($target, $property, $attributeClass) { $property = static::getProperty($target, $property); foreach ($property->getAttributes() as $attribute) { $instance = $attribute->newInstance(); if ($instance instanceof $attributeClass) return true; } return false; } static function getProperty($target, $property) { return (new \ReflectionObject($target))->getProperty($property); } static function propertyIsTyped($target, $property) { $property = static::getProperty($target, $property); return $property->hasType(); } static function propertyIsTypedAndUninitialized($target, $property) { $property = static::getProperty($target, $property); return $property->hasType() && (! $property->isInitialized($target)); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Drawer/Tests/ImplicitRouteBindingUnitTest.php
src/Drawer/Tests/ImplicitRouteBindingUnitTest.php
<?php namespace Livewire\Drawer\Tests; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Route; use Livewire\Component; use Livewire\Livewire; use Sushi\Sushi; class ImplicitRouteBindingUnitTest extends \Tests\TestCase { public function test_props_are_set_via_mount() { Livewire::test(ComponentWithPropBindings::class, [ 'model' => new PropBoundModel('mount-model'), ])->assertSeeText('prop:mount-model'); } public function test_props_are_set_via_implicit_binding() { Route::get('/foo/{model}', ComponentWithPropBindings::class); $this->withoutExceptionHandling()->get('/foo/route-model')->assertSeeText('prop:via-route:route-model'); } public function test_dependent_props_are_set_via_implicit_binding() { Route::get('/foo/{parent:custom}/bar/{child:custom}', ComponentWithDependentPropBindings::class); $this->get('/foo/robert/bar/bobby')->assertSeeText('prop:via-route:robert:via-parent:bobby'); } public function test_props_are_set_via_scope_binding() { Route::get('/scope-binding/{store:name}/{book:name}', ComponentWithScopeBindings::class)->scopeBindings(); $this->get('/scope-binding/First/Foo') ->assertSeeText('Store ID: 1') ->assertSeeText('Book ID: 1'); $this->get('/scope-binding/Second/Foo') ->assertSeeText('Store ID: 2') ->assertSeeText('Book ID: 2'); } public function test_dependent_props_are_set_via_mount() { Route::get('/foo/{parent:custom}/bar/{child:custom}', ComponentWithDependentMountBindings::class); $this->get('/foo/robert/bar/bobby')->assertSeeText('prop:via-route:robert:via-parent:bobby'); } public function test_props_and_mount_work_together() { Route::get('/foo/{parent}/child/{child}', ComponentWithPropBindingsAndMountMethod::class); // In the case that a parent is a public property, and a child is injected via mount(), // the result will *not* resolve via the relationship (it's super edge-case and makes everything terrible) $this->withoutExceptionHandling()->get('/foo/parent-model/child/child-model')->assertSeeText('via-route:parent-model:via-route:child-model'); } public function test_props_are_set_via_implicit_binding_when_with_trashed() { Route::get('/foo/{model}', ComponentWithTrashedPropBindings::class); $this->get('/foo/route-model') ->assertNotFound(); Route::get('/foo/with-trashed/{model}', ComponentWithTrashedPropBindings::class)->withTrashed(); $this->withoutExceptionHandling() ->get('/foo/with-trashed/route-model') ->assertSeeText('prop:via-route:trashed:route-model'); } public function test_props_are_set_via_implicit_binding_after_404() { Route::get('/foo/{user}', ComponentWithModelPropBindings::class); $this->get('/foo/404') ->assertNotFound(); $this->get('/foo/1') ->assertSeeText('prop:John'); } } class PropBoundModel extends Model { public $value; public function __construct($value = 'model-default') { $this->value = $value; } public function resolveRouteBinding($value, $field = null) { $this->value = "via-route:{$value}"; return $this; } public function resolveChildRouteBinding($childType, $value, $field) { return new static("via-parent:{$value}"); } } class ComponentWithPropBindings extends Component { public PropBoundModel $model; public $name; public function render() { $this->name = 'prop:'.$this->model->value; return app('view')->make('show-name-with-this'); } } class ComponentWithDependentPropBindings extends Component { public PropBoundModel $parent; public PropBoundModel $child; public $name; public function render() { $this->name = collect(['prop', $this->parent->value, $this->child->value])->implode(':'); return app('view')->make('show-name-with-this'); } } class ComponentWithPropBindingsAndMountMethod extends Component { public PropBoundModel $child; public $parent; public $name; public function mount(PropBoundModel $parent) { $this->parent = $parent; } public function render() { $this->name = "{$this->parent->value}:{$this->child->value}"; return app('view')->make('show-name-with-this'); } } class ComponentWithDependentMountBindings extends Component { public $parent; public $child; public $name; public function mount(PropBoundModel $parent, PropBoundModel $child) { $this->parent = $parent; $this->child = $child; } public function render() { $this->name = collect(['prop', $this->parent->value, $this->child->value])->implode(':'); return app('view')->make('show-name-with-this'); } } class PropBoundModelWithSoftDelete extends Model { use SoftDeletes; public $value; public function __construct($value = 'model-default') { $this->value = $value; } public function resolveRouteBinding($value, $field = null) { return null; } public function resolveSoftDeletableRouteBinding($value, $field = null) { $this->value = "via-route:trashed:{$value}"; return $this; } } class ComponentWithTrashedPropBindings extends Component { public PropBoundModelWithSoftDelete $model; public $name; public function render() { $this->name = 'prop:'.$this->model->value; return app('view')->make('show-name-with-this'); } } class ComponentWithModelPropBindings extends Component { public User $user; public function mount(User $user) { $this->user = $user; } public function render() { $this->name = 'prop:'.$this->user->name; return app('view')->make('show-name-with-this'); } } class User extends Model { use Sushi; protected array $schema = [ 'id' => 'integer', 'name' => 'string', ]; protected array $rows = [ [ 'id' => 1, 'name' => 'John', ], ]; } class ComponentWithScopeBindings extends Component { public Store $store; public Book $book; public function render() { return <<<'BLADE' <div> Store ID: {{ $store->id }} Book ID: {{ $book->id }} </div> BLADE; } } class Store extends Model { use Sushi; protected array $schema = [ 'id' => 'integer', 'name' => 'string', ]; protected array $rows = [ [ 'id' => 1, 'name' => 'First', ], [ 'id' => 2, 'name' => 'Second', ], ]; public function books() : HasMany { return $this->hasMany(Book::class); } } class Book extends Model { use Sushi; protected array $schema = [ 'id' => 'integer', 'store_id' => 'integer', 'name' => 'string', ]; protected array $rows = [ [ 'id' => 1, 'store_id' => 1, 'name' => 'Foo', ], [ 'id' => 2, 'store_id' => 2, 'name' => 'Foo', ], ]; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Concerns/InteractsWithProperties.php
src/Concerns/InteractsWithProperties.php
<?php namespace Livewire\Concerns; use Illuminate\Database\Eloquent\Model; use Livewire\Drawer\Utils; use Livewire\Form; trait InteractsWithProperties { public function hasProperty($prop) { return property_exists($this, Utils::beforeFirstDot($prop)); } public function getPropertyValue($name) { $value = $this->{Utils::beforeFirstDot($name)}; if (Utils::containsDots($name)) { return data_get($value, Utils::afterFirstDot($name)); } return $value; } public function fill($values) { $publicProperties = array_keys($this->all()); if ($values instanceof Model) { $values = $values->toArray(); } foreach ($values as $key => $value) { if (in_array(Utils::beforeFirstDot($key), $publicProperties)) { data_set($this, $key, $value); } } } public function reset(...$properties) { $properties = count($properties) && is_array($properties[0]) ? $properties[0] : $properties; // Reset all if (empty($properties)) { $properties = array_keys($this->all()); } $freshInstance = new static; foreach ($properties as $property) { $property = str($property); // Check if the property contains a dot which means it is actually on a nested object like a FormObject if (str($property)->contains('.')) { $propertyName = $property->afterLast('.'); $objectName = $property->before('.'); // form object reset if (is_subclass_of($this->{$objectName}, Form::class)) { $this->{$objectName}->reset($propertyName); continue; } $object = data_get($freshInstance, $objectName, null); if (is_object($object)) { $isInitialized = (new \ReflectionProperty($object, (string) $propertyName))->isInitialized($object); } else { $isInitialized = false; } } else { $isInitialized = (new \ReflectionProperty($freshInstance, (string) $property))->isInitialized($freshInstance); } // Handle resetting properties that are not initialized by default. if (! $isInitialized) { data_forget($this, (string) $property); continue; } data_set($this, $property, data_get($freshInstance, $property)); } } protected function resetExcept(...$properties) { if (count($properties) && is_array($properties[0])) { $properties = $properties[0]; } $keysToReset = array_diff(array_keys($this->all()), $properties); if($keysToReset === []) { return; } $this->reset($keysToReset); } public function pull($properties = null) { $wantsASingleValue = is_string($properties); $properties = is_array($properties) ? $properties : func_get_args(); $beforeReset = match (true) { empty($properties) => $this->all(), $wantsASingleValue => $this->getPropertyValue($properties[0]), default => $this->only($properties), }; $this->reset($properties); return $beforeReset; } public function only($properties) { $results = []; foreach (is_array($properties) ? $properties : func_get_args() as $property) { $results[$property] = $this->hasProperty($property) ? $this->getPropertyValue($property) : null; } return $results; } public function except($properties) { $properties = is_array($properties) ? $properties : func_get_args(); return array_diff_key($this->all(), array_flip($properties)); } public function all() { return Utils::getPublicPropertiesDefinedOnSubclass($this); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Concerns/Tests/ComponentCanReturnPublicPropertiesUnitTest.php
src/Concerns/Tests/ComponentCanReturnPublicPropertiesUnitTest.php
<?php namespace Livewire\Concerns\Tests; use Livewire\Livewire; use Tests\TestComponent; class ComponentCanReturnPublicPropertiesUnitTest extends \Tests\TestCase { public function test_a_livewire_component_can_return_an_associative_array_of_public_properties() { Livewire::test(ComponentWithProperties::class) ->call('setAllProperties') ->assertSetStrict('allProperties', [ 'onlyProperties' => [], 'exceptProperties' => [], 'allProperties' => [], 'foo' => 'Foo', 'bar' => 'Bar', 'baz' => 'Baz', ]) ->call('setOnlyProperties', ['foo', 'bar']) ->assertSetStrict('onlyProperties', [ 'foo' => 'Foo', 'bar' => 'Bar', ]) ->call('setExceptProperties', ['foo', 'onlyProperties', 'exceptProperties', 'allProperties']) ->assertSetStrict('exceptProperties', [ 'bar' => 'Bar', 'baz' => 'Baz', ]); } } class ComponentWithProperties extends TestComponent { public $onlyProperties = []; public $exceptProperties = []; public $allProperties = []; public $foo = 'Foo'; public $bar = 'Bar'; public $baz = 'Baz'; public function setOnlyProperties($properties) { $this->onlyProperties = $this->only($properties); } public function setExceptProperties($properties) { $this->exceptProperties = $this->except($properties); } public function setAllProperties() { $this->allProperties = $this->all(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Concerns/Tests/ComponentCanBeFilledUnitTest.php
src/Concerns/Tests/ComponentCanBeFilledUnitTest.php
<?php namespace Livewire\Concerns\Tests; use Livewire\Component; use Livewire\Livewire; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Blade; class ComponentCanBeFilledUnitTest extends \Tests\TestCase { public function test_can_fill_from_an_array() { $component = Livewire::test(ComponentWithFillableProperties::class); $component->assertSee('public'); $component->assertSee('protected'); $component->assertSee('private'); $component->call('callFill', [ 'publicProperty' => 'Caleb', 'protectedProperty' => 'Caleb', 'privateProperty' => 'Caleb', ]); $component->assertSee('Caleb'); $component->assertSee('protected'); $component->assertSee('private'); } public function test_can_fill_from_an_object() { $component = Livewire::test(ComponentWithFillableProperties::class); $component->assertSee('public'); $component->assertSee('protected'); $component->assertSee('private'); $component->call('callFill', new User()); $component->assertSee('Caleb'); $component->assertSee('protected'); $component->assertSee('private'); } public function test_can_fill_from_an_eloquent_model() { $component = Livewire::test(ComponentWithFillableProperties::class); $component->assertSee('public'); $component->assertSee('protected'); $component->assertSee('private'); $component->call('callFill', new UserModel()); $component->assertSee('Caleb'); $component->assertSee('protected'); $component->assertSee('private'); } public function test_can_fill_using_dot_notation() { Livewire::test(ComponentWithFillableProperties::class) ->assertSetStrict('dotProperty', []) ->call('callFill', [ 'dotProperty.foo' => 'bar', 'dotProperty.bob' => 'lob', ]) ->assertSetStrict('dotProperty.foo', 'bar') ->assertSetStrict('dotProperty.bob', 'lob'); } } class User { public $publicProperty = 'Caleb'; public $protectedProperty = 'Caleb'; public $privateProperty = '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 Component { public $publicProperty = 'public'; protected $protectedProperty = 'protected'; private $privateProperty = 'private'; public $dotProperty = []; public function callFill($values) { $this->fill($values); } public function render() { return Blade::render( <<<'HTML' <div> {{ $publicProperty }} {{ $protectedProperty }} {{ $privateProperty }} </div> HTML, [ 'publicProperty' => $this->publicProperty, 'protectedProperty' => $this->protectedProperty, 'privateProperty' => $this->privateProperty, ] ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Concerns/Tests/ResetPropertiesUnitTest.php
src/Concerns/Tests/ResetPropertiesUnitTest.php
<?php namespace Livewire\Concerns\Tests; use Livewire\Livewire; use Tests\TestComponent; class ResetPropertiesUnitTest extends \Tests\TestCase { public function test_can_reset_properties() { Livewire::test(ResetPropertiesComponent::class) ->assertSetStrict('foo', 'bar') ->assertSetStrict('bob', 'lob') ->assertSetStrict('mwa', 'hah') ->set('foo', 'baz') ->set('bob', 'law') ->set('mwa', 'aha') ->assertSetStrict('foo', 'baz') ->assertSetStrict('bob', 'law') ->assertSetStrict('mwa', 'aha') // Reset all. ->call('resetAll') ->assertSetStrict('foo', 'bar') ->assertSetStrict('bob', 'lob') ->assertSetStrict('mwa', 'hah') ->set('foo', 'baz') ->set('bob', 'law') ->set('mwa', 'aha') ->assertSetStrict('foo', 'baz') ->assertSetStrict('bob', 'law') ->assertSetStrict('mwa', 'aha') // Reset foo and bob. ->call('resetKeys', ['foo', 'bob']) ->assertSetStrict('foo', 'bar') ->assertSetStrict('bob', 'lob') ->assertSetStrict('mwa', 'aha') ->set('foo', 'baz') ->set('bob', 'law') ->set('mwa', 'aha') ->assertSetStrict('foo', 'baz') ->assertSetStrict('bob', 'law') ->assertSetStrict('mwa', 'aha') // Reset only foo. ->call('resetKeys', 'foo') ->assertSetStrict('foo', 'bar') ->assertSetStrict('bob', 'law') ->assertSetStrict('mwa', 'aha') ->set('foo', 'baz') ->set('bob', 'law') ->set('mwa', 'aha') ->assertSetStrict('foo', 'baz') ->assertSetStrict('bob', 'law') ->assertSetStrict('mwa', 'aha') // Reset all except foo. ->call('resetKeysExcept', 'foo') ->assertSetStrict('foo', 'baz') ->assertSetStrict('bob', 'lob') ->assertSetStrict('mwa', 'hah') ->set('foo', 'baz') ->set('bob', 'law') ->set('mwa', 'aha') ->assertSetStrict('foo', 'baz') ->assertSetStrict('bob', 'law') ->assertSetStrict('mwa', 'aha') // Reset all except foo and bob. ->call('resetKeysExcept', ['foo', 'bob']) ->assertSetStrict('foo', 'baz') ->assertSetStrict('bob', 'law') ->assertSetStrict('mwa', 'hah') // Reset all except all ->call('resetKeysExcept', ['foo', 'bob', 'mwa', 'notSet', 'nullProp', 'pullResult']) ->assertSetStrict('foo', 'baz') ->assertSetStrict('bob', 'law') ->assertSetStrict('mwa', 'hah'); } public function test_can_reset_unset_properties() { $component = Livewire::test(ResetPropertiesComponent::class) ->set('notSet', 1) ->assertSetStrict('notSet', 1) // Reset only notSet. ->call('resetKeys', 'notSet'); $this->assertFalse(isset($component->notSet)); } public function test_can_reset_null_properties() { $component = Livewire::test(ResetPropertiesComponent::class) ->set('nullProp', 1) ->assertSetStrict('nullProp', 1) // Reset only nullProp. ->call('resetKeys', 'nullProp') ->assertSetStrict('nullProp', null); $this->assertTrue(is_null($component->nullProp)); } public function test_can_reset_array_properties() { $component = Livewire::test(ResetPropertiesComponent::class) ->set('arrayProp', ['bar']) ->assertSetStrict('arrayProp', ['bar']) ->call('resetKeys', 'arrayProp'); $this->assertTrue($component->arrayProp === []); } public function test_can_reset_nested_array_properties() { $component = Livewire::test(ResetPropertiesComponent::class) ->set('nestedArrayProp.foo', 'bar') ->assertSetStrict('nestedArrayProp.foo', 'bar') ->call('resetKeys', 'nestedArrayProp.foo'); $this->assertTrue(!array_key_exists('foo', $component->nestedArrayProp)); } public function test_can_reset_and_return_property_with_pull_method() { $component = Livewire::test(ResetPropertiesComponent::class) ->assertSetStrict('foo', 'bar') ->set('foo', 'baz') ->assertSetStrict('foo', 'baz') ->assertSetStrict('pullResult', null) ->call('proxyPull', 'foo') ->assertSetStrict('foo', 'bar') ->assertSetStrict('pullResult', 'baz'); } public function test_can_pull_all_properties() { $component = Livewire::test(ResetPropertiesComponent::class) ->assertSetStrict('foo', 'bar') ->set('foo', 'baz') ->assertSetStrict('foo', 'baz') ->assertSetStrict('pullResult', null) ->call('proxyPull'); $this->assertEquals('baz', $component->pullResult['foo']); $this->assertEquals('lob', $component->pullResult['bob']); } public function test_can_pull_some_properties() { $component = Livewire::test(ResetPropertiesComponent::class) ->assertSetStrict('foo', 'bar') ->set('foo', 'baz') ->assertSetStrict('foo', 'baz') ->assertSetStrict('pullResult', null) ->call('proxyPull', ['foo']); $this->assertEquals('baz', $component->pullResult['foo']); $this->assertFalse(array_key_exists('bob', $component->pullResult)); } } class ResetPropertiesComponent extends TestComponent { public $foo = 'bar'; public $bob = 'lob'; public $mwa = 'hah'; public int $notSet; public ?int $nullProp = null; public $pullResult = null; public array $arrayProp = []; public array $nestedArrayProp = [ 'foo' => '', ]; public function resetAll() { $this->reset(); } public function resetKeys($keys) { $this->reset($keys); } public function resetKeysExcept($keys) { $this->resetExcept($keys); } public function proxyPull(...$args) { $this->pullResult = $this->pull(...$args); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/AlpineUiBrowserTest.php
src/Tests/AlpineUiBrowserTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; class AlpineUiBrowserTest extends \Tests\BrowserTestCase { public function test_component_with_listbox_and_wire_model_live_should_not_cause_infinite_loop() { Livewire::visit(new class extends Component { public ?array $foo = null; function render() { return <<<'HTML' <div> <script src="https://unpkg.com/@alpinejs/ui@3.13.4-beta.0/dist/cdn.min.js"></script> <button wire:click="$refresh">refresh</button> <div x-data="{ value: null, frameworks: [{ id: 1, name: 'Laravel', disabled: false, }], updates: 0, }" x-modelable="value" wire:model.live="foo" x-effect="console.log(value); updates++"> <div>updates: <span x-text="updates" dusk="updatesCount"></span></div> <div x-listbox x-model="value"> <label x-listbox:label>Backend framework</label> <button x-listbox:button dusk="openListbox"> <span x-text="value ? value.name : 'Select framework'"></span> </button> <ul x-listbox:options x-cloak> <template x-for="framework in frameworks" :key="framework.id"> <li x-listbox:option :value="framework" :disabled="framework.disabled" dusk="listboxOption"> <span x-text="framework.name"></span> </li> </template> </ul> </div> </div> </div> HTML; } }) ->waitForLivewireToLoad() ->click('@openListbox') ->assertSeeIn('@updatesCount', '1') ->pressAndWaitFor('@listboxOption', 250) ->assertSeeIn('@updatesCount', '2') ; } public function test_component_with_combobox_and_wire_model_live_should_not_cause_infinite_loop() { Livewire::visit(new class extends Component { public ?array $value = null; function render() { return <<<'HTML' <div> <script src="https://unpkg.com/@alpinejs/ui@3.13.4-beta.0/dist/cdn.min.js"></script> <div x-data="{ query: '', selected: null, frameworks: [{ id: 1, name: 'Laravel', disabled: false, }, ], get filteredFrameworks() { return this.query === '' ? this.frameworks : this.frameworks.filter((framework) => { return framework.name.toLowerCase().includes(this.query.toLowerCase()) }) }, updates: 0, }" x-modelable="selected" wire:model.live="value" x-effect="console.log(selected); updates++"> <div>updates: <span x-text="updates" dusk="updatesCount"></span></div> <div x-combobox x-model="selected"> <div> <div> <input x-combobox:input :display-value="framework => framework?.name" @change="query = $event.target.value;" placeholder="Search..." /> <button x-combobox:button dusk="openCombobox"> open combobox </button> </div> <div x-combobox:options x-cloak> <ul> <template x-for="framework in filteredFrameworks" :key="framework.id" hidden> <li x-combobox:option :value="framework" :disabled="framework.disabled" dusk="comboboxOption"> <span x-text="framework.name"></span> </li> </template> </ul> <p x-show="filteredFrameworks.length == 0">No frameworks match your query.</p> </div> </div> </div> </div> </div> HTML; } }) ->waitForLivewireToLoad() ->click('@openCombobox') ->assertSeeIn('@updatesCount', '1') ->pressAndWaitFor('@comboboxOption', 250) ->assertSeeIn('@updatesCount', '2') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/ComponentUsesCustomNameUnitTest.php
src/Tests/ComponentUsesCustomNameUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Livewire; use Tests\TestComponent; class ComponentUsesCustomNameUnitTest extends \Tests\TestCase { public function test_uses_default_component_name() { $component = Livewire::test(UsesDefaultComponentName::class); $this->assertEquals('Hello World', $component->get('name')); $this->assertNotEquals('Hello World', $component->instance()->getName()); } public function test_preserves_name_property() { $component = Livewire::test(PreservesNameProperty::class); $this->assertEquals('Hello World', $component->get('name')); $this->assertEquals('uses-custom-name', $component->instance()->getName()); } } class UsesDefaultComponentName extends TestComponent { public $name = 'Hello World'; } class PreservesNameProperty extends TestComponent { public $name = 'Hello World'; public function getName() { return 'uses-custom-name'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/LivewireAssetsDirectiveUnitTest.php
src/Tests/LivewireAssetsDirectiveUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Livewire; use Illuminate\Support\Facades\View; class LivewireAssetsDirectiveUnitTest extends \Tests\TestCase { function setUp(): void { $this->markTestSkipped('not sure exactly how we want to handle all this asset stuff for v3 so holding off on this...'); } public function test_livewire_js_is_unminified_when_app_is_in_debug_mode() { config()->set('app.debug', true); $this->assertStringContainsString( '<script src="/livewire/livewire.js?', Livewire::scripts() ); $this->assertStringContainsString( "window.livewire_app_url = '';", Livewire::scripts() ); } public function livewire_js_should_use_configured_app_url() { config()->set('app.debug', true); config()->set('livewire.app_url', 'https://foo.com'); $this->assertStringContainsString( '<script src="/livewire/livewire.js?', Livewire::scripts() ); $this->assertStringContainsString( "window.livewire_app_url = 'https://foo.com';", Livewire::scripts() ); } public function test_livewire_js_calls_reference_relative_root() { $this->assertStringContainsString( '<script src="/livewire/livewire.js?', Livewire::scripts() ); $this->assertStringContainsString( "window.livewire_app_url = '';", Livewire::scripts() ); } public function test_livewire_js_calls_reference_configured_asset_url() { $this->assertStringContainsString( '<script src="https://foo.com/assets/livewire/livewire.js?', Livewire::scripts(['asset_url' => 'https://foo.com/assets']) ); $this->assertStringContainsString( "window.livewire_app_url = 'https://foo-bar.com/path';", Livewire::scripts(['app_url' => 'https://foo-bar.com/path']) ); } public function test_asset_url_trailing_slashes_are_trimmed() { $this->assertStringContainsString( '<script src="https://foo.com/assets/livewire/livewire.js?', Livewire::scripts(['asset_url' => 'https://foo.com/assets/']) ); $this->assertStringContainsString( "window.livewire_app_url = 'https://foo.com/assets';", Livewire::scripts(['app_url' => 'https://foo.com/assets/']) ); } public function test_asset_url_passed_into_blade_assets_directive() { $output = View::make('assets-directive', [ 'options' => ['asset_url' => 'https://foo.com/assets/', 'app_url' => 'https://bar.com/'], ])->render(); $this->assertStringContainsString( '<script src="https://foo.com/assets/livewire/livewire.js?', $output ); $this->assertStringContainsString( "window.livewire_app_url = 'https://bar.com';", $output ); } public function test_nonce_passed_into_directive_gets_added_as_script_tag_attribute() { $output = View::make('assets-directive', [ 'options' => ['nonce' => 'foobarnonce'], ])->render(); $this->assertStringContainsString( ' nonce="foobarnonce">', $output ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/ComponentDependencyInjectionUnitTest.php
src/Tests/ComponentDependencyInjectionUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; use Illuminate\Routing\UrlGenerator; use Tests\TestComponent; class ComponentDependencyInjectionUnitTest extends \Tests\TestCase { public function test_component_mount_action_with_dependency() { $component = Livewire::test(ComponentWithDependencyInjection::class, ['id' => 123]); $this->assertEquals('http://localhost/some-url/123', $component->foo); $this->assertEquals(123, $component->bar); } public function test_component_action_with_dependency() { $component = Livewire::test(ComponentWithDependencyInjection::class); $component->runAction('injection', 'foobar'); // $this->assertEquals('http://localhost', $component->foo); $this->assertEquals('foobar', $component->bar); } public function test_component_action_with_spread_operator() { $component = Livewire::test(ComponentWithDependencyInjection::class); $component->runAction('spread', 'foo', 'bar', 'baz'); $this->assertEquals(['foo', 'bar', 'baz'], $component->foo); } public function test_component_action_with_paramter_name_that_matches_a_container_registration_name() { $component = Livewire::test(ComponentWithDependencyInjection::class); app()->bind('foo', \stdClass::class); $component->runAction('actionWithContainerBoundNameCollision', 'bar'); $this->assertEquals('bar', $component->foo); } public function test_component_action_with_primitive() { $component = Livewire::test(ComponentWithDependencyInjection::class); $component->runAction('primitive', 1); $this->assertEquals(1, $component->foo); } public function test_component_action_with_default_value() { $component = Livewire::test(ComponentWithDependencyInjection::class); $component->runAction('primitiveWithDefault', 10, 'foo'); $this->assertEquals(10, $component->foo); $this->assertEquals('foo', $component->bar); $component->runAction('primitiveWithDefault', 100); $this->assertEquals(100, $component->foo); $this->assertEquals('default', $component->bar); $component->runAction('primitiveWithDefault'); $this->assertEquals(1, $component->foo); $this->assertEquals('default', $component->bar); $component->runAction('primitiveWithDefault', null, 'foo'); $this->assertEquals(null, $component->foo); $this->assertEquals('foo', $component->bar); } public function test_component_action_with_dependency_and_primitive() { $component = Livewire::test(ComponentWithDependencyInjection::class); $component->runAction('mixed', 1); $this->assertEquals('http://localhost/some-url/1', $component->foo); $this->assertEquals(1, $component->bar); } public function test_component_action_with_dependency_and_optional_primitive() { $component = Livewire::test(ComponentWithDependencyInjection::class); $component->runAction('mixedWithDefault', 10); $this->assertEquals('http://localhost/some-url', $component->foo); $this->assertEquals(10, $component->bar); $component->runAction('mixedWithDefault'); $this->assertEquals('http://localhost/some-url', $component->foo); $this->assertEquals(1, $component->bar); $component->runAction('mixedWithDefault', null); $this->assertEquals('http://localhost/some-url', $component->foo); $this->assertNull($component->bar); } public function test_component_render_method_with_dependency() { $component = Livewire::test(CustomComponent::class); $component->assertSee('Results from the service'); } public function test_component_mount_action_with_primitive_union_types() { $component = Livewire::test(ComponentWithUnionTypes::class); $this->assertEquals('http://localhost/some-url/123', $component->foo); $this->assertEquals(123, $component->bar); $component->runAction('injection', 'foobar'); $this->assertEquals('http://localhost', $component->foo); $this->assertEquals('foobar', $component->bar); } } class ComponentWithDependencyInjection extends TestComponent { public $foo; public $bar; public function mount(UrlGenerator $generator, $id = 123) { $this->foo = $generator->to('/some-url', $id); $this->bar = $id; } public function injection(UrlGenerator $generator, $bar) { $this->foo = $generator->to('/'); $this->bar = $bar; } public function spread(...$params) { $this->foo = $params; } public function primitive(int $foo) { $this->foo = $foo; } public function primitiveWithDefault(?int $foo = 1, $bar = 'default') { $this->foo = $foo; $this->bar = $bar; } public function mixed(UrlGenerator $generator, int $id) { $this->foo = $generator->to('/some-url', $id); $this->bar = $id; } public function mixedWithDefault(UrlGenerator $generator, ?int $id = 1) { $this->foo = $generator->to('/some-url'); $this->bar = $id; } public function actionWithContainerBoundNameCollision($foo) { $this->foo = $foo; } } class CustomComponent extends Component { public function render(CustomService $service) { return view('show-property-value', [ 'message' => $service->results() ]); } } class CustomService { public function results() { return 'Results from the service'; } } class ComponentWithUnionTypes extends TestComponent { public $foo; public $bar; public function mount(UrlGenerator $generator, string|int $id = 123) { $this->foo = $generator->to('/some-url', $id); $this->bar = $id; } public function injection(UrlGenerator $generator, $bar) { $this->foo = $generator->to('/'); $this->bar = $bar; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/AlpineMorphingBrowserTest.php
src/Tests/AlpineMorphingBrowserTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; /** @group morphing */ class AlpineMorphingBrowserTest extends \Tests\BrowserTestCase { public function test_component_with_custom_directive_keeps_state_after_cloning() { Livewire::visit(new class extends Component { public int $counter = 0; function render() { return <<<'HTML' <div> <div x-counter wire:model.live='counter'> <span dusk='counter' x-text="__counter"></span> <button x-counter:increment dusk='increment'>+</button> </div> <script> document.addEventListener('alpine:init', () => { Alpine.directive('counter', function (el, { value }) { if (value === 'increment') { Alpine.bind(el, { 'x-on:click.prevent'() { this.$data.__counter++; } }) } else if (! value) { Alpine.bind(el, { 'x-modelable': '__counter', 'x-data'() { return { __counter: 0 } } }) } }) }) </script> </div> HTML; } }) ->waitForLivewire()->click('@increment') ->assertInputValue('@counter', '1') ; } public function test_deep_alpine_state_is_preserved_when_morphing_with_uninitialized_livewire_html() { Livewire::visit(new class extends Component { function render() { return <<<'HTML' <div> <div x-data="{ showCounter: false }"> <button @click="showCounter = true" dusk="button">show</button> <template x-if="showCounter"> <div x-data="{ count: 0 }"> <button x-on:click="count++" dusk="increment">+</button> <h1 x-text="count" dusk="count"></h1> </div> </template> </div> <button wire:click="$commit" dusk="refresh">Refresh</button> </div> HTML; } }) ->assertMissing('@count') ->click('@button') ->assertVisible('@count') ->assertSeeIn('@count', '0') ->click('@increment') ->assertSeeIn('@count', '1') ->waitForLivewire()->click('@refresh') ->assertVisible('@count') ->assertSeeIn('@count', '1'); ; } public function test_alpine_property_persists_on_array_item_reorder() { return Livewire::visit(new class extends Component { public array $items = [ ['id' => 1, 'title' => 'foo', 'complete' => false], ['id' => 2, 'title' => 'bar', 'complete' => false], ['id' => 3, 'title' => 'baz', 'complete' => false] ]; public function getItems() { return $this->items; } public function complete(int $index): void { $this->items[$index]['complete'] = true; } function render() { return <<<'HTML' <div> @foreach (collect($this->getItems())->sortBy('complete')->toArray() as $index => $item) <div wire:key="{{$item['id']}}" x-data="{show: false}"> <div>{{ $item['title'] }} (completed: @json($item['complete']))</div> <div x-show="show" x-cloak dusk="hidden"> (I shouldn't be visible): {{ $item['title'] }} </div> <button dusk="complete-{{ $index }}" wire:click="complete({{ $index }})">complete</button> </div> @endforeach </div> HTML; } }) // Click on the top two items and mark them as complete. ->click('@complete-0') ->pause(500) ->click('@complete-1') ->pause(500) // Error thrown in console, and Alpine fails and shows the hidden text when it should not. ->assertMissing('@hidden'); // ->assertConsoleLogMissingWarning('show is not defined'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/ComponentIsMacroableUnitTest.php
src/Tests/ComponentIsMacroableUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; use Tests\TestComponent; class ComponentIsMacroableUnitTest extends \Tests\TestCase { public function test_it_resolves_the_mount_parameters() { Component::macro('macroedMethod', function ($first, $second) { return [$first, $second]; }); Livewire::test(ComponentWithMacroedMethodStub::class) ->assertSetStrict('foo', ['one', 'two']); } } class ComponentWithMacroedMethodStub extends TestComponent { public $foo; public function mount() { $this->foo = $this->macroedMethod('one', 'two'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/UpdatingTableRowsTest.php
src/Tests/UpdatingTableRowsTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; class UpdatingTableRowsTest extends \Tests\BrowserTestCase { public function test_component_renders_table_rows_and_updates_properly() { Livewire::visit([new class extends Component { public function render() { return <<<'HTML' <table> <tbody> <livewire:child /> </tbody> </table> HTML; } }, 'child' => new class extends Component { public int $counter = 0; public function increment() { $this->counter++; } public function render() { return <<<'HTML' <tr dusk="table-row"> <td> <button type="button" wire:click="increment" dusk="increment">+</button> </td> <td> <input wire:model="counter" dusk="counter"> </td> </tr> HTML; } }]) ->assertPresent('@table-row') ->assertPresent('@counter') ->assertInputValue('@counter', '0') ->click('@increment') ->waitForLivewire() ->assertPresent('@table-row') ->assertPresent('@counter') ->assertInputValue('@counter', '1') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/VirtualPropertyUnitTest.php
src/Tests/VirtualPropertyUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; const PROPERTY_NAME = 'virtualProperty'; class VirtualPropertyUnitTest extends \Tests\TestCase { public function test_virtual_property_is_accessible() { $this->markTestSkipped('Not sure we should support this.'); $component = Livewire::test(ComponentWithPublicVirtualproperty::class) ->assertSee('Caleb') ->set(PROPERTY_NAME, 'Porzio') ->assertSetStrict('name', 'Porzio'); $this->assertEquals($component->get(PROPERTY_NAME), 'Porzio'); } } class ComponentWithPublicVirtualproperty extends Component { public $name = 'Caleb'; public function render() { return app('view')->make('show-name'); } public function getPublicPropertiesDefinedBySubClass() { $data = parent::getPublicPropertiesDefinedBySubClass(); $data[PROPERTY_NAME] = $this->name; return $data; } public function __get($property) { if($property == PROPERTY_NAME) return $this->name; return parent::__get($property); } public function __set($property, $value) { if($property == PROPERTY_NAME) { $this->name = $value; return; } parent::__set($property, $value); } public function propertyIsPublicAndNotDefinedOnBaseClass($propertyName) { if($propertyName == PROPERTY_NAME) return true; return parent::propertyIsPublicAndNotDefinedOnBaseClass($propertyName); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/AlpineIntersectBrowserTest.php
src/Tests/AlpineIntersectBrowserTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; class AlpineIntersectBrowserTest extends \Tests\BrowserTestCase { public function test_component_with_intersect_plugin_works() { Livewire::visit(new class () extends Component { public function render() { return <<<'HTML' <div x-data="{ inViewport: false }"> <div x-intersect:enter="inViewport = true" x-intersect:leave="inViewport = false">something</div> <p x-text="inViewport ? 'in viewport': 'outside viewport'"></p> <button type="button" dusk="button" wire:click="$refresh">refresh</button> </div> HTML; } }) ->assertSeeIn('p', 'in viewport') ->waitForLivewire()->click('@button') ->assertSeeIn('p', 'in viewport'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/PublicPropertyHydrationHooksUnitTest.php
src/Tests/PublicPropertyHydrationHooksUnitTest.php
<?php namespace Livewire\Tests; use Illuminate\Support\Str; use Livewire\Livewire; use Tests\TestComponent; class PublicPropertyHydrationHooksUnitTest extends \Tests\TestCase { public function test_public_properties_can_be_cast() { $this->markTestSkipped('This test needs to be split, so each property type is tested as part of their dedicated Synth'); Livewire::test(ComponentWithPublicPropertyCasters::class) ->call('storeTypeOfs') ->assertSetStrict('typeOfs.date', 'Carbon\Carbon') ->assertSetStrict('typeOfs.dateWithFormat', 'Carbon\Carbon') ->assertSetStrict('typeOfs.collection', 'Illuminate\Support\Collection') ->assertSetStrict('typeOfs.allCaps', 'FOO') ->assertSetStrict('typeOfs.stringable', 'Illuminate\Support\Stringable') ->assertSetStrict('dateWithFormat', '00-01-01') ->assertSetStrict('collection', function ($value) { return $value->toArray() === ['foo', 'bar']; }) ->assertSetStrict('allCaps', 'foo') ->assertSetStrict('stringable', 'Be excellent to each other') ->set('dateWithFormat', '00-02-02') ->assertSetStrict('dateWithFormat', '00-02-02'); } } class ComponentWithPublicPropertyCasters extends TestComponent { public $date; public $dateWithFormat; public $collection; public $allCaps; public $typeOfs; public $stringable; public function updatedDateWithFormat($value) { $this->dateWithFormat = \Carbon\Carbon::createFromFormat('y-m-d', $value); } public function hydrate() { $this->dateWithFormat = \Carbon\Carbon::createFromFormat('y-m-d', $this->dateWithFormat); $this->allCaps = strtoupper($this->allCaps); $this->stringable = Str::of('Be excellent to each other'); } public function dehydrate() { $this->dateWithFormat = $this->dateWithFormat->format('y-m-d'); $this->allCaps = strtolower($this->allCaps); $this->stringable = $this->stringable->__toString(); } public function mount() { $this->date = \Carbon\Carbon::parse('Jan 1 1900'); $this->dateWithFormat = \Carbon\Carbon::parse('Jan 1 1900'); $this->collection = collect(['foo', 'bar']); $this->allCaps = 'FOO'; $this->stringable = Str::of('Be excellent to each other'); } public function storeTypeOfs() { $this->typeOfs = [ 'date' => get_class($this->date), 'dateWithFormat' => get_class($this->date), 'collection' => get_class($this->collection), 'allCaps' => $this->allCaps, 'stringable' => get_class($this->stringable), ]; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/PublicPropertiesAreInitializedUnitTest.php
src/Tests/PublicPropertiesAreInitializedUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; use Stringable; use Tests\TestComponent; class PublicPropertiesAreInitializedUnitTest extends \Tests\TestCase { public function test_uninitialized_public_property_is_null() { Livewire::test(UninitializedPublicPropertyComponent::class) ->assertSetStrict('message', null); } public function test_initialized_public_property_shows_value() { Livewire::test(InitializedPublicPropertyComponent::class) ->assertSee('Non-typed Properties are boring'); } public function test_modified_initialized_public_property_should_not_revert_after_subsequent_hydration() { $propertyValue = Livewire::test(InitializedPublicPropertyComponent::class) ->set('some_id', null) ->set('message', 'whatever') ->get('some_id') ; $this->assertEquals(null, $propertyValue); } public function test_uninitialized_public_typed_property_is_null() { Livewire::test(UninitializedPublicTypedPropertyComponent::class) ->assertSetStrict('message', null); } public function test_uninitialized_public_union_typed_property_is_null() { Livewire::test(UninitializedPublicUnionTypedPropertyComponent::class) ->assertSetStrict('message', null); } public function test_uninitialized_public_typed_property_is_still_null_after_refresh() { Livewire::test(UninitializedPublicTypedPropertyAfterRefreshComponent::class) ->call('$refresh') ->assertSetStrict('message', null); } public function test_initialized_public_typed_property_shows_value() { Livewire::test(InitializedPublicTypedPropertyComponent::class) ->assertSee('Typed Properties FTW!'); } } class UninitializedPublicPropertyComponent extends TestComponent { public $message; } class InitializedPublicPropertyComponent extends Component { public $message = 'Non-typed Properties are boring'; public $some_id = 3; public function render() { return app('view')->make('show-property-value'); } } class UninitializedPublicTypedPropertyComponent extends TestComponent { public string $message; } class UninitializedPublicUnionTypedPropertyComponent extends TestComponent { public string | Stringable $message; } class UninitializedPublicTypedPropertyAfterRefreshComponent extends TestComponent { public string $message; } class InitializedPublicTypedPropertyComponent extends Component { public string $message = 'Typed Properties FTW!'; public function render() { return app('view')->make('show-property-value'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/InvadeHelperUnitTest.php
src/Tests/InvadeHelperUnitTest.php
<?php namespace Livewire\Tests; use function Livewire\invade; use Livewire\Request; use Livewire\Response; class InvadeHelperUnitTest extends \Tests\TestCase { public function test_get_property() { $thing = new class { private $foo = 'bar'; }; $this->assertEquals('bar', invade($thing)->foo); } public function test_set_property() { $thing = new class { private $foo = 'bar'; }; invade($thing)->foo = 'baz'; $this->assertEquals('baz', invade($thing)->foo); } public function test_call_method() { $thing = new class { private $foo = 'bar'; private function getFoo() { return $this->foo; } }; $this->assertEquals('bar', invade($thing)->getFoo()); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/ComponentMethodBindingsUnitTest.php
src/Tests/ComponentMethodBindingsUnitTest.php
<?php namespace Livewire\Tests; use Illuminate\Database\Eloquent\Model; use Illuminate\Routing\UrlGenerator; use Illuminate\Support\Facades\Route; use Livewire\Component; use Livewire\Livewire; class ComponentMethodBindingsUnitTest extends \Tests\TestCase { public function test_mount_method_receives_explicit_model_binding() { Livewire::test(ComponentWithBindings::class, [ 'model' => new ModelToBeBound('new model'), ])->assertSeeText('new model')->assertSeeText('param-default'); Livewire::test(ComponentWithBindings::class, [ 'model' => new ModelToBeBound('new model'), 'param' => 'foo', ])->assertSeeText('new model')->assertSeeText('foo'); } public function test_mount_method_receives_explicit_enum_binding() { Livewire::test(ComponentWithEnumBindings::class, [ 'enum' => EnumToBeBound::FIRST, ])->assertSeeText('enum-first')->assertSeeText('param-default'); Livewire::test(ComponentWithEnumBindings::class, [ 'enum' => EnumToBeBound::FIRST, 'param' => 'foo', ])->assertSeeText('enum-first')->assertSeeText('foo'); } public function test_mount_method_receives_implicit_model_binding() { Livewire::test(ComponentWithBindings::class, [ 'model' => 'new model', ])->assertSeeText('new model:param-default'); Livewire::test(ComponentWithBindings::class, [ 'model' => 'new model', 'param' => 'foo', ])->assertSeeText('new model:foo'); Livewire::test(ComponentWithBindings::class, [ 'new model', 'foo', ])->assertSeeText('new model:foo'); Livewire::test(ComponentWithBindings::class, [ 'foo', 'model' => 'new model', ])->assertSeeText('new model:foo'); } public function test_mount_method_receives_implicit_enum_binding() { Livewire::test(ComponentWithEnumBindings::class, [ 'enum' => 'enum-first', ])->assertSeeText('enum-first:param-default'); Livewire::test(ComponentWithEnumBindings::class, [ 'enum' => 'enum-first', 'param' => 'foo', ])->assertSeeText('enum-first:foo'); Livewire::test(ComponentWithEnumBindings::class, [ 'enum' => 'enum-first', 'foo', ])->assertSeeText('enum-first:foo'); Livewire::test(ComponentWithEnumBindings::class, [ 'foo', 'enum' => 'enum-first', ])->assertSeeText('enum-first:foo'); } public function test_mount_method_receives_route_and_implicit_model_binding_and_dependency_injection() { Livewire::test(ComponentWithMountInjections::class, [ 'foo', 'model' => 'new model', ])->assertSeeText('http://localhost/some-url:new model:foo'); Livewire::component(ComponentWithMountInjections::class); Route::get('/foo/{model}', ComponentWithMountInjections::class); $this->withoutExceptionHandling()->get('/foo/route-model')->assertSeeText('http://localhost/some-url:route-model:param-default'); } public function test_mount_method_receives_route_and_implicit_enum_binding_and_dependency_injection() { Livewire::test(ComponentWithEnumMountInjections::class, [ 'foo', 'enum' => 'enum-first', ])->assertSeeText('http://localhost/some-url:enum-first:foo'); Livewire::component(ComponentWithEnumMountInjections::class); Route::get('/foo/{enum}', ComponentWithEnumMountInjections::class); $this->withoutExceptionHandling()->get('/foo/enum-first')->assertSeeText('http://localhost/some-url:enum-first:param-default'); } public function test_mount_method_receives_route_and_implicit_enum_optional_binding_and_dependency_injection() { Livewire::test(ComponentWithOptionalEnumMountInjections::class, [ 'foo', 'enum' => null, ])->assertSeeText('http://localhost/some-url:foo'); Livewire::component(ComponentWithOptionalEnumMountInjections::class); Route::get('/foo/{enum?}', ComponentWithOptionalEnumMountInjections::class); $this->get('/foo/enum-first')->assertSeeText('http://localhost/some-url:enum-first:param-default'); $this->get('/foo')->assertSeeText('http://localhost/some-url:param-default'); } public function test_action_receives_implicit_model_binding() { $component = Livewire::test(ComponentWithBindings::class) ->assertSee('model-default'); $component->runAction('actionWithModel', 'implicitly bound'); $this->assertEquals('implicitly bound:param-default', $component->name); $component->runAction('actionWithModel', 'implicitly bound', 'foo'); $this->assertEquals('implicitly bound:foo', $component->name); } public function test_mount_method_receives_route_and_implicit_model_optional_binding_and_dependency_injection() { Livewire::component(ComponentWithOptionalModelMountInjections::class); Route::get('/route-with-optional-params/{model?}', ComponentWithOptionalModelMountInjections::class); /** * This is expected since we don't have a database * General error: 1 no such table: optional_model_to_be_bounds **/ $this->get('/route-with-optional-params/1') ->assertInternalServerError(); $this->get('/route-with-optional-params/') ->assertSee('Nullable - No Model'); } public function test_action_receives_implicit_model_binding_independent_of_parameter_order() { $component = Livewire::test(ComponentWithBindings::class) ->assertSee('model-default'); $component->runAction('actionWithModelAsSecond', 'bar', 'implicitly bound'); $this->assertEquals('bar:implicitly bound:param-default', $component->name); $component->runAction('actionWithModelAsSecond', 'bar', 'implicitly bound', 'foo'); $this->assertEquals('bar:implicitly bound:foo', $component->name); } public function test_action_implicit_model_binding_plays_well_with_dependency_injection() { $component = Livewire::test(ComponentWithBindings::class) ->assertSee('model-default'); $component->runAction('actionWithModelAndDependency', 'implicitly bound'); $this->assertEquals('implicitly bound:http://localhost/some-url/param-default', $component->name); $component->runAction('actionWithModelAndDependency', 'implicitly bound', 'foo'); $this->assertEquals('implicitly bound:http://localhost/some-url/foo', $component->name); } public function test_action_receives_implicit_enum_binding() { $component = Livewire::test(ComponentWithEnumBindings::class, ['enum' => EnumToBeBound::FIRST]) ->assertSee('enum-first:param-default'); $component->runAction('actionWithEnum', 'enum-first'); $this->assertEquals('enum-first:param-default', $component->name); $component->runAction('actionWithEnum', 'enum-first', 'foo'); $this->assertEquals('enum-first:foo', $component->name); } public function test_action_receives_implicit_enum_binding_independent_of_parameter_order() { $component = Livewire::test(ComponentWithEnumBindings::class, ['enum' => EnumToBeBound::FIRST]) ->assertSee('enum-first:param-default'); $component->runAction('actionWithEnumAsSecond', 'bar', 'enum-first'); $this->assertEquals('bar:enum-first:param-default', $component->name); $component->runAction('actionWithEnumAsSecond', 'bar', 'enum-first', 'foo'); $this->assertEquals('bar:enum-first:foo', $component->name); } public function test_action_implicit_enum_binding_plays_well_with_dependency_injection() { $component = Livewire::test(ComponentWithEnumBindings::class, ['enum' => EnumToBeBound::FIRST]) ->assertSee('enum-first:param-default'); $component->runAction('actionWithEnumAndDependency', 'enum-first'); $this->assertEquals('enum-first:http://localhost/some-url/param-default', $component->name); $component->runAction('actionWithEnumAndDependency', 'enum-first', 'foo'); $this->assertEquals('enum-first:http://localhost/some-url/foo', $component->name); } } class ModelToBeBound extends Model { public $value; public function __construct($value = 'model-default') { $this->value = $value; } public function resolveRouteBinding($value, $field = null) { $this->value = $value; return $this; } } enum EnumToBeBound: string { case FIRST = 'enum-first'; } class ComponentWithBindings extends Component { public $name; public function mount(ModelToBeBound $model, $param = 'param-default') { $this->name = collect([$model->value, $param])->join(':'); } public function actionWithModel(ModelToBeBound $model, $param = 'param-default') { $this->name = collect([$model->value, $param])->join(':'); } public function actionWithModelAsSecond($foo, ModelToBeBound $model, $param = 'param-default') { $this->name = collect([$foo, $model->value, $param])->join(':'); } public function actionWithModelAndDependency(UrlGenerator $generator, ModelToBeBound $model, $param = 'param-default') { $this->name = collect([$model->value, $generator->to('/some-url/' . $param)])->join(':'); } public function render() { return app('view')->make('show-name-with-this'); } } class OptionalModel extends Model { protected $attributes = [ 'name' => 'Livewire' ]; } class ComponentWithOptionalModelMountInjections extends Component { public ?OptionalModel $model = null; public function mount(?OptionalModel $model = null) { $this->model = $model; } public function render() { return <<<'HTML' <div> {{ is_null($this->model) ? 'Nullable - No Model' : $this->model->name }} </div> HTML; } } class ComponentWithEnumBindings extends Component { public $name; public function mount(EnumToBeBound $enum, $param = 'param-default') { $this->name = collect([$enum->value, $param])->join(':'); } public function actionWithEnum(EnumToBeBound $enum, $param = 'param-default') { $this->name = collect([$enum->value, $param])->join(':'); } public function actionWithEnumAsSecond($foo, EnumToBeBound $enum, $param = 'param-default') { $this->name = collect([$foo, $enum->value, $param])->join(':'); } public function actionWithEnumAndDependency(UrlGenerator $generator, EnumToBeBound $enum, $param = 'param-default') { $this->name = collect([$enum->value, $generator->to('/some-url/' . $param)])->join(':'); } public function render() { return app('view')->make('show-name-with-this'); } } class ComponentWithMountInjections extends Component { public $name; public function mount(UrlGenerator $generator, ModelToBeBound $model, $param = 'param-default') { $this->name = collect([$generator->to('/some-url'), $model->value, $param])->join(':'); } public function render() { return app('view')->make('show-name-with-this'); } } class ComponentWithEnumMountInjections extends Component { public $name; public function mount(UrlGenerator $generator, EnumToBeBound $enum, $param = 'param-default') { $this->name = collect([$generator->to('/some-url'), $enum->value, $param])->join(':'); } public function render() { return app('view')->make('show-name-with-this'); } } class ComponentWithOptionalEnumMountInjections extends Component { public $name; public function mount(UrlGenerator $generator, ?EnumToBeBound $enum = null, $param = 'param-default') { $this->name = collect([$generator->to('/some-url'), $enum?->value, $param])->filter(fn($value) => !is_null($value))->join(':'); } public function render() { return app('view')->make('show-name-with-this'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/JavascriptHooksBrowserTest.php
src/Tests/JavascriptHooksBrowserTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; class JavascriptHooksBrowserTest extends \Tests\BrowserTestCase { public function test_dollar_wire_hook_works_with_inline_alpine_component() { Livewire::visit(new class () extends Component { public function render() { return <<<'HTML' <div> <button type="button" wire:click="$refresh" dusk="refresh">Refresh</button> <div x-data="{ commitFired: false, init: function() { this.$wire.$hook('commit', ({ component, commit, respond, succeed, fail }) => { this.commitFired = true }) } }"> <span x-text="commitFired" dusk="commitFired"></span> </div> </div> HTML; } }) ->assertSeeIn('@commitFired', 'false') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@commitFired', 'true'); } public function test_dollar_wire_hook_works_with_alpine_data_component() { Livewire::visit(new class () extends Component { public function render() { return <<<'HTML' <div> <button type="button" wire:click="$refresh" dusk="refresh">Refresh</button> <div x-data="myComponent"> <span x-text="commitFired" dusk="commitFired"></span> </div> <script> document.addEventListener('alpine:init', () => { Alpine.data('myComponent', () => ({ commitFired: false, init() { this.$wire.$hook('commit', ({ component, commit, respond, succeed, fail }) => { this.commitFired = true }) } })) }) </script> </div> HTML; } }) ->assertSeeIn('@commitFired', 'false') ->waitForLivewire()->click('@refresh') ->assertSeeIn('@commitFired', 'true'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/QueryParamsUnitTest.php
src/Tests/QueryParamsUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Livewire; use Tests\TestComponent; class QueryParamsUnitTest extends \Tests\TestCase { public function test_it_sets_name_from_query_params() { $name = 'Livewire'; Livewire::withQueryParams(['name' => $name]) ->test(QueryParamsComponent::class) ->assertSetStrict('name', $name); } public function test_it_does_not_set_name_when_no_query_params_are_provided() { Livewire::test(QueryParamsComponent::class) ->assertSetStrict('name', null); } } class QueryParamsComponent extends TestComponent { public $name; public function mount() { $this->name = request('name'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/LivewireRouteCachingUnitTest.php
src/Tests/LivewireRouteCachingUnitTest.php
<?php namespace Livewire\Tests; use Error; use Exception; use Illuminate\Routing\Route; use Tests\TestCase; class LivewireRouteCachingUnitTest extends TestCase { public function test_livewire_script_route_is_cacheable(): void { // The route changes based on debug mode $uri = ltrim(\Livewire\Mechanisms\HandleRequests\EndpointResolver::scriptPath(! config('app.debug')), '/'); $route = $this->getRoute($uri); $this->cacheRoute($route, 'Livewire\Mechanisms\FrontendAssets\FrontendAssets@returnJavaScriptAsFile', "Failed to cache route '$uri'"); } public function test_livewire_update_route_is_cacheable(): void { $uri = ltrim(\Livewire\Mechanisms\HandleRequests\EndpointResolver::updatePath(), '/'); $route = $this->getRoute($uri); $this->cacheRoute($route, 'Livewire\Mechanisms\HandleRequests\HandleRequests@handleUpdate', "Failed to cache route 'livewire/update'"); } protected function getRoute(string $uri): Route { $route = collect(\Illuminate\Support\Facades\Route::getRoutes()) ->firstWhere(fn(Route $route) => $route->uri() === $uri); if ($route === null) { $this->fail("Route '$uri' not found."); } return $route; } protected function cacheRoute(Route $route, string $expectedHandle, string $message): void { try { $route->prepareForSerialization(); $this->assertStringContainsString($expectedHandle, $route->getAction('uses')); } catch (Error|Exception) { $this->fail($message); } $this->assertTrue(true); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/ComponentsAreSecureUnitTest.php
src/Tests/ComponentsAreSecureUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Mechanisms\HandleComponents\CorruptComponentPayloadException; use Livewire\Exceptions\PublicPropertyNotFoundException; use Livewire\Exceptions\MethodNotFoundException; use Tests\TestComponent; class ComponentsAreSecureUnitTest extends \Tests\TestCase { public function test_throws_method_not_found_exception_when_action_missing() { $this->expectException(MethodNotFoundException::class); app('livewire')->component('security-target', SecurityTargetStub::class); $component = app('livewire')->test('security-target'); $component->runAction('missingMethod'); } public function test_can_only_call_methods_defined_by_user() { $this->expectException(MethodNotFoundException::class); app('livewire')->component('security-target', SecurityTargetStub::class); $component = app('livewire')->test('security-target'); // "redirect" happens to be a public method defined on the base Component class. $component->runAction('redirect'); } public function test_can_only_set_public_properties() { $this->expectException(PublicPropertyNotFoundException::class); app('livewire')->component('security-target', SecurityTargetStub::class); $component = app('livewire')->test('security-target'); $component->updateProperty('protectedProperty', 'baz'); } public function test_data_cannot_be_tampered_with_on_frontend() { $this->expectException(CorruptComponentPayloadException::class); app('livewire')->component('security-target', SecurityTargetStub::class); $component = app('livewire')->test('security-target'); $snapshot = $component->snapshot; $snapshot['data']['0']['publicProperty'] = 'different-property'; $component->snapshot = $snapshot; $component->call('$refresh'); } public function test_id_cannot_be_tampered_with_on_frontend() { $this->expectException(CorruptComponentPayloadException::class); app('livewire')->component('security-target', SecurityTargetStub::class); $component = app('livewire')->test('security-target'); $snapshot = $component->snapshot; $snapshot['memo']['id'] = 'different-id'; $component->snapshot = $snapshot; $component->call('$refresh'); } public function test_component_name_cannot_be_tampered_with_on_frontend() { $this->expectException(CorruptComponentPayloadException::class); app('livewire')->component('safe', SecurityTargetStub::class); app('livewire')->component('unsafe', UnsafeComponentStub::class); $component = app('livewire')->test('safe'); $snapshot = $component->snapshot; // Hijack the "safe" component, with "unsafe" $snapshot['memo']['name'] = 'unsafe'; $component->snapshot = $snapshot; // If the hijack was stopped, the expected exception will be thrown. // If it worked, then an exception will be thrown that will fail the test. $component->runAction('someMethod'); } } class SecurityTargetStub extends TestComponent { public $publicProperty = 'foo'; protected $protectedProperty = 'bar'; public function publicMethod() { } protected function protectedMethod() { } } class UnsafeComponentStub extends TestComponent { public function someMethod() { throw new \Exception('Should not be able to acess me!'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/LifecycleHooksUnitTest.php
src/Tests/LifecycleHooksUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Livewire; use Illuminate\Support\Stringable; use PHPUnit\Framework\Assert as PHPUnit; use Tests\TestComponent; class CustomException extends \Exception {}; class LifecycleHooksUnitTest extends \Tests\TestCase { public function test_refresh_magic_method() { $component = Livewire::test(ForMagicMethods::class); $component->call('$refresh'); $this->assertEquals([ 'mount' => true, 'hydrate' => 1, 'hydrateFoo' => 1, 'dehydrate' => 2, 'dehydrateFoo' => 2, 'updating' => false, 'updated' => false, 'updatingFoo' => false, 'updatedFoo' => false, 'updatingBar' => false, 'updatingBarBaz' => false, 'updatedBar' => false, 'updatedBarBaz' => false, 'caughtException' => false, ], $component->lifecycles); } public function test_set_magic_method() { $component = Livewire::test(ForMagicMethods::class, [ 'expected' => [ 'updating' => [[ 'foo' => 'bar', ]], 'updated' => [[ 'foo' => 'bar', ]], 'updatingFoo' => ['bar'], 'updatedFoo' => ['bar'], ] ]); $component->call('$set', 'foo', 'bar'); $this->assertEquals([ 'mount' => true, 'hydrate' => 1, 'hydrateFoo' => 1, 'dehydrate' => 2, 'dehydrateFoo' => 2, 'updating' => true, 'updated' => true, 'updatingFoo' => true, 'updatedFoo' => true, 'updatingBar' => false, 'updatingBarBaz' => false, 'updatedBar' => false, 'updatedBarBaz' => false, 'caughtException' => false, ], $component->lifecycles); $component->call('testExceptionInterceptor'); $this->assertTrue($component->lifecycles['caughtException']); } } class ForMagicMethods extends TestComponent { public $foo; public $baz; public $bar = []; public $expected; public $lifecycles = [ 'mount' => false, 'hydrate' => 0, 'hydrateFoo' => 0, 'dehydrate' => 0, 'dehydrateFoo' => 0, 'updating' => false, 'updated' => false, 'updatingFoo' => false, 'updatedFoo' => false, 'updatingBar' => false, 'updatingBarBaz' => false, 'updatedBar' => false, 'updatedBarBaz' => false, 'caughtException' => false, ]; public function mount(array $expected = []) { $this->expected = $expected; $this->lifecycles['mount'] = true; } public function exception($e, $stopPropagation) { if ($e instanceof CustomException) { $this->lifecycles['caughtException'] = true; $stopPropagation(); } } public function testExceptionInterceptor() { throw new CustomException; } public function hydrate() { $this->lifecycles['hydrate']++; } public function hydrateFoo() { $this->lifecycles['hydrateFoo']++; } public function dehydrate() { $this->lifecycles['dehydrate']++; } public function dehydrateFoo() { $this->lifecycles['dehydrateFoo']++; } public function updating($name, $value) { PHPUnit::assertEquals(array_shift($this->expected['updating']), [$name => $value]); $this->lifecycles['updating'] = true; } public function updated($name, $value) { PHPUnit::assertEquals(array_shift($this->expected['updated']), [$name => $value]); $this->lifecycles['updated'] = true; } public function updatingFoo($value) { PHPUnit::assertEquals(array_shift($this->expected['updatingFoo']), $value); $this->lifecycles['updatingFoo'] = true; } public function updatedFoo($value) { PHPUnit::assertEquals(array_shift($this->expected['updatedFoo']), $value); $this->lifecycles['updatedFoo'] = true; } public function updatingBar($value, $key) { $expected = array_shift($this->expected['updatingBar']); $expected_key = array_keys($expected)[0]; $expected_value = $expected[$expected_key]; [$before, $after] = $expected_value; PHPUnit::assertNotInstanceOf(Stringable::class, $key); PHPUnit::assertEquals($expected_key, $key); PHPUnit::assertEquals($before, data_get($this->bar, $key)); PHPUnit::assertEquals($after, $value); $this->lifecycles['updatingBar'] = true; } public function updatedBar($value, $key) { $expected = array_shift($this->expected['updatedBar']); $expected_key = array_keys($expected)[0]; $expected_value = $expected[$expected_key]; PHPUnit::assertNotInstanceOf(Stringable::class, $key); PHPUnit::assertEquals($expected_key, $key); PHPUnit::assertEquals($expected_value, $value); PHPUnit::assertEquals($expected_value, data_get($this->bar, $key)); $this->lifecycles['updatedBar'] = true; } public function updatingBarBaz($value, $key) { $expected = array_shift($this->expected['updatingBarBaz']); $expected_key = array_keys($expected)[0]; $expected_value = $expected[$expected_key]; [$before, $after] = $expected_value; PHPUnit::assertNotInstanceOf(Stringable::class, $key); PHPUnit::assertEquals($expected_key, $key); PHPUnit::assertEquals($before, data_get($this->bar, $key)); PHPUnit::assertEquals($after, $value); $this->lifecycles['updatingBarBaz'] = true; } public function updatedBarBaz($value, $key) { $expected = array_shift($this->expected['updatedBarBaz']); $expected_key = array_keys($expected)[0]; $expected_value = $expected[$expected_key]; PHPUnit::assertNotInstanceOf(Stringable::class, $key); PHPUnit::assertEquals($expected_key, $key); PHPUnit::assertEquals($expected_value, $value); PHPUnit::assertEquals($expected_value, data_get($this->bar, $key)); $this->lifecycles['updatedBarBaz'] = true; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/RequestPoolingBrowserTest.php
src/Tests/RequestPoolingBrowserTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; class RequestPoolingBrowserTest extends \Tests\BrowserTestCase { public function test_component_not_found_error_is_not_thrown_when_two_requests_are_sent_in_a_row() { Livewire::visit([ new class () extends Component { public int $selectedId = 0; public function select(int $id): void { $this->selectedId = $id; usleep(500*1000); // 500ms } public function render() { return <<<'HTML' <div> <button wire:click="select(1)" class="size-10" dusk="select-1">1</button> <div> @if ($this->selectedId !== 0) <livewire:child :key="'key'.$this->selectedId" :item="$this->selectedId" /> @endif </div> {{-- This needs to be here... --}} <div x-data="{ show: false }" x-cloak> <div x-show="show"></div> </div> </div> HTML; } }, 'child' => new class () extends Component { public $item; public function render() { return <<<'HTML' <div> Child {{ $item }} </div> HTML; } }, ]) ->waitForLivewireToLoad() ->click('@select-1') // Pause a moment before clicking again to ensure the call is in a new request... ->pause(50) ->click('@select-1') // Wait for the second request to complete... ->pause(600) ->assertConsoleLogHasNoErrors(); } public function test_component_not_found_error_is_not_thrown_when_a_faster_component_finishes_first_and_triggers_processing_of_queued_commits() { Livewire::visit([ new class () extends Component { public function render() { return <<<'HTML' <div> <livewire:fastchild :item="1" /> <livewire:slowchild :item="2" /> {{-- This needs to be here... --}} <div x-data="{ show: false }" x-cloak> <div x-show="show"></div> </div> </div> HTML; } }, 'fastchild' => new #[\Livewire\Attributes\Isolate] class () extends Component { public $item; public $show = false; public function showChild(): void { $this->show = true; usleep(200*1000); // 200ms } public function render() { return <<<'HTML' <div> <button wire:click="showChild" class="size-10" dusk="fastchild-show">Show Fast Child</button> <div> @if ($show) <livewire:child :key="$item" :item="$item" /> @endif </div> {{-- This needs to be here... --}} <div x-data="{ show: false }" x-cloak> <div x-show="show"></div> </div> </div> HTML; } }, 'slowchild' => new class () extends Component { public $item; public $show = false; public function showChild(): void { $this->show = true; usleep(1000*1000); // 1000ms } public function render() { return <<<'HTML' <div> <button wire:click="showChild" class="size-10" dusk="slowchild-show">Show Slow Child</button> <div> @if ($show) <livewire:child :key="$item" :item="$item" /> @endif </div> {{-- This needs to be here... --}} <div x-data="{ show: false }" x-cloak> <div x-show="show"></div> </div> </div> HTML; } }, 'child' => new class () extends Component { public $item; public function render() { return <<<'HTML' <div> Child {{ $item }} </div> HTML; } }, ]) ->waitForLivewireToLoad() ->click('@slowchild-show') // Pause a moment before clicking again to ensure the call is in a new request... ->pause(20) ->click('@slowchild-show') // Pause a moment before clicking again to ensure the call is in a new request... ->pause(20) ->click('@fastchild-show') // Wait for the second slow request to complete... ->pause(1200) ->assertConsoleLogHasNoErrors(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/WorksOnLoadBalancersUnitTest.php
src/Tests/WorksOnLoadBalancersUnitTest.php
<?php namespace Livewire\Tests; use Livewire\Livewire; use Livewire\Component; use Illuminate\Support\Facades\File; class WorksOnLoadBalancersUnitTest extends \Tests\TestCase { public function test_livewire_renders_chidren_properly_across_load_balancers() { $this->markTestSkipped('I havent wired this up yet because I want to make sure there isnt a less complex way...'); Livewire::component('parent', LoadBalancerParentComponent::class); Livewire::component('child', LoadBalancerChildComponent::class); $component = Livewire::test('parent'); $component->assertSee('child-content-1'); $component->assertSee('child-content-2'); // Nuke the view cache to simulate two different servers serving the same // livewire page for different requests. File::cleanDirectory(__DIR__.'/../../vendor/orchestra/testbench-core/laravel/storage/framework/views'); $component->call('$refresh'); $component->assertDontSee('child-content-1'); $component->assertDontSee('child-content-2'); } } class LoadBalancerParentComponent extends Component { public function render() { return view('load-balancer-parent'); } } class LoadBalancerChildComponent extends Component { public $number; public function render() { return view('load-balancer-child'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/ComponentWontConflictWithPredefinedClasses.php
src/Tests/ComponentWontConflictWithPredefinedClasses.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; class ComponentWontConflictWithPredefinedClasses extends \Tests\TestCase { public function setUp(): void { parent::setUp(); // We need to set Livewire's class namespace to the current namespace, because // Livewire's mechanism will only conflict with PHP's predefined classes // when the relative path to the class matches exactly to any of // the predefined classes (for example 'directory'). config()->set('livewire.class_namespace', 'Livewire\\Tests'); } public function test_wont_conflict_on_initial_request() { $component = Livewire::test(Directory::class); $component->assertSee('Count: 1'); } public function test_wont_conflict_on_subsequent_requests() { $component = Livewire::test(Directory::class); $component->call('increment'); $component->assertSee('Count: 2'); } } class Directory extends Component { public int $count = 1; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> Count: {{ $count }} </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Tests/WireModelBrowserTest.php
src/Tests/WireModelBrowserTest.php
<?php namespace Livewire\Tests; use Livewire\Component; use Livewire\Livewire; class WireModelBrowserTest extends \Tests\BrowserTestCase { public function test_supports_bracket_notation_in_expressions() { Livewire::visit(new class extends Component { public $foo = [ 'bars' => [ 'baz' => 'qux', ], ]; public function render() { return <<<'HTML' <div> <input type="text" wire:model="foo['bars']['baz']" dusk="input"> <span wire:text="foo['bars']['baz']" dusk="text"></span> </div> HTML; } }) ->waitForLivewireToLoad() ->typeSlowly('@input', 'livewire', 50) ->assertSeeIn('@text', 'livewire'); } public function test_wire_model_self_by_default_or_with_bubble_modifier() { Livewire::visit(new class extends Component { public $foo = ''; public function render() { return <<<'HTML' <div> <div wire:model="foo"> <input type="text" dusk="default-input"> </div> <div wire:model.bubble="foo"> <input type="text" dusk="bubble-input"> </div> <span wire:text="foo" dusk="text"></span> </div> HTML; } }) ->waitForLivewireToLoad() ->typeSlowly('@default-input', 'livewire', 50) ->assertDontSeeIn('@text', 'livewire') ->typeSlowly('@bubble-input', 'livewire', 50) ->assertSeeIn('@text', 'livewire'); } public function test_wire_model_dot_blur() { Livewire::visit(new class extends Component { public $foo = [ 'bars' => [ 'baz' => 'qux', ], ]; public function render() { return <<<'HTML' <div> <input type="text" wire:model="foo['bars']['baz']" dusk="input"> <span wire:text="foo['bars']['baz']" dusk="text"></span> </div> HTML; } }) ->waitForLivewireToLoad() ->typeSlowly('@input', 'livewire', 50) ->assertSeeIn('@text', 'livewire'); } public function test_debounces_requests_on_input_elements_by_default() { Livewire::visit(new class extends Component { public $foo; public function render() { return <<<'HTML' <div x-init="window.requests = 0"> <input type="text" wire:model.live="foo" dusk="input"> <span wire:text="foo" dusk="text"></span> </div> @script <script> this.intercept(({ onSend }) => { onSend(() => { window.requests++ }) }) </script> @endscript HTML; } }) ->waitForLivewireToLoad() ->typeSlowly('@input', 'livewire', 50) ->assertSeeIn('@text', 'livewire') // wire:text should update immediately ->pause(200) // Wait for the request to be handled ->assertScript('window.requests', 1); // Only one request was sent } public function test_debounces_requests_with_custom_duration() { Livewire::visit(new class extends Component { public $foo; public function render() { return <<<'HTML' <div x-init="window.requests = 0"> <input type="text" wire:model.live.debounce.250ms="foo" dusk="input"> <span wire:text="foo" dusk="text"></span> </div> @script <script> this.intercept(({ onSend }) => { onSend(() => { window.requests++ }) }) </script> @endscript HTML; } }) ->waitForLivewireToLoad() ->typeSlowly('@input', 'livewire', 50) ->assertSeeIn('@text', 'livewire') // wire:text should update immediately ->pause(300) // Wait for the request to be handled ->assertScript('window.requests', 1); // Only one request was sent } public function test_throttles_requests_with_custom_duration() { Livewire::visit(new class extends Component { public $foo; public function render() { return <<<'HTML' <div x-init="window.requests = 0"> <input type="text" wire:model.live.throttle.250ms="foo" dusk="input"> <span wire:text="foo" dusk="text"></span> </div> @script <script> this.intercept(({ onSend }) => { onSend(() => { window.requests++ }) }) </script> @endscript HTML; } }) ->waitForLivewireToLoad() ->typeSlowly('@input', 'livewire', 40) // 320ms total ->assertSeeIn('@text', 'livewire') // wire:text should update immediately ->pause(200) // Wait for the request to be handled ->assertScript('window.requests', 2); // Two requests: after 250ms and 500ms } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWithMethod/UnitTest.php
src/Features/SupportWithMethod/UnitTest.php
<?php namespace Livewire\Features\SupportWithMethod; use Livewire\Component; use Livewire\Livewire; use Tests\TestCase; class UnitTest extends TestCase { public function test_with_method_provides_data_to_view() { $component = Livewire::test(ComponentWithWith::class); $component->assertSee('bar'); $component->assertSee('Hello World'); } public function test_component_without_with_method_works_normally() { $component = Livewire::test(ComponentWithoutWith::class); $component->assertSee('Normal component'); } public function test_with_method_returning_non_array_is_ignored() { $component = Livewire::test(ComponentWithInvalidWith::class); $component->assertSee('Invalid component'); $component->assertDontSee('invalid data'); } public function test_with_method_data_overrides_component_properties() { $component = Livewire::test(ComponentWithOverridingWith::class); // The 'foo' from the with() method should override the component property $component->assertSee('from with method'); $component->assertDontSee('from property'); } } class ComponentWithWith extends Component { public function with() { return [ 'foo' => 'bar', 'message' => 'Hello World', ]; } public function render() { return <<<'HTML' <div> <span>{{ $foo }}</span> <span>{{ $message }}</span> </div> HTML; } } class ComponentWithoutWith extends Component { public function render() { return '<div>Normal component</div>'; } } class ComponentWithInvalidWith extends Component { public function with() { return 'invalid data'; // Not an array } public function render() { return '<div>Invalid component</div>'; } } class ComponentWithOverridingWith extends Component { public $foo = 'from property'; public function with() { return [ 'foo' => 'from with method', ]; } public function render() { return '<div>{{ $foo }}</div>'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWithMethod/SupportWithMethod.php
src/Features/SupportWithMethod/SupportWithMethod.php
<?php namespace Livewire\Features\SupportWithMethod; use Livewire\ComponentHook; use function Livewire\wrap; class SupportWithMethod extends ComponentHook { public function render($view, $data) { // Check if the component has a with() method if (! method_exists($this->component, 'with')) { return; } // Call the with() method and get the additional data $withData = wrap($this->component)->with(); // Ensure the with() method returns an array if (! is_array($withData)) { return; } // Merge the with() data with the existing view data, giving precedence to with() data $mergedData = array_merge($data, $withData); // Update the view's data with the merged data $view->with($withData); } public function renderIsland($name, $view, $data) { // Check if the component has a with() method if (! method_exists($this->component, 'with')) { return; } // Call the with() method and get the additional data $withData = wrap($this->component)->with(); // Ensure the with() method returns an array if (! is_array($withData)) { return; } // Merge the with() data with the existing view data, giving precedence to with() data $mergedData = array_merge($data, $withData); // Update the view's data with the merged data $view->with($withData); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSingleAndMultiFileComponents/SupportSingleAndMultiFileComponents.php
src/Features/SupportSingleAndMultiFileComponents/SupportSingleAndMultiFileComponents.php
<?php namespace Livewire\Features\SupportSingleAndMultiFileComponents; use Livewire\ComponentHook; class SupportSingleAndMultiFileComponents extends ComponentHook { static function provide() { // } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSingleAndMultiFileComponents/BrowserTest.php
src/Features/SupportSingleAndMultiFileComponents/BrowserTest.php
<?php namespace Livewire\Features\SupportSingleAndMultiFileComponents; use Livewire\Livewire; use Illuminate\Support\Facades\Route; class BrowserTest extends \Tests\BrowserTestCase { public static function tweakApplicationHook() { return function () { app('livewire.finder')->addLocation(viewPath: __DIR__ . '/fixtures'); }; } public function test_single_file_component_script() { Livewire::visit('sfc-scripts') ->waitForLivewireToLoad() // Pause for a moment to allow the script to be loaded... ->pause(100) ->assertSeeIn('@foo', 'baz'); } public function test_single_file_component_script_with_js_action() { Livewire::visit('sfc-scripts-with-js-action') ->waitForLivewireToLoad() // Pause for a moment to allow the script to be loaded... ->pause(100) ->assertSeeIn('@foo', 'bar') ->click('@set-foo') ->assertSeeIn('@foo', 'baz'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSingleAndMultiFileComponents/UnitTest.php
src/Features/SupportSingleAndMultiFileComponents/UnitTest.php
<?php namespace Livewire\Features\SupportSingleAndMultiFileComponents; use Livewire\Livewire; class UnitTest extends \Tests\TestCase { public function test_can_use_single_file_component() { app('livewire.finder')->addLocation(viewPath: __DIR__ . '/fixtures'); Livewire::test('sfc-counter') ->assertSee('Count: 1') ->call('increment') ->assertSee('Count: 2'); } public function test_can_use_multi_file_component() { app('livewire.finder')->addLocation(viewPath: __DIR__ . '/fixtures'); Livewire::test('mfc-counter') ->assertSee('Count: 1') ->call('increment') ->assertSee('Count: 2'); } public function test_sfc_component_includes_the_view_method_and_data_is_passed_to_the_view() { app('livewire.finder')->addLocation(viewPath: __DIR__ . '/fixtures'); Livewire::test('sfc-component-with-render-and-data') ->assertSee('Message: Hello World'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSingleAndMultiFileComponents/fixtures/sfc-scripts.blade.php
src/Features/SupportSingleAndMultiFileComponents/fixtures/sfc-scripts.blade.php
<?php new class extends Livewire\Component { public int $count = 1; public function increment() { $this->count++; } }; ?> <div> <div dusk="foo">bar</div> </div> <script> this.$el.querySelector('[dusk="foo"]').textContent = 'baz'; </script>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSingleAndMultiFileComponents/fixtures/sfc-component-with-render-and-data.blade.php
src/Features/SupportSingleAndMultiFileComponents/fixtures/sfc-component-with-render-and-data.blade.php
<?php use Livewire\Component; new class extends Component { public function render() { return $this->view([ 'message' => 'Hello World', ]); } }; ?> <div>Message: {{ $message }}</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSingleAndMultiFileComponents/fixtures/sfc-scripts-with-js-action.blade.php
src/Features/SupportSingleAndMultiFileComponents/fixtures/sfc-scripts-with-js-action.blade.php
<?php new class extends \Livewire\Component { public $foo = 'bar'; }; ?> <div> <div dusk="foo" wire:text="$js.getFoo"></div> <button wire:click="$js.setFoo('baz')" dusk="set-foo">Set Foo</button> </div> <script> this.$js.getFoo = () => { return this.foo; } this.$js.setFoo = (value) => { this.foo = value; } </script>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportSingleAndMultiFileComponents/fixtures/sfc-counter.blade.php
src/Features/SupportSingleAndMultiFileComponents/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/SupportSingleAndMultiFileComponents/fixtures/mfc-counter/mfc-counter.blade.php
src/Features/SupportSingleAndMultiFileComponents/fixtures/mfc-counter/mfc-counter.blade.php
<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/SupportSingleAndMultiFileComponents/fixtures/mfc-counter/mfc-counter.php
src/Features/SupportSingleAndMultiFileComponents/fixtures/mfc-counter/mfc-counter.php
<?php new class extends Livewire\Component { public int $count = 1; public function increment() { $this->count++; } }; ?>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportStdClasses/UnitTest.php
src/Features/SupportStdClasses/UnitTest.php
<?php namespace Livewire\Features\SupportStdClasses; use Livewire\Component; use Livewire\Livewire; use Tests\BrowserTestCase; class UnitTest extends BrowserTestCase { function test_can_use_wire_stdclass_property() { Livewire::test(new class extends Component { public $obj; function mount() { $this->obj = (object)[]; } function render() { return <<<'HTML' <div> <input type="text" dusk="input" wire:model.live="obj.property" /> <span dusk="output">{{ $obj?->property ?? '' }}</span> </div> HTML; } }) ->assertSetStrict('obj.property', null) ->set('obj.property', 'foo') ->assertSetStrict('obj.property', 'foo') ->set('obj.property', 'bar') ->assertSetStrict('obj.property', 'bar') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportAccessingParent/BrowserTest.php
src/Features/SupportAccessingParent/BrowserTest.php
<?php namespace Livewire\Features\SupportAccessingParent; use LegacyTests\Browser\TestCase; use Livewire\Component; class BrowserTest extends TestCase { public function test_can_access_parent() { $this->browse(function ($browser) { $this->visitLivewireComponent($browser, [ParentCounter::class, 'child-counter' => ChildCounter::class]) ->assertSeeIn('@output', '1') ->waitForLivewire()->click('@button') ->waitForTextIn('@output', '2') ->assertSeeIn('@output', '2') ; }); } } class ParentCounter extends Component { public $count = 1; function increment() { $this->count++; } public function render() { return <<<'HTML' <div> <span dusk="output">{{ $count }}</span> <livewire:child-counter /> </div> HTML; } } class ChildCounter extends Component { public function render() { return <<<'HTML' <div> <button wire:click="$parent.increment()" dusk="button"></button> </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/FileUploadConfiguration.php
src/Features/SupportFileUploads/FileUploadConfiguration.php
<?php namespace Livewire\Features\SupportFileUploads; use Illuminate\Support\Facades\Storage; use League\Flysystem\WhitespacePathNormalizer; class FileUploadConfiguration { public static function storage() { $disk = static::disk(); if (app()->runningUnitTests()) { // We want to "fake" the first time in a test run, but not again because // Storage::fake() wipes the storage directory every time its called. rescue( // If the storage disk is not found (meaning it's the first time), // this will throw an error and trip the second callback. fn() => Storage::disk($disk), fn() => Storage::fake($disk), // swallows the error that is thrown on the first try report: false ); } return Storage::disk($disk); } public static function disk() { if (app()->runningUnitTests()) { return 'tmp-for-tests'; } return config('livewire.temporary_file_upload.disk') ?: config('filesystems.default'); } public static function diskConfig() { return config('filesystems.disks.'.static::disk()); } public static function isUsingS3() { $diskBeforeTestFake = config('livewire.temporary_file_upload.disk') ?: config('filesystems.default'); return config('filesystems.disks.'.strtolower($diskBeforeTestFake).'.driver') === 's3'; } public static function isUsingGCS() { $diskBeforeTestFake = config('livewire.temporary_file_upload.disk') ?: config('filesystems.default'); return config('filesystems.disks.'.strtolower($diskBeforeTestFake).'.driver') === 'gcs'; } public static function normalizeRelativePath($path) { return (new WhitespacePathNormalizer)->normalizePath($path); } public static function directory() { return static::normalizeRelativePath(config('livewire.temporary_file_upload.directory') ?: 'livewire-tmp'); } protected static function s3Root() { if (! static::isUsingS3()) return ''; $diskConfig = static::diskConfig(); if (! is_array($diskConfig)) return ''; $root = $diskConfig['root'] ?? null; return $root !== null ? static::normalizeRelativePath($root) : ''; } public static function path($path = '', $withS3Root = true) { $prefix = $withS3Root ? static::s3Root() : ''; $directory = static::directory(); $path = static::normalizeRelativePath($path); return $prefix.($prefix ? '/' : '').$directory.($path ? '/' : '').$path; } public static function mimeType($filename) { $mimeType = static::storage()->mimeType(static::path($filename)); return $mimeType === 'image/svg' ? 'image/svg+xml' : $mimeType; } public static function lastModified($filename) { return static::storage()->lastModified($filename); } public static function middleware() { return config('livewire.temporary_file_upload.middleware') ?: 'throttle:60,1'; } public static function shouldCleanupOldUploads() { return config('livewire.temporary_file_upload.cleanup', true); } public static function rules() { $rules = config('livewire.temporary_file_upload.rules'); if (is_null($rules)) return ['required', 'file', 'max:12288']; if (is_array($rules)) return $rules; return explode('|', $rules); } public static function maxUploadTime() { return config('livewire.temporary_file_upload.max_upload_time') ?: 5; } public static function storeTemporaryFile($file, $disk) { $filename = TemporaryUploadedFile::generateHashName($file); $metaFilename = $filename . '.json'; Storage::disk($disk)->put('/'.static::path($metaFilename), json_encode([ 'name' => $file->getClientOriginalName(), 'type' => $file->getMimeType(), 'size' => $file->getSize(), 'hash' => $file->hashName(), ])); return $file->storeAs('/'.static::path(), $filename, [ 'disk' => $disk ]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/GenerateSignedUploadUrl.php
src/Features/SupportFileUploads/GenerateSignedUploadUrl.php
<?php namespace Livewire\Features\SupportFileUploads; use Illuminate\Support\Facades\URL; use function Livewire\invade; class GenerateSignedUploadUrl { public function forLocal() { return URL::temporarySignedRoute( 'livewire.upload-file', now()->addMinutes(FileUploadConfiguration::maxUploadTime()) ); } public function forS3($file, $visibility = 'private') { $storage = FileUploadConfiguration::storage(); $driver = $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; $fileType = $file->getMimeType(); $fileHashName = TemporaryUploadedFile::generateHashNameWithOriginalNameEmbedded($file); $path = FileUploadConfiguration::path($fileHashName); $command = $client->getCommand('putObject', array_filter([ 'Bucket' => $bucket, 'Key' => $path, 'ACL' => $visibility, 'ContentType' => $fileType ?: 'application/octet-stream', 'CacheControl' => null, 'Expires' => null, ])); $signedRequest = $client->createPresignedRequest( $command, '+' . FileUploadConfiguration::maxUploadTime() . ' minutes' ); $uri = $signedRequest->getUri(); if (filled($url = $storage->getConfig()['temporary_url'] ?? null)) { $uri = invade($storage)->replaceBaseUrl($uri, $url); } return [ 'path' => $fileHashName, 'url' => (string) $uri, 'headers' => $this->headers($signedRequest, $fileType), ]; } protected function headers($signedRequest, $fileType) { return array_merge( $signedRequest->getHeaders(), [ 'Content-Type' => $fileType ?: 'application/octet-stream' ] ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/FileNotPreviewableException.php
src/Features/SupportFileUploads/FileNotPreviewableException.php
<?php namespace Livewire\Features\SupportFileUploads; use Livewire\Exceptions\BypassViewHandler; class FileNotPreviewableException extends \Exception { use BypassViewHandler; public function __construct(TemporaryUploadedFile $file) { parent::__construct( "File with extension \"{$file->guessExtension()}\" is not previewable. See the livewire.temporary_file_upload.preview_mimes config." ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/FileUploadSynth.php
src/Features/SupportFileUploads/FileUploadSynth.php
<?php namespace Livewire\Features\SupportFileUploads; use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; use Illuminate\Http\UploadedFile; class FileUploadSynth extends Synth { public static $key = 'fil'; static function match($target) { return $target instanceof UploadedFile; } function dehydrate($target) { return [$this->dehydratePropertyFromWithFileUploads($target), []]; } public function dehydratePropertyFromWithFileUploads($value) { if (TemporaryUploadedFile::canUnserialize($value)) { return TemporaryUploadedFile::unserializeFromLivewireRequest($value); } if ($value instanceof TemporaryUploadedFile) { return $value->serializeForLivewireResponse(); } if (is_array($value) && isset(array_values($value)[0])) { $isValid = true; foreach ($value as $key => $arrayValue) { if (!($arrayValue instanceof TemporaryUploadedFile) || !is_numeric($key)) { $isValid = false; break; } } if ($isValid) { return array_values($value)[0]::serializeMultipleForLivewireResponse($value); } } if (is_array($value)) { foreach ($value as $key => $item) { $value[$key] = $this->dehydratePropertyFromWithFileUploads($item); } } if ($value instanceof \Livewire\Wireable) { $keys = array_keys(get_object_vars($value)); foreach ($keys as $key) { $value->{$key} = $this->dehydratePropertyFromWithFileUploads($value->{$key}); } } return $value; } function hydrate($value) { if (TemporaryUploadedFile::canUnserialize($value)) { return TemporaryUploadedFile::unserializeFromLivewireRequest($value); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/FileUploadController.php
src/Features/SupportFileUploads/FileUploadController.php
<?php namespace Livewire\Features\SupportFileUploads; use Illuminate\Routing\Controllers\HasMiddleware; use Illuminate\Routing\Controllers\Middleware; use Illuminate\Support\Facades\Validator; class FileUploadController implements HasMiddleware { public static array $defaultMiddleware = ['web']; public static function middleware() { $middleware = (array) FileUploadConfiguration::middleware(); // Prepend the default middleware to the middleware array if it's not already present... foreach (array_reverse(static::$defaultMiddleware) as $defaultMiddleware) { if (! in_array($defaultMiddleware, $middleware)) { array_unshift($middleware, $defaultMiddleware); } } return array_map(fn ($middleware) => new Middleware($middleware), $middleware); } public function handle() { abort_unless(request()->hasValidSignature(), 401); $disk = FileUploadConfiguration::disk(); $filePaths = $this->validateAndStore(request('files'), $disk); return ['paths' => $filePaths]; } public function validateAndStore($files, $disk) { Validator::make(['files' => $files], [ 'files.*' => FileUploadConfiguration::rules() ])->validate(); $fileHashPaths = collect($files)->map(function ($file) use ($disk) { return FileUploadConfiguration::storeTemporaryFile($file, $disk); }); // Strip out the temporary upload directory from the paths. return $fileHashPaths->map(function ($path) { return str_replace(FileUploadConfiguration::path('/'), '', $path); }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/TemporaryUploadedFile.php
src/Features/SupportFileUploads/TemporaryUploadedFile.php
<?php namespace Livewire\Features\SupportFileUploads; use Illuminate\Support\Arr; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\URL; use Illuminate\Support\Facades\Storage; use League\MimeTypeDetection\FinfoMimeTypeDetector; class TemporaryUploadedFile extends UploadedFile { protected $disk; protected $storage; protected $path; protected $metaFileData; public function __construct($path, $disk) { $this->disk = $disk; $this->storage = Storage::disk($this->disk); $this->path = FileUploadConfiguration::path($path, false); $tmpFile = tmpfile(); parent::__construct(stream_get_meta_data($tmpFile)['uri'], $this->path); // While running tests, update the last modified timestamp to the current // Carbon timestamp (which respects time traveling), because otherwise // cleanupOldUploads() will mess up with the filesystem... if (app()->runningUnitTests()) { @touch($this->path(), now()->timestamp); } } public function getPath(): string { return $this->storage->path(FileUploadConfiguration::directory()); } public function isValid(): bool { return true; } public function getSize(): int { if (app()->runningUnitTests()) { if (isset($this->metaFileData()['size'])) { return $this->metaFileData()['size']; } // This is for backwards compatibility when test file meta data was stored in the filename... if (str($this->getFilename())->contains('-size=')) { return (int) str($this->getFilename())->between('-size=', '.')->__toString(); } } return (int) $this->storage->size($this->path); } public function getMimeType(): string { if (app()->runningUnitTests()) { if (isset($this->metaFileData()['type'])) { return $this->metaFileData()['type']; } // This is for backwards compatibility when test file meta data was stored in the filename... if (str($this->getFilename())->contains('-mimeType=')) { $escapedMimeType = str($this->getFilename())->between('-mimeType=', '-'); // MimeTypes contain slashes, but we replaced them with underscores in `SupportTesting\Testable` // to ensure the filename is valid, so we now need to revert that. return (string) $escapedMimeType->replace('_', '/'); } } $mimeType = $this->storage->mimeType($this->path); // Flysystem V2.0+ removed guess mimeType from extension support, so it has been re-added back // in here to ensure the correct mimeType is returned when using faked files in tests if (in_array($mimeType, ['application/octet-stream', 'inode/x-empty', 'application/x-empty'])) { $detector = new FinfoMimeTypeDetector(); $mimeType = $detector->detectMimeTypeFromPath($this->path) ?: 'text/plain'; } return $mimeType; } public function getFilename(): string { return $this->getName($this->path); } public function getRealPath(): string { return $this->storage->path($this->path); } public function getPathname(): string { return $this->getRealPath(); } public function getClientOriginalName(): string { return $this->extractOriginalNameFromMetaFileData() ?? $this->extractOriginalNameFromFilePath($this->path); } public function dimensions() { stream_copy_to_stream($this->storage->readStream($this->path), $tmpFile = tmpfile()); return @getimagesize(stream_get_meta_data($tmpFile)['uri']); } public function temporaryUrl() { if (!$this->isPreviewable()) { throw new FileNotPreviewableException($this); } if ((FileUploadConfiguration::isUsingS3() or FileUploadConfiguration::isUsingGCS()) && ! app()->runningUnitTests()) { return $this->storage->temporaryUrl( $this->path, now()->addDay()->endOfHour(), ['ResponseContentDisposition' => 'attachment; filename="' . urlencode($this->getClientOriginalName()) . '"'] ); } if (method_exists($this->storage->getAdapter(), 'getTemporaryUrl')) { // This will throw an error because it's not used with S3. return $this->storage->temporaryUrl($this->path, now()->addDay()); } return URL::temporarySignedRoute( 'livewire.preview-file', now()->addMinutes(30)->endOfHour(), ['filename' => $this->getFilename()] ); } public function isPreviewable() { $supportedPreviewTypes = config('livewire.temporary_file_upload.preview_mimes', [ 'png', 'gif', 'bmp', 'svg', 'wav', 'mp4', 'mov', 'avi', 'wmv', 'mp3', 'm4a', 'jpg', 'jpeg', 'mpga', 'webp', 'wma', ]); return in_array($this->guessExtension(), $supportedPreviewTypes); } public function readStream() { return $this->storage->readStream($this->path); } public function exists() { return $this->storage->exists($this->path); } public function get() { return $this->storage->get($this->path); } public function delete() { return $this->storage->delete($this->path); } public function storeAs($path, $name = null, $options = []) { $options = $this->parseOptions($options); $disk = Arr::pull($options, 'disk') ?: $this->disk; $newPath = trim($path.'/'.$name, '/'); Storage::disk($disk)->put( $newPath, $this->storage->readStream($this->path), $options ); return $newPath; } public static function generateHashName($file) { $hash = str()->random(40); $extension = '.'.$file->getClientOriginalExtension(); return $hash.$extension; } public static function generateHashNameWithOriginalNameEmbedded($file) { $hash = str()->random(30); $meta = str('-meta'.base64_encode($file->getClientOriginalName()).'-')->replace('/', '_'); $extension = '.'.$file->getClientOriginalExtension(); return $hash.$meta.$extension; } public function hashName($path = null) { if (app()->runningUnitTests()) { if (isset($this->metaFileData()['hash'])) { return $this->metaFileData()['hash']; } // This is for backwards compatibility when test file meta data was stored in the filename... if (str($this->getFilename())->contains('-hash=')) { return str($this->getFilename())->between('-hash=', '-mimeType')->value(); } } return parent::hashName($path); } public function extractOriginalNameFromFilePath($path) { return base64_decode(head(explode('-', last(explode('-meta', str($path)->replace('_', '/')))))); } public function extractOriginalNameFromMetaFileData() { return $this->metaFileData()['name'] ?? null; } public function metaFileData() { if (is_null($this->metaFileData)) { $this->metaFileData = []; if ($contents = $this->storage->get($this->path.'.json')) { $contents = json_decode($contents, true); $this->metaFileData = $contents; } } return $this->metaFileData; } public static function createFromLivewire($filePath) { return new static($filePath, FileUploadConfiguration::disk()); } public static function canUnserialize($subject) { if (is_string($subject)) { return (string) str($subject)->startsWith(['livewire-file:', 'livewire-files:']); } if (is_array($subject)) { return collect($subject)->contains(function ($value) { return static::canUnserialize($value); }); } return false; } public static function unserializeFromLivewireRequest($subject) { if (is_string($subject)) { if (str($subject)->startsWith('livewire-file:')) { return static::createFromLivewire(str($subject)->after('livewire-file:')); } if (str($subject)->startsWith('livewire-files:')) { $paths = json_decode(str($subject)->after('livewire-files:'), true); return collect($paths)->map(function ($path) { return static::createFromLivewire($path); })->toArray(); } } if (is_array($subject)) { foreach ($subject as $key => $value) { $subject[$key] = static::unserializeFromLivewireRequest($value); } } return $subject; } public function serializeForLivewireResponse() { return 'livewire-file:'.$this->getFilename(); } public static function serializeMultipleForLivewireResponse($files) { return 'livewire-files:'.json_encode(collect($files)->map->getFilename()); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/WithFileUploads.php
src/Features/SupportFileUploads/WithFileUploads.php
<?php namespace Livewire\Features\SupportFileUploads; use Facades\Livewire\Features\SupportFileUploads\GenerateSignedUploadUrl; use Illuminate\Validation\ValidationException; use Illuminate\Http\UploadedFile; use Livewire\Attributes\Renderless; trait WithFileUploads { #[Renderless] function _startUpload($name, $fileInfo, $isMultiple) { if (FileUploadConfiguration::isUsingS3()) { throw_if($isMultiple, S3DoesntSupportMultipleFileUploads::class); $file = UploadedFile::fake()->create($fileInfo[0]['name'], $fileInfo[0]['size'] / 1024, $fileInfo[0]['type']); $this->dispatch('upload:generatedSignedUrlForS3', name: $name, payload: GenerateSignedUploadUrl::forS3($file))->self(); return; } $this->dispatch('upload:generatedSignedUrl', name: $name, url: GenerateSignedUploadUrl::forLocal())->self(); } function _finishUpload($name, $tmpPath, $isMultiple, $append = true) { if (FileUploadConfiguration::shouldCleanupOldUploads()) { $this->cleanupOldUploads(); } if ($isMultiple) { $file = collect($tmpPath)->map(function ($i) { return TemporaryUploadedFile::createFromLivewire($i); })->toArray(); $this->dispatch('upload:finished', name: $name, tmpFilenames: collect($file)->map->getFilename()->toArray())->self(); if ($append) { $existing = $this->getPropertyValue($name); if ($existing instanceof \Illuminate\Support\Collection) { $file = $existing->merge($file); } elseif (is_array($existing)) { $file = array_merge($existing, $file); } } } else { $file = TemporaryUploadedFile::createFromLivewire($tmpPath[0]); $this->dispatch('upload:finished', name: $name, tmpFilenames: [$file->getFilename()])->self(); // If the property is an array, but the upload ISNT set to "multiple" // then APPEND the upload to the array, rather than replacing it. if (is_array($value = $this->getPropertyValue($name))) { $file = array_merge($value, [$file]); } } app('livewire')->updateProperty($this, $name, $file); } function _uploadErrored($name, $errorsInJson, $isMultiple) { $this->dispatch('upload:errored', name: $name)->self(); if (is_null($errorsInJson)) { // Handle any translations/custom names $translator = app()->make('translator'); $attribute = $translator->get("validation.attributes.{$name}"); if ($attribute === "validation.attributes.{$name}") $attribute = $name; $message = trans('validation.uploaded', ['attribute' => $attribute]); if ($message === 'validation.uploaded') $message = "The {$name} failed to upload."; throw ValidationException::withMessages([$name => $message]); } $errorsInJson = $isMultiple ? str_ireplace('files', $name, $errorsInJson) : str_ireplace('files.0', $name, $errorsInJson); $errors = json_decode($errorsInJson, true)['errors']; throw (ValidationException::withMessages($errors)); } function _removeUpload($name, $tmpFilename) { $uploads = $this->getPropertyValue($name); if (is_array($uploads) && isset($uploads[0]) && $uploads[0] instanceof TemporaryUploadedFile) { $this->dispatch('upload:removed', name: $name, tmpFilename: $tmpFilename)->self(); app('livewire')->updateProperty($this, $name, array_values(array_filter($uploads, function ($upload) use ($tmpFilename) { if ($upload->getFilename() === $tmpFilename) { $upload->delete(); return false; } return true; }))); } elseif ($uploads instanceof TemporaryUploadedFile && $uploads->getFilename() === $tmpFilename) { $uploads->delete(); $this->dispatch('upload:removed', name: $name, tmpFilename: $tmpFilename)->self(); app('livewire')->updateProperty($this, $name, null); } } protected function cleanupOldUploads() { if (FileUploadConfiguration::isUsingS3()) return; $storage = FileUploadConfiguration::storage(); foreach ($storage->allFiles(FileUploadConfiguration::path()) as $filePathname) { // On busy websites, this cleanup code can run in multiple threads causing part of the output // of allFiles() to have already been deleted by another thread. if (! $storage->exists($filePathname)) continue; $yesterdaysStamp = now()->subDay()->timestamp; if ($yesterdaysStamp > $storage->lastModified($filePathname)) { $storage->delete($filePathname); } } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/BrowserTest.php
src/Features/SupportFileUploads/BrowserTest.php
<?php namespace Livewire\Features\SupportFileUploads; use Illuminate\Support\Facades\Storage; use Livewire\WithFileUploads; use Livewire\Component; use Livewire\Features\SupportValidation\BaseValidate; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_can_upload_preview_and_save_a_file() { Storage::persistentFake('tmp-for-tests'); Livewire::visit(new class extends Component { use WithFileUploads; public $photo; function mount() { Storage::disk('tmp-for-tests')->deleteDirectory('photos'); } function save() { $this->photo->storeAs('photos', 'photo.png'); } function render() { return <<<'HTML' <div> <input type="file" wire:model="photo" dusk="upload"> <div wire:loading wire:target="photo">uploading...</div> <button wire:click="$refresh">refresh</button> <div> @if ($photo) <img src="{{ $photo->temporaryUrl() }}" dusk="preview"> @endif </div> <button wire:click="save" dusk="save">Save</button> </div> HTML; } }) ->assertMissing('@preview') ->attach('@upload', __DIR__ . '/browser_test_image.png') ->waitFor('@preview') ->assertVisible('@preview') ->tap(function () { Storage::disk('tmp-for-tests')->assertMissing('photos/photo.png'); }) ->waitForLivewire() ->click('@save') ->tap(function () { Storage::disk('tmp-for-tests')->assertExists('photos/photo.png'); }) ; } public function test_can_cancel_an_upload() { if (getenv('FORCE_RUN') !== '1') { $this->markTestSkipped('Skipped'); } Storage::persistentFake('tmp-for-tests'); Livewire::visit(new class extends Component { use WithFileUploads; public $photo; function mount() { Storage::disk('tmp-for-tests')->deleteDirectory('photos'); } function save() { $this->photo->storeAs('photos', 'photo.png'); } function render() { return <<<'HTML' <div x-on:livewire-upload-cancel="$el.querySelector('h1').textContent = 'cancelled'"> <input type="file" wire:model="photo" dusk="upload"> <div wire:loading wire:target="photo">uploading...</div> <button wire:click="$cancelUpload('photo')" dusk="cancel">cancel</button> <h1 dusk="output"></h1> <button wire:click="save" dusk="save">Save</button> </div> HTML; } }) ->assertMissing('@preview') ->attach('@upload', __DIR__ . '/browser_test_image_big.jpg') ->pause(5) ->click('@cancel') ->assertSeeIn('@output', 'cancelled') ; } public function test_an_element_targeting_a_file_upload_retains_loading_state_until_the_upload_has_finished() { Storage::persistentFake('tmp-for-tests'); Livewire::visit(new class extends Component { use \Livewire\WithFileUploads; public $photo; public function render() { return <<<'HTML' <div> <input type="file" wire:model="photo" dusk="upload" /> <p wire:loading wire:target="photo" id="loading" dusk="loading">Loading</p> </div> HTML; } }) ->waitForLivewireToLoad() // Set a script to record if the loading element was displayed when `livewire-upload-progress` was fired ->tap(fn ($b) => $b->script([ "window.Livewire.first().on('livewire-upload-progress', () => { window.loadingWasDisplayed = document.getElementById('loading').style.display === 'inline-block' })", ])) ->assertMissing('@loading') ->waitForLivewire()->attach('@upload', __DIR__.'/browser_test_image_big.jpg') // Wait for Upload to finish ->waitUntilMissing('@loading') // Assert that the loading element was displayed while `livewire-upload-progress` was emitted ->assertScript('window.loadingWasDisplayed', true) ; } public function test_file_upload_being_renderless_is_not_impacted_by_real_time_validation() { Storage::persistentFake('tmp-for-tests'); Livewire::visit(new class extends Component { use \Livewire\WithFileUploads; #[BaseValidate(['required', 'min:3'])] public $foo; public $photo; public function render() { return <<<'HTML' <div> <input type="text" wire:model="foo" dusk="foo" /> <div> @error('foo') <span dusk="error">{{ $message }}</span> @enderror </div> <input type="file" wire:model="photo" dusk="upload" /> <div> @if ($photo) Preview <img src="{{ $photo->temporaryUrl() }}" dusk="preview"> @endif </div> </div> HTML; } }) ->assertNotPresent('@preview') ->assertNotPresent('@error') ->type('@foo', 'ba') ->waitForLivewire()->attach('@upload', __DIR__.'/browser_test_image_big.jpg') ->waitFor('@preview')->assertVisible('@preview') ->assertVisible('@error') ; } public function test_can_clear_out_file_input_after_property_has_been_reset() { Storage::persistentFake('tmp-for-tests'); Livewire::visit(new class extends Component { use WithFileUploads; public $photo; function mount() { Storage::disk('tmp-for-tests')->deleteDirectory('photos'); } function resetFileInput() { unset($this->photo); } function render() { return <<<'HTML' <div> <input type="file" wire:model="photo" dusk="upload"> <button wire:click="resetFileInput" dusk="resetFileInput">ResetFileInput</button> </div> HTML; } }) ->assertInputValue('@upload', null) ->attach('@upload', __DIR__ . '/browser_test_image.png') // Browsers will return the `C:\fakepath\` prefix for security reasons ->assertInputValue('@upload', 'C:\fakepath\browser_test_image.png') ->pause(250) ->waitForLivewire() ->click('@resetFileInput') ->assertInputValue('@upload', null) ; } public function test_can_clear_out_multiple_file_input_after_property_has_been_reset() { Storage::persistentFake('tmp-for-tests'); Livewire::visit(new class extends Component { use WithFileUploads; public $photos = []; function mount() { Storage::disk('tmp-for-tests')->deleteDirectory('photos'); } function resetFileInput() { $this->photos = []; } function render() { return <<<'HTML' <div> <input type="file" wire:model="photos" dusk="upload" multiple> <button wire:click="resetFileInput" dusk="resetFileInput">ResetFileInput</button> </div> HTML; } }) ->assertInputValue('@upload', null) ->attach('@upload', __DIR__ . '/browser_test_image.png') ->attach('@upload', __DIR__ . '/browser_test_image2.png') // Browsers will return the `C:\fakepath\` prefix for security reasons // The first file input should have the first file as the value, but it will display '2 files' in the label ->assertInputValue('@upload', 'C:\fakepath\browser_test_image.png') ->pause(250) ->waitForLivewire() ->click('@resetFileInput') ->assertInputValue('@upload', null) ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/UnitTest.php
src/Features/SupportFileUploads/UnitTest.php
<?php namespace Livewire\Features\SupportFileUploads; use App\Livewire\UploadFile; use Carbon\Carbon; use Illuminate\Filesystem\FilesystemAdapter; use Livewire\WithFileUploads; use Livewire\Livewire; use Livewire\Features\SupportDisablingBackButtonCache\SupportDisablingBackButtonCache; use League\Flysystem\PathTraversalDetected; use Illuminate\Validation\Rule; use Illuminate\Support\Facades\Storage; use Illuminate\Http\UploadedFile; use Facades\Livewire\Features\SupportFileUploads\GenerateSignedUploadUrl; use Illuminate\Http\Testing\FileFactory; use Illuminate\Support\Arr; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_component_must_have_file_uploads_trait_to_accept_file_uploads() { $this->expectException(MissingFileUploadsTraitException::class); Livewire::test(NonFileUploadComponent::class) ->set('photo', UploadedFile::fake()->image('avatar.jpg')); } public function test_s3_driver_only_supports_single_file_uploads() { config()->set('livewire.temporary_file_upload.disk', 's3'); $this->expectException(S3DoesntSupportMultipleFileUploads::class); Livewire::test(FileUploadComponent::class) ->set('photos', [UploadedFile::fake()->image('avatar.jpg')]); } public function test_can_set_a_file_as_a_property_and_store_it() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('upload', 'uploaded-avatar.png'); Storage::disk('avatars')->assertExists('uploaded-avatar.png'); } public function test_can_remove_a_file_property() { $file = UploadedFile::fake()->image('avatar.jpg'); $component = Livewire::test(FileUploadComponent::class) ->set('photo', $file); $tmpFilename = $component->viewData('photo')->getFilename(); $component->call('_removeUpload', 'photo', $tmpFilename) ->assertDispatched('upload:removed', name: 'photo', tmpFilename: $tmpFilename) ->assertSetStrict('photo', null); } public function test_cant_remove_a_file_property_with_mismatched_filename_provided() { $file = UploadedFile::fake()->image('avatar.jpg'); $component = Livewire::test(FileUploadComponent::class) ->set('photo', $file); $component->call('_removeUpload', 'photo', 'mismatched-filename.png') ->assertNotDispatched('upload:removed', name: 'photo', tmpFilename: 'mismatched-filename.png') ->assertNotSet('photo', null); } public function test_can_remove_a_file_from_an_array_of_files_property() { $file1 = UploadedFile::fake()->image('avatar1.jpg'); $file2 = UploadedFile::fake()->image('avatar2.jpg'); $component = Livewire::test(FileUploadComponent::class) ->set('photos', [$file1, $file2]); $tmpFiles = $component->viewData('photos'); $component->call('_removeUpload', 'photos', $tmpFiles[1]->getFilename()) ->assertDispatched('upload:removed', name: 'photos', tmpFilename: $tmpFiles[1]->getFilename()); $tmpFiles = $component->call('$refresh')->viewData('photos'); $this->assertCount(1, $tmpFiles); } public function test_if_the_file_property_is_an_array_the_uploaded_file_will_append_to_the_array() { Storage::fake('avatars'); $file1 = UploadedFile::fake()->image('avatar1.jpg'); $file2 = UploadedFile::fake()->image('avatar2.jpg'); Livewire::test(FileUploadComponent::class) ->set('photosArray', $file1) ->set('photosArray', $file2) ->call('uploadPhotosArray', 'uploaded-avatar'); Storage::disk('avatars')->assertExists('uploaded-avatar1.png'); Storage::disk('avatars')->assertExists('uploaded-avatar2.png'); } public function test_storing_a_file_returns_its_filename() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); $storedFilename = Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('uploadAndSetStoredFilename') ->get('storedFilename'); Storage::disk('avatars')->assertExists($storedFilename); } public function test_storing_a_file_uses_uploaded_file_hashname() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('uploadAndSetStoredFilename'); Storage::disk('avatars')->assertExists($file->hashName()); } public function test_can_get_a_file_original_name() { $file = UploadedFile::fake()->image('avatar.jpg'); $component = Livewire::test(FileUploadComponent::class) ->set('photo', $file); $tmpFile = $component->viewData('photo'); $this->assertEquals('avatar.jpg', $tmpFile->getClientOriginalName()); } public function test_can_get_multiple_files_original_name() { $file1 = UploadedFile::fake()->image('avatar1.jpg'); $file2 = UploadedFile::fake()->image('avatar2.jpg'); $component = Livewire::test(FileUploadComponent::class) ->set('photos', [$file1, $file2]); $tmpFiles = $component->viewData('photos'); $this->assertEquals('avatar1.jpg', $tmpFiles[0]->getClientOriginalName()); $this->assertEquals('avatar2.jpg', $tmpFiles[1]->getClientOriginalName()); } public function test_can_set_a_file_as_a_property_using_the_s3_driver_and_store_it() { config()->set('livewire.temporary_file_upload.disk', 's3'); Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('upload', 'uploaded-avatar.png'); Storage::disk('avatars')->assertExists('uploaded-avatar.png'); } public function test_can_set_multiple_files_as_a_property_and_store_them() { Storage::fake('avatars'); $file1 = UploadedFile::fake()->image('avatar1.jpg'); $file2 = UploadedFile::fake()->image('avatar2.jpg'); Livewire::test(FileUploadComponent::class) ->set('photos', [$file1, $file2]) ->call('uploadMultiple', 'uploaded-avatar'); Storage::disk('avatars')->assertExists('uploaded-avatar1.png'); Storage::disk('avatars')->assertExists('uploaded-avatar2.png'); } public function test_a_file_cant_be_larger_than_12mb_or_the_global_livewire_uploader_will_fail() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg')->size(13000); // 13MB Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->assertHasErrors('photo'); } public function test_the_global_upload_validation_rules_can_be_configured_and_the_error_messages_show_as_normal_validation_errors_for_the_property() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg')->size(100); // 100KB config()->set('livewire.temporary_file_upload.rules', 'file|max:50'); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->assertHasErrors('photo'); } public function test_multiple_files_cant_be_larger_than_12mb_or_the_global_livewire_uploader_will_fail() { Storage::fake('avatars'); $file1 = UploadedFile::fake()->image('avatar.jpg')->size(13000); // 13MB $file2 = UploadedFile::fake()->image('avatar.jpg')->size(13000); // 13MB Livewire::test(FileUploadComponent::class) ->set('photos', [$file1, $file2]) ->assertHasErrors('photos.0') ->assertHasErrors('photos.1'); } public function test_an_uploaded_file_can_be_validated() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg')->size(200); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('validateUpload') ->assertHasErrors(['photo' => 'max']); } public function test_multiple_uploaded_files_can_be_validated() { Storage::fake('avatars'); $file1 = UploadedFile::fake()->image('avatar.jpg'); $file2 = UploadedFile::fake()->image('avatar.jpg')->size(200); Livewire::test(FileUploadComponent::class) ->set('photos', [$file1, $file2]) ->call('validateMultipleUploads') ->assertHasErrors(['photos.1' => 'max']); } public function test_a_file_can_be_validated_in_real_time() { Storage::fake('avatars'); $file = UploadedFile::fake()->create('avatar.xls', 75); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->assertHasErrors(['photo' => 'image']); } public function test_multiple_files_can_be_validated_in_real_time() { Storage::fake('avatars'); $file1 = UploadedFile::fake()->image('avatar.png'); $file2 = UploadedFile::fake()->create('avatar.xls', 75); Livewire::test(FileUploadComponent::class) ->set('photos', [$file1, $file2]) ->assertHasErrors(['photos.1' => 'image']); } public function test_file_upload_global_validation_can_be_translated() { Storage::fake('avatars'); $translator = app()->make('translator'); $translator->addLines([ 'validation.uploaded' => 'The :attribute failed to upload.', 'validation.attributes.file' => 'upload' ], 'en'); $file = UploadedFile::fake()->create('upload.xls', 100); $test = Livewire::test(FileUploadComponent::class) ->set('file', $file) ->call('uploadError', 'file') ->assertHasErrors(['file']); $this->assertEquals('The upload failed to upload.', $test->errors()->get('file')[0]); } public function test_image_dimensions_can_be_validated() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.png', 100, 200); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('validateUploadWithDimensions') ->assertHasErrors(['photo' => 'dimensions']); Storage::disk('avatars')->assertMissing('uploaded-avatar.png'); } public function test_invalid_file_extension_can_validate_dimensions() { Storage::fake('avatars'); $file = UploadedFile::fake() ->create('not-a-png-image.pdf', 512, 512); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('validateUploadWithDimensions') ->assertHasErrors(['photo' => 'dimensions']); Storage::disk('avatars')->assertMissing('uploaded-not-a-png-image.png'); } public function test_temporary_files_older_than_24_hours_are_cleaned_up_on_every_new_upload() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); $file2 = UploadedFile::fake()->image('avatar.jpg'); $file3 = UploadedFile::fake()->image('avatar.jpg'); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('upload', 'uploaded-avatar.png'); Livewire::test(FileUploadComponent::class) ->set('photo', $file2) ->call('upload', 'uploaded-avatar2.png'); // 4 files because we have 2 files and 2 meta files... $this->assertCount(4, FileUploadConfiguration::storage()->allFiles()); // Make temporary files look 2 days old. foreach (FileUploadConfiguration::storage()->allFiles() as $fileShortPath) { touch(FileUploadConfiguration::storage()->path($fileShortPath), now()->subDays(2)->timestamp); } Livewire::test(FileUploadComponent::class) ->set('photo', $file3) ->call('upload', 'uploaded-avatar3.png'); // 2 files because we have 1 file and 1 meta file... $this->assertCount(2, FileUploadConfiguration::storage()->allFiles()); } public function test_temporary_files_older_than_24_hours_are_not_cleaned_up_if_configuration_specifies() { config()->set('livewire.temporary_file_upload.cleanup', false); Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); $file2 = UploadedFile::fake()->image('avatar.jpg'); $file3 = UploadedFile::fake()->image('avatar.jpg'); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('upload', 'uploaded-avatar.png'); Livewire::test(FileUploadComponent::class) ->set('photo', $file2) ->call('upload', 'uploaded-avatar2.png'); // 4 files because we have 2 files and 2 meta files... $this->assertCount(4, FileUploadConfiguration::storage()->allFiles()); // Make temporary files look 2 days old. foreach (FileUploadConfiguration::storage()->allFiles() as $fileShortPath) { touch(FileUploadConfiguration::storage()->path($fileShortPath), now()->subDays(2)->timestamp); } Livewire::test(FileUploadComponent::class) ->set('photo', $file3) ->call('upload', 'uploaded-avatar3.png'); // 6 files because we have 2 files and 4 meta files... $this->assertCount(6, FileUploadConfiguration::storage()->allFiles()); } public function test_temporary_files_older_than_24_hours_are_not_cleaned_up_on_every_new_upload_when_using_S3() { config()->set('livewire.temporary_file_upload.disk', 's3'); Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); $file2 = UploadedFile::fake()->image('avatar.jpg'); $file3 = UploadedFile::fake()->image('avatar.jpg'); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('upload', 'uploaded-avatar.png'); Livewire::test(FileUploadComponent::class) ->set('photo', $file2) ->call('upload', 'uploaded-avatar2.png'); // 4 files because we have 2 files and 2 meta files... $this->assertCount(4, FileUploadConfiguration::storage()->allFiles()); // Make temporary files look 2 days old. foreach (FileUploadConfiguration::storage()->allFiles() as $fileShortPath) { touch(FileUploadConfiguration::storage()->path($fileShortPath), now()->subDays(2)->timestamp); } Livewire::test(FileUploadComponent::class) ->set('photo', $file3) ->call('upload', 'uploaded-avatar3.png'); // 6 files because we have 2 files and 4 meta files... $this->assertCount(6, FileUploadConfiguration::storage()->allFiles()); } public function test_S3_can_be_configured_so_that_temporary_files_older_than_24_hours_are_cleaned_up_automatically() { $this->artisan('livewire:configure-s3-upload-cleanup'); // Can't "really" test this without using a live S3 bucket. $this->assertTrue(true); } public function test_the_global_upload_route_middleware_is_configurable() { config()->set('livewire.temporary_file_upload.middleware', DummyMiddleware::class); $url = GenerateSignedUploadUrl::forLocal(); try { $this->withoutExceptionHandling()->post($url); } catch (\Throwable $th) { $this->assertStringContainsString(DummyMiddleware::class, $th->getMessage()); } } public function test_the_global_upload_route_middleware_supports_multiple_middleware() { config()->set('livewire.temporary_file_upload.middleware', ['throttle:60,1', DummyMiddleware::class]); $url = GenerateSignedUploadUrl::forLocal(); try { $this->withoutExceptionHandling()->post($url); } catch (\Throwable $th) { $this->assertStringContainsString('throttle:60,1', $th->getMessage()); $this->assertStringContainsString(DummyMiddleware::class, $th->getMessage()); } } public function test_can_preview_a_temporary_file_with_a_temporary_signed_url() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); $photo = Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->viewData('photo'); // Due to Livewire object still being in memory, we need to // reset the "shouldDisableBackButtonCache" property back to its default // which is false to ensure it's not applied to the below route \Livewire\Features\SupportDisablingBackButtonCache\SupportDisablingBackButtonCache::$disableBackButtonCache = false; ob_start(); $this->get($photo->temporaryUrl())->sendContent(); $rawFileContents = ob_get_clean(); $this->assertEquals($file->get(), $rawFileContents); $this->assertTrue($photo->isPreviewable()); } public function test_file_is_not_sent_on_cache_hit() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); $photo = Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->viewData('photo'); ob_start(); $response = $this->get($photo->temporaryUrl()); $response->sendContent(); $rawFileContents = ob_get_clean(); $this->assertEquals($file->get(), $rawFileContents); ob_start(); $cachedResponse = $this->get($photo->temporaryUrl(), [ 'If-Modified-Since' => $response->headers->get('last-modified'), ]); $cachedResponse->sendContent(); $this->assertEquals(304, $cachedResponse->getStatusCode()); $cachedFileContents = ob_get_clean(); $this->assertEquals('', $cachedFileContents); } public function test_can_preview_a_temporary_file_on_a_remote_storage() { $disk = Storage::fake('tmp-for-tests'); // A remote storage will always return the short path when calling $disk->path(). To simulate a remote // storage, the fake storage will be recreated with an empty prefix option in order to get the short path even // if it's a local filesystem. Storage::set('tmp-for-tests', new FilesystemAdapter($disk->getDriver(), $disk->getAdapter(), ['prefix' => ''])); $file = UploadedFile::fake()->image('avatar.jpg'); $photo = Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->viewData('photo'); // Due to Livewire object still being in memory, we need to // reset the "shouldDisableBackButtonCache" property back to it's default // which is false to ensure it's not applied to the below route \Livewire\Features\SupportDisablingBackButtonCache\SupportDisablingBackButtonCache::$disableBackButtonCache = false; ob_start(); $this->get($photo->temporaryUrl())->sendContent(); $rawFileContents = ob_get_clean(); $this->assertEquals($file->get(), $rawFileContents); $this->assertTrue($photo->isPreviewable()); } public function test_cant_preview_a_non_image_temporary_file_with_a_temporary_signed_url() { Storage::fake('avatars'); $file = UploadedFile::fake()->create('avatar.pdf'); $photo = Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->viewData('photo'); $this->expectException(FileNotPreviewableException::class); $photo->temporaryUrl(); $this->assertFalse($photo->isPreviewable()); } public function test_allows_setting_file_types_for_temporary_signed_urls_in_config() { config()->set('livewire.temporary_file_upload.preview_mimes', ['pdf']); Storage::fake('advatars'); $file = UploadedFile::fake()->create('file.pdf'); $photo = Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->viewData('photo'); // Due to Livewire object still being in memory, we need to // reset the "shouldDisableBackButtonCache" property back to it's default // which is false to ensure it's not applied to the below route SupportDisablingBackButtonCache::$disableBackButtonCache = false; ob_start(); $this->get($photo->temporaryUrl())->sendContent(); $rawFileContents = ob_get_clean(); $this->assertEquals($file->get(), $rawFileContents); } public function test_public_temporary_file_url_must_have_valid_signature() { $photo = Livewire::test(FileUploadComponent::class) ->set('photo', UploadedFile::fake()->image('avatar.jpg')) ->viewData('photo'); $this->get(str($photo->temporaryUrl())->before('&signature='))->assertStatus(401); } public function test_file_paths_cant_include_slashes_which_would_allow_them_to_access_other_private_directories() { $this->expectException(PathTraversalDetected::class); $file = UploadedFile::fake()->image('avatar.jpg'); $component = Livewire::test(FileUploadComponent::class) ->set('photo', $file); // Try to hijack the photo property to a path outside the temporary livewire directory root. $component->set('photo', 'livewire-file:../dangerous.png') ->call('$refresh'); } public function test_can_preview_a_temporary_files_with_a_temporary_signed_url_from_s3() { config()->set('livewire.temporary_file_upload.disk', 's3'); Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); $photo = Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->viewData('photo'); // Due to Livewire object still being in memory, we need to // reset the "shouldDisableBackButtonCache" property back to it's default // which is false to ensure it's not applied to the below route SupportDisablingBackButtonCache::$disableBackButtonCache = false; // When testing, rather than trying to hit an s3 server, we just serve // the local driver preview URL. ob_start(); $this->get($photo->temporaryUrl())->sendContent(); $rawFileContents = ob_get_clean(); $this->assertEquals($file->get(), $rawFileContents); } public function test_removing_first_item_from_array_of_temporary_uploaded_files_serializes_correctly() { $file1 = UploadedFile::fake()->image('avatar1.jpg'); $file2 = UploadedFile::fake()->image('avatar2.jpg'); $file3 = UploadedFile::fake()->image('avatar3.jpg'); $file4 = UploadedFile::fake()->image('avatar4.jpg'); $component = Livewire::test(FileUploadComponent::class) ->set('photos', [$file1, $file2, $file3, $file4]); $this->assertCount(4, $component->snapshot['data']['photos'][0]); $component->call('removePhoto', 3); $this->assertCount(3, $component->snapshot['data']['photos'][0]); $component->call('removePhoto', 0); $this->assertCount(2, $component->snapshot['data']['photos'][0]); } public function test_removing_first_item_from_array_of_temporary_uploaded_files_serializes_correctly_with_in_array_public_property() { $file1 = UploadedFile::fake()->image('avatar1.jpg'); $file2 = UploadedFile::fake()->image('avatar2.jpg'); $file3 = UploadedFile::fake()->image('avatar3.jpg'); $file4 = UploadedFile::fake()->image('avatar4.jpg'); $component = Livewire::test(FileUploadInArrayComponent::class) ->set('obj.file_uploads', [$file1, $file2, $file3, $file4]) ->set('obj.first_name', 'john') ->set('obj.last_name', 'doe'); $this->assertSame($component->get('obj.first_name'), 'john'); $this->assertSame($component->get('obj.last_name'), 'doe'); $this->assertCount(4, $component->snapshot['data']['obj'][0]['file_uploads'][0]); $component->call('removePhoto', 3); $this->assertCount(3, $component->snapshot['data']['obj'][0]['file_uploads'][0]); $component->call('removePhoto', 0); $this->assertCount(2, $component->snapshot['data']['obj'][0]['file_uploads'][0]); } public function test_it_can_upload_multiple_file_within_array_public_property() { $file1 = UploadedFile::fake()->image('avatar1.jpg'); $file2 = UploadedFile::fake()->image('avatar2.jpg'); $file3 = UploadedFile::fake()->image('avatar3.jpg'); $file4 = UploadedFile::fake()->image('avatar4.jpg'); $component = Livewire::test(FileUploadInArrayComponent::class) ->set('obj.file_uploads', [$file1, $file2, $file3, $file4]) ->set('obj.first_name', 'john') ->set('obj.last_name', 'doe'); $tmpFiles = $component->viewData('obj')['file_uploads']; $this->assertSame($component->get('obj.first_name'), 'john'); $this->assertSame($component->get('obj.last_name'), 'doe'); $component->updateProperty('obj.first_number', 10); $this->assertSame($component->get('obj.first_number'), 10); $this->assertSame($component->get('obj.second_number'), 99); $this->assertStringStartsWith('livewire-file:', $component->snapshot['data']['obj'][0]['file_uploads'][0][0][0]); $this->assertStringStartsWith('livewire-file:', $component->snapshot['data']['obj'][0]['file_uploads'][0][1][0]); $this->assertStringStartsWith('livewire-file:', $component->snapshot['data']['obj'][0]['file_uploads'][0][2][0]); $this->assertStringStartsWith('livewire-file:', $component->snapshot['data']['obj'][0]['file_uploads'][0][3][0]); $this->assertCount(4, $tmpFiles); } public function test_it_can_upload_single_file_within_array_public_property() { $file1 = UploadedFile::fake()->image('avatar1.jpg'); $component = Livewire::test(FileUploadInArrayComponent::class) ->set('obj.file_uploads', $file1) ->set('obj.first_name', 'john') ->set('obj.last_name', 'doe'); $this->assertSame($component->get('obj.first_name'), 'john'); $this->assertSame($component->get('obj.last_name'), 'doe'); $component->updateProperty('obj.first_number', 10); $this->assertSame($component->get('obj.first_number'), 10); $this->assertSame($component->get('obj.second_number'), 99); $this->assertStringStartsWith('livewire-file:', $component->snapshot['data']['obj'][0]['file_uploads'][0]); } public function test_it_returns_temporary_path_set_by_livewire() { Storage::fake('avatars'); $file = UploadedFile::fake()->image($fileName = 'avatar.jpg'); $photo = Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('upload', $fileName) ->viewData('photo'); $this->assertEquals( FileUploadConfiguration::storage()->path(FileUploadConfiguration::directory()), $photo->getPath() ); } public function test_preview_url_is_stable_over_some_time() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); $photo = Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->viewData('photo'); Carbon::setTestNow(Carbon::today()->setTime(10, 01, 00)); $first_url = $photo->temporaryUrl(); Carbon::setTestNow(Carbon::today()->setTime(10, 05, 00)); $second_url = $photo->temporaryUrl(); $this->assertEquals($first_url, $second_url); } public function test_file_content_can_be_retrieved_from_temporary_uploaded_files() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.jpg'); Livewire::test(FileReadContentComponent::class) ->set('file', $file) ->assertSetStrict('content', $file->getContent()); } public function test_validation_of_file_uploads_while_time_traveling() { Storage::fake('avatars'); $this->travelTo(now()->addMonth()); $file = UploadedFile::fake()->image('avatar.jpg'); Livewire::test(FileUploadComponent::class) ->set('photo', $file) ->call('upload', 'uploaded-avatar.png'); Storage::disk('avatars')->assertExists('uploaded-avatar.png'); } public function test_extension_validation_cant_be_spoofed_by_manipulating_the_mime_type() { Storage::fake('avatars'); $file = (new \Illuminate\Http\Testing\FileFactory)->create('malicious.php', 0, 'image/png'); Livewire::test(FileExtensionValidatorComponent::class) ->set('photo', $file) ->call('save') ->assertHasErrors('photo'); Storage::disk('avatars')->assertMissing('malicious.php'); } public function test_the_file_upload_controller_middleware_prepends_the_web_group() { config()->set('livewire.temporary_file_upload.middleware', ['throttle:60,1']); $middleware = Arr::pluck(FileUploadController::middleware(), 'middleware'); $this->assertEquals(['web', 'throttle:60,1'], $middleware); } public function test_the_file_upload_controller_middleware_only_adds_the_web_group_if_absent() { config()->set('livewire.temporary_file_upload.middleware', ['throttle:60,1', 'web']); $middleware = Arr::pluck(FileUploadController::middleware(), 'middleware'); $this->assertEquals(['throttle:60,1', 'web'], $middleware); } public function test_temporary_file_uploads_guess_correct_mime_during_testing() { Livewire::test(UseProvidedMimeTypeDuringTestingComponent::class) ->set('photo', UploadedFile::fake()->create('file.png', 1000, 'application/pdf')) ->call('save') ->assertHasErrors([ 'photo' => 'mimetypes', ]); } public function test_the_default_file_upload_controller_middleware_overwritten() { config()->set('livewire.temporary_file_upload.middleware', ['throttle:60,1']); FileUploadController::$defaultMiddleware = ['tenant']; $middleware = Arr::pluck(FileUploadController::middleware(), 'middleware'); $this->assertEquals(['tenant', 'throttle:60,1'], $middleware); } public function test_a_meta_file_gets_stored_with_a_temporary_file() { $disk = Storage::fake('tmp-for-tests'); $file = UploadedFile::fake()->image('avatar.jpg'); $component = Livewire::test(FileUploadComponent::class) ->set('photo', $file); $temporaryFile = $component->get('photo'); $disk->assertExists('livewire-tmp/'.$temporaryFile->getFileName().'.json'); $metaFileData = $temporaryFile->metaFileData(); $this->assertEquals($file->getClientOriginalName(), $metaFileData['name']); $this->assertEquals($file->getMimeType(), $metaFileData['type']); $this->assertEquals($file->getSize(), $metaFileData['size']); $this->assertEquals($file->hashName(), $metaFileData['hash']); } public function test_file_name_falls_back_to_extracting_file_name_from_hash_if_no_meta_file_is_present() { $disk = Storage::fake('tmp-for-tests'); $file = UploadedFile::fake()->image('avatar.jpg'); $hashWithOriginalNameEmbedded = TemporaryUploadedFile::generateHashNameWithOriginalNameEmbedded($file); $disk->putFileAs('livewire-tmp', $file, $hashWithOriginalNameEmbedded); $temporaryFile = TemporaryUploadedFile::createFromLivewire($disk->path('livewire-tmp/'.$hashWithOriginalNameEmbedded)); $disk->assertMissing('livewire-tmp/'.$temporaryFile->getFileName().'.json'); $this->assertEquals($file->getClientOriginalName(), $temporaryFile->getClientOriginalName()); } } class DummyMiddleware { public function handle($request, $next) {
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/SupportFileUploads.php
src/Features/SupportFileUploads/SupportFileUploads.php
<?php namespace Livewire\Features\SupportFileUploads; use function Livewire\on; use Livewire\ComponentHook; use Illuminate\Support\Facades\Route; use Livewire\Mechanisms\HandleRequests\EndpointResolver; use Facades\Livewire\Features\SupportFileUploads\GenerateSignedUploadUrl as GenerateSignedUploadUrlFacade; class SupportFileUploads extends ComponentHook { static function provide() { if (app()->runningUnitTests()) { // Don't actually generate S3 signedUrls during testing. GenerateSignedUploadUrlFacade::swap(new class extends GenerateSignedUploadUrl { public function forS3($file, $visibility = '') { return []; } }); } app('livewire')->propertySynthesizer([ FileUploadSynth::class, ]); on('call', function ($component, $method, $params, $componentContext, $earlyReturn) { if ($method === '_startUpload') { if (! method_exists($component, $method)) { throw new MissingFileUploadsTraitException($component); } } }); Route::post(EndpointResolver::uploadPath(), [FileUploadController::class, 'handle']) ->name('livewire.upload-file'); Route::get(EndpointResolver::previewPath(), [FilePreviewController::class, 'handle']) ->name('livewire.preview-file'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/MissingFileUploadsTraitException.php
src/Features/SupportFileUploads/MissingFileUploadsTraitException.php
<?php namespace Livewire\Features\SupportFileUploads; use Exception; use Livewire\Exceptions\BypassViewHandler; class MissingFileUploadsTraitException extends Exception { use BypassViewHandler; public function __construct($component) { parent::__construct( "Cannot handle file upload without [Livewire\WithFileUploads] trait on the [{$component->getName()}] component class." ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/S3DoesntSupportMultipleFileUploads.php
src/Features/SupportFileUploads/S3DoesntSupportMultipleFileUploads.php
<?php namespace Livewire\Features\SupportFileUploads; use Exception; use Livewire\Exceptions\BypassViewHandler; class S3DoesntSupportMultipleFileUploads extends Exception { use BypassViewHandler; public function __construct() { parent::__construct( 'S3 temporary file upload driver only supports single file uploads. Remove the [multiple] HTML attribute from your input tag.' ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFileUploads/FilePreviewController.php
src/Features/SupportFileUploads/FilePreviewController.php
<?php namespace Livewire\Features\SupportFileUploads; use Illuminate\Routing\Controllers\HasMiddleware; use Illuminate\Routing\Controllers\Middleware; use Livewire\Drawer\Utils; class FilePreviewController implements HasMiddleware { public static array $middleware = ['web']; public static function middleware() { return array_map(fn ($middleware) => new Middleware($middleware), static::$middleware); } public function handle($filename) { abort_unless(request()->hasValidSignature(), 401); return Utils::pretendPreviewResponseIsPreviewFile($filename); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTeleporting/BrowserTest.php
src/Features/SupportTeleporting/BrowserTest.php
<?php namespace Livewire\Features\SupportTeleporting; use Livewire\Component; use Livewire\Livewire; use Tests\BrowserTestCase; class BrowserTest extends BrowserTestCase { public function test_can_teleport_dom_via_blade_directive() { Livewire::visit(new class extends Component { public function render() { return <<<'HTML' <div dusk="component"> @teleport('body') <span>teleportedbar</span> @endteleport </div> HTML; } }) ->assertDontSeeIn('@component', 'teleportedbar') ->assertSee('teleportedbar'); } public function test_can_teleport_dom_via_blade_directive_then_change_it() { Livewire::visit(new class extends Component { public $foo = 'bar'; public function setFoo() { $this->foo = 'baz'; } public function render() { return <<<'HTML' <div dusk="component"> <button dusk="setFoo" type="button" wire:click="setFoo"> Set foo </button> @teleport('body') <span>teleported{{ $foo }}</span> @endteleport </div> HTML; } }) ->assertDontSeeIn('@component', 'teleportedbar') ->assertSee('teleportedbar') ->waitForLivewire()->click('@setFoo') ->assertDontSeeIn('@component', 'teleportedbaz') ->assertSee('teleportedbaz'); } public function test_morphdom_doesnt_remove_subsequent_teleports_if_there_are_multiple() { Livewire::visit(new class extends Component { public $count = 1; public function render() { return <<<'HTML' <div dusk="component"> <button wire:click="$set('count', 2)" dusk="button">refresh</button> <div> <template x-teleport="body"> <span>first teleport. run ({{ $count }})</span> </template> <span dusk="first-check">{{ $count }}</span> </div> <div> <template x-teleport="body"> <span>second teleport. run ({{ $count }})</span> </template> <span dusk="second-check">{{ $count }}</span> </div> </div> HTML; } }) ->assertSee('first teleport') ->assertSee('second teleport') ->assertSeeIn('@first-check', '1') ->assertSeeIn('@second-check', '1') ->waitForLivewire()->click('@button') ->assertSee('first teleport') ->assertSee('second teleport') ->assertSeeIn('@first-check', '2') ->assertSeeIn('@second-check', '2'); } public function test_conditionally_rendered_elements_initialise_in_teleport() { Livewire::visit(new class extends Component { public $show = false; public $output = 'start'; public function thing1(){ $this->output .= 'thing1'; } public function thing2(){ $this->output .= 'thing2'; } public function render() { return <<<'HTML' <div> <button wire:click="$toggle('show')" dusk="show">Show</button> <p dusk="output">{{ $output }}</p> @teleport('body') <div> <button wire:click="thing1" dusk="thing1">Thing 1</button> @if ($show) <button wire:click="thing2" dusk="thing2">Thing 2</button> @endif </div> @endteleport </div> HTML; } }) ->assertSeeIn('@output', 'start') ->assertDontSeeIn('@output', 'thing1') ->assertDontSeeIn('@output', 'thing2') ->waitForLivewire()->click('@thing1') ->assertSeeIn('@output', 'startthing1') ->assertDontSeeIn('@output', 'thing2') ->waitForLivewire()->click('@show') ->assertSeeIn('@output', 'startthing1') ->assertDontSeeIn('@output', 'thing2') ->waitForLivewire()->click('@thing2') ->assertSeeIn('@output', 'startthing1thing2'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportTeleporting/SupportTeleporting.php
src/Features/SupportTeleporting/SupportTeleporting.php
<?php namespace Livewire\Features\SupportTeleporting; use Illuminate\Support\Facades\Blade; use Livewire\ComponentHook; class SupportTeleporting extends ComponentHook { static function provide() { Blade::directive('teleport', function ($expression) { return '<template x-teleport="<?php echo e('.$expression.'); ?>">'; }); Blade::directive('endteleport', function () { return '</template>'; }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportModels/ModelSynth.php
src/Features/SupportModels/ModelSynth.php
<?php namespace Livewire\Features\SupportModels; use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; use Livewire\Mechanisms\HandleComponents\ComponentContext; use Illuminate\Queue\SerializesAndRestoresModelIdentifiers; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\ClassMorphViolationException; class ModelSynth extends Synth { use SerializesAndRestoresModelIdentifiers, IsLazy; public static $key = 'mdl'; static function match($target) { return $target instanceof Model; } function dehydrate($target) { if ($this->isLazy($target)) { $meta = $this->getLazyMeta($target); return [ null, $meta, ]; } $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; } $serializedModel = $target->exists ? (array) $this->getSerializedPropertyValue($target) : null; $meta = ['class' => $alias]; // If the model doesn't exist as it's an empty model or has been // recently deleted, then we don't want to include any key. if ($serializedModel) $meta['key'] = $serializedModel['id']; return [ null, $meta, ]; } function hydrate($data, $meta) { $class = $meta['class'] ?? null; // If no alias found, this returns `null` $aliasClass = Relation::getMorphedModel($class); if (! is_null($aliasClass)) { $class = $aliasClass; } // Verify class extends Model even though checksum protects this... if (! $class || ! is_a($class, Model::class, true)) { throw new \Exception('Livewire: Invalid model class.'); } // If no key is provided then an empty model is returned if (! array_key_exists('key', $meta)) { return new $class; } $key = $meta['key']; return $this->makeLazyProxy($class, $meta, function () use ($class, $key) { return (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail(); }); } function get(&$target, $key) { throw new \Exception('Can\'t access model properties directly'); } function set(&$target, $key, $value, $pathThusFar, $fullPath) { throw new \Exception('Can\'t set model properties directly'); } function call($target, $method, $params, $addEffect) { throw new \Exception('Can\'t call model methods directly'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportModels/SupportModels.php
src/Features/SupportModels/SupportModels.php
<?php namespace Livewire\Features\SupportModels; use Livewire\ComponentHook; class SupportModels extends ComponentHook { static function provide() { app('livewire')->propertySynthesizer([ ModelSynth::class, EloquentCollectionSynth::class, ]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportModels/BrowserTest.php
src/Features/SupportModels/BrowserTest.php
<?php namespace Livewire\Features\SupportModels; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\RefreshDatabase; use Livewire\Component; use Livewire\Features\SupportEvents\BaseOn; use Livewire\Livewire; use Sushi\Sushi; class BrowserTest extends \Tests\BrowserTestCase { use RefreshDatabase; public function test_parent_component_with_eloquent_collection_property_does_not_error_when_child_deletes_a_model_contained_within_it() { Livewire::visit([ new class extends Component { public $posts; public function mount() { $this->posts = BrowserTestPost::all(); } #[BaseOn('postDeleted')] public function setPosts() { $this->posts = BrowserTestPost::all(); } public function render() { return <<<'HTML' <div> @foreach($posts as $post) <div wire:key="parent-post-{{ $post->id }}"> <livewire:child wire:key="{{ $post->id }}" :post="$post" /> </div> @endforeach </div> HTML; } }, 'child' => new class extends Component { public $post; public function delete($id) { BrowserTestPost::find($id)->delete(); $this->dispatch('postDeleted'); } public function render() { return <<<'HTML' <div dusk="post-{{ $post->id }}"> {{ $post->title }} <button dusk="delete-{{ $post->id }}" wire:click="delete({{ $post->id }})">Delete</button> </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertPresent('@post-1') ->assertSeeIn('@post-1', 'Post #1') ->waitForLivewire()->click('@delete-1') ->assertNotPresent('@parent-post-1') ; } public function test_empty_eloquent_collection_property_is_dehydrated_without_errors() { Livewire::visit([ new class extends Component { public $placeholder = 'Original text'; public $posts; public EloquentCollection $typedPostsNotInitialized; public EloquentCollection $typedPostsInitialized; public function mount() { $this->posts = new EloquentCollection(); $this->typedPostsInitialized = new EloquentCollection(); } function changePlaceholder() { $this->placeholder = 'New text'; } public function render() { return <<<'HTML' <div> <button dusk="changePlaceholder" wire:click="changePlaceholder">Change placeholder</button> <span dusk="placeholder">{{ $placeholder }}</span> <span dusk="postsIsEloquentCollection">{{ $posts instanceof \Illuminate\Database\Eloquent\Collection ? 'true' : 'false' }}</span> <span dusk="typedPostsNotInitializedIsEloquentCollection">{{ $typedPostsNotInitialized instanceof \Illuminate\Database\Eloquent\Collection ? 'true' : 'false' }}</span> <span dusk="typedPostsInitializedIsEloquentCollection">{{ $typedPostsInitialized instanceof \Illuminate\Database\Eloquent\Collection ? 'true' : 'false' }}</span> </div> HTML; } }, ]) ->waitForLivewireToLoad() ->assertSeeIn('@placeholder', 'Original text') ->assertSeeIn('@postsIsEloquentCollection', 'true') ->assertSeeIn('@typedPostsNotInitializedIsEloquentCollection', 'false') ->assertSeeIn('@typedPostsInitializedIsEloquentCollection', 'true') ->waitForLivewire()->click('@changePlaceholder') ->assertSeeIn('@placeholder', 'New text') ->assertSeeIn('@postsIsEloquentCollection', 'true') ->assertSeeIn('@typedPostsNotInitializedIsEloquentCollection', 'false') ->assertSeeIn('@typedPostsInitializedIsEloquentCollection', 'true') ; } } class BrowserTestPost extends Model { use Sushi; protected $guarded = []; public function getRows() { return [ ['id' => 1, 'title' => 'Post #1'], ['id' => 2, 'title' => 'Post #2'], ['id' => 3, 'title' => 'Post #3'], ]; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportModels/IsLazy.php
src/Features/SupportModels/IsLazy.php
<?php namespace Livewire\Features\SupportModels; trait IsLazy { protected static ?\WeakMap $lazyMetas = null; public function isLazy($target) { if (PHP_VERSION_ID < 80400) { return false; } return (new \ReflectionClass($target))->isUninitializedLazyObject($target); } public function getLazyMeta($target) { if (! static::$lazyMetas) { static::$lazyMetas = new \WeakMap(); } if (! static::$lazyMetas->offsetExists($target)) { throw new \Exception('Lazy model not found'); } return static::$lazyMetas[$target]; } public function setLazyMeta($target, $meta) { if (! static::$lazyMetas) { static::$lazyMetas = new \WeakMap(); } static::$lazyMetas[$target] = $meta; } public function makeLazyProxy($class, $meta, $callback) { if (PHP_VERSION_ID < 80400) { return $callback(); } $reflector = new \ReflectionClass($class); $lazyModel = $reflector->newLazyProxy($callback); $this->setLazyMeta($lazyModel, $meta); return $lazyModel; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportModels/UnitTest.php
src/Features/SupportModels/UnitTest.php
<?php namespace Livewire\Features\SupportModels; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Relation; use Livewire\Livewire; use Sushi\Sushi; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_model_properties_are_persisted() { (new Article)::resolveConnection()->enableQueryLog(); Livewire::test(new class extends \Livewire\Component { public Article $article; public function mount() { $this->article = Article::first(); } public function render() { return <<<'HTML' <div>{{ $article->title }}</div> HTML; } }) ->assertSee('First') ->call('$refresh') ->assertSee('First'); $this->assertCount(2, Article::resolveConnection()->getQueryLog()); } public function test_cant_update_a_model_property() { $this->expectExceptionMessage("Can't set model properties directly"); Livewire::test(new class extends \Livewire\Component { public Article $article; public function mount() { $this->article = Article::first(); } public function render() { return <<<'HTML' <div>{{ $article->title }}</div> HTML; } }) ->assertSee('First') ->set('article.title', 'bar'); } public function test_cant_view_model_data_in_javascript() { $data = Livewire::test(new class extends \Livewire\Component { public Article $article; public function mount() { $this->article = Article::first(); } public function render() { return <<<'HTML' <div>{{ $article->title }}</div> HTML; } })->getData(); $this->assertNull($data['article']); } public function test_unpersisted_models_can_be_assigned_but_no_data_is_persisted_between_requests() { $component = Livewire::test(new class extends \Livewire\Component { public Article $article; public function mount() { $this->article = new Article(); } public function render() { return <<<'HTML' <div>{{ $article->title }}</div> HTML; } }) ->call('$refresh') ->assertSet('article', new Article()) ; $data = $component->getData(); $this->assertNull($data['article']); } public function test_model_properties_are_lazy_loaded() { $this->markTestSkipped(); // @todo: probably not going to go this route... (new Article)::resolveConnection()->enableQueryLog(); Livewire::test(new class extends TestComponent { #[Lazy] public Article $article; public function mount() { $this->article = Article::first(); } public function save() { $this->article->save(); } }) ->call('$refresh') ->call('save'); $this->assertCount(2, Article::resolveConnection()->getQueryLog()); } public function test_it_uses_laravels_morph_map_instead_of_class_name_if_available_when_dehydrating() { Relation::morphMap([ 'article' => Article::class, ]); $component = Livewire::test(ArticleComponent::class); $this->assertEquals('article', $component->snapshot['data']['article'][1]['class']); } public function test_it_uses_laravels_morph_map_instead_of_class_name_if_available_when_hydrating() { $article = Article::first(); Relation::morphMap([ 'article' => Article::class, ]); Livewire::test(ArticleComponent::class) ->call('$refresh') ->assertSet('article', $article); } public function test_collections_with_duplicate_models_are_available_when_hydrating() { Livewire::test(new class extends \Livewire\Component { public Collection $articles; public function mount() { $this->articles = new Collection([ Article::first(), Article::first(), ]); } public function render() { return <<<'HTML' <div> @foreach($articles as $article) {{ $article->title.'-'.$loop->index }} @endforeach </div> HTML; } }) ->assertSee('First-0') ->assertSee('First-1') ->call('$refresh') ->assertSee('First-0') ->assertSee('First-1'); } public function test_collections_retain_their_order_on_hydration() { Livewire::test(new class extends \Livewire\Component { public Collection $articles; public function mount() { $this->articles = Article::all()->reverse(); } public function render() { return <<<'HTML' <div> @foreach($articles as $article) {{ $article->title.'-'.$loop->index }} @endforeach </div> HTML; } }) ->assertSee('Second-0') ->assertSee('First-1') ->call('$refresh') ->assertSee('Second-0') ->assertSee('First-1'); } public function test_it_does_not_trigger_ClassMorphViolationException_when_morh_map_is_enforced() { // reset morph Relation::morphMap([], false); Relation::requireMorphMap(); $component = Livewire::test(new class extends TestComponent { public $article; public function mount() { $this->article = Article::first(); } }); $this->assertEquals(Article::class, $component->snapshot['data']['article'][1]['class']); Relation::requireMorphMap(false); } public function test_model_synth_rejects_non_model_classes() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid model class'); $component = Livewire::test(ArticleComponent::class); // Create a synth instance and try to hydrate with a non-Model class $synth = new ModelSynth( new \Livewire\Mechanisms\HandleComponents\ComponentContext($component->instance()), 'article' ); // This should throw because stdClass doesn't extend Model $synth->hydrate(null, ['class' => \stdClass::class]); } } #[\Attribute] class Lazy { // } class ArticleComponent extends \Livewire\Component { public $article; public function mount() { $this->article = Article::first(); } public function render() { return '<div>{{ $article->title }}</div>'; } } class Article extends Model { use Sushi; protected $rows = [ ['title' => 'First'], ['title' => 'Second'], ]; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportModels/EloquentCollectionSynth.php
src/Features/SupportModels/EloquentCollectionSynth.php
<?php namespace Livewire\Features\SupportModels; use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; use Livewire\Mechanisms\HandleComponents\ComponentContext; use Illuminate\Queue\SerializesAndRestoresModelIdentifiers; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Eloquent\Collection as EloquentCollection; class EloquentCollectionSynth extends Synth { use SerializesAndRestoresModelIdentifiers, IsLazy; public static $key = 'elcln'; static function match($target) { return $target instanceof EloquentCollection; } function dehydrate(EloquentCollection $target, $dehydrateChild) { if ($this->isLazy($target)) { $meta = $this->getLazyMeta($target); return [ null, $meta, ]; } $class = $target::class; $modelClass = $target->getQueueableClass(); /** * `getQueueableClass` above checks all models are the same and * then returns the class. We then instantiate a model object * so we can call `getMorphClass()` on it. * * If no alias is found, this just returns the class name */ $modelAlias = $modelClass ? (new $modelClass)->getMorphClass() : null; $meta = []; $serializedCollection = (array) $this->getSerializedPropertyValue($target); $meta['keys'] = $serializedCollection['id']; $meta['class'] = $class; $meta['modelClass'] = $modelAlias; return [ null, $meta ]; } function hydrate($data, $meta, $hydrateChild) { $class = $meta['class']; $modelClass = $meta['modelClass']; // If no alias found, this returns `null` $modelAlias = Relation::getMorphedModel($modelClass); if (! is_null($modelAlias)) { $modelClass = $modelAlias; } $keys = $meta['keys'] ?? []; if (count($keys) === 0) { return new $class(); } return $this->makeLazyProxy($class, $meta, function () use ($modelClass, $keys, $meta) { // We are using Laravel's method here for restoring the collection, which ensures // that all models in the collection are restored in one query, preventing n+1 // issues and also only restores models that exist. $collection = (new $modelClass)->newQueryForRestoration($keys)->useWritePdo()->get(); $collection = $collection->keyBy->getKey(); return new $meta['class']( collect($meta['keys'])->map(function ($id) use ($collection) { return $collection[$id] ?? null; })->filter() ); }); } function get(&$target, $key) { throw new \Exception('Can\'t access model properties directly'); } function set(&$target, $key, $value, $pathThusFar, $fullPath) { throw new \Exception('Can\'t set model properties directly'); } function call($target, $method, $params, $addEffect) { throw new \Exception('Can\'t call model methods directly'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportRequestInteractions/BrowserTest.php
src/Features/SupportRequestInteractions/BrowserTest.php
<?php namespace Livewire\Features\SupportRequestInteractions; use Livewire\Component; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_a_new_component_level_user_action_does_not_cancel_an_old_component_level_user_action_for_the_same_component_it_is_instead_queued_for_execution_after_the_old_action() { Livewire::visit( new class extends Component { public function firstRequest() { usleep(500 * 1000); // 500ms } public function secondRequest() { // Don't sleep the second request... } public function render() { return <<<'HTML' <div> <button wire:click="firstRequest" dusk="first-request">First Request</button> <button wire:click="secondRequest" dusk="second-request">Second Request</button> </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`)) onCancel(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`)) onSuccess(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`)) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() ->click('@first-request') // Wait for the first request to have started before checking the intercepts... ->pause(10) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'firstRequest-component started', 'firstRequest-component sent', ]) ->waitForLivewire()->click('@second-request') ->assertScript('window.intercepts.length', 6) ->assertScript('window.intercepts', [ 'firstRequest-component started', 'firstRequest-component sent', 'firstRequest-component succeeded', 'secondRequest-component started', 'secondRequest-component sent', 'secondRequest-component succeeded', ]) ; } public function test_a_new_component_level_user_action_cancels_an_old_component_level_poll_action_for_the_same_component() { Livewire::visit( new class extends Component { public function pollRequest() { usleep(100 * 1000); // 100ms } public function userRequest() { // Don't sleep the user request... } public function render() { return <<<'HTML' <div wire:poll.200ms="pollRequest"> <button wire:click="userRequest" dusk="user-request">User Request</button> </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`)) onCancel(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`)) onSuccess(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`)) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() // Wait for the poll to have started.. ->pause(210) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'pollRequest-component started', 'pollRequest-component sent', ]) ->waitForLivewire()->click('@user-request') ->assertScript('window.intercepts.length', 6) ->assertScript('window.intercepts', [ 'pollRequest-component started', 'pollRequest-component sent', 'pollRequest-component cancelled', 'userRequest-component started', 'userRequest-component sent', 'userRequest-component succeeded', ]) ; } public function test_a_new_component_level_poll_action_does_not_cancel_an_old_component_level_user_action_for_the_same_component() { Livewire::visit( new class extends Component { public function pollRequest() { // Don't sleep the poll request... } public function userRequest() { usleep(200 * 1000); // 500ms } public function render() { return <<<'HTML' <div wire:poll.400ms="pollRequest"> <button wire:click="userRequest" dusk="user-request">User Request</button> </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`)) onCancel(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`)) onSuccess(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`)) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() ->pause(250) ->click('@user-request') // Wait for the user request to have started... ->pause(10) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'userRequest-component started', 'userRequest-component sent', ]) // Timing is essential in this test as dusk is single threaded, so even if a request is cancelled, // the server will still handle it and take however long it needs. So we need to calculate the // time it takes for the first request to finished as if it was successful, plus the time for // the second request... // Wait for the poll to have started and be cancelled, and then the user request to finish.. ->pause(400) ->assertScript('window.intercepts.length', 3) ->assertScript('window.intercepts', [ 'userRequest-component started', 'userRequest-component sent', 'userRequest-component succeeded', ]) ; } public function test_a_new_component_level_poll_action_does_not_cancel_an_old_component_level_poll_action_for_the_same_component() { Livewire::visit( new class extends Component { public function firstPollRequest() { usleep(200 * 1000); // 500ms } public function secondPollRequest() { // Don't sleep the second poll request... } public function render() { return <<<'HTML' <div wire:poll.400ms="firstPollRequest"> <div wire:poll.500ms="secondPollRequest"></div> </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`) console.log(JSON.stringify(window.intercepts)) }) onCancel(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`) console.log(JSON.stringify(window.intercepts)) }) onSuccess(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`) console.log(JSON.stringify(window.intercepts)) }) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() // Wait for the first poll request to have started... ->pause(410) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'firstPollRequest-component started', 'firstPollRequest-component sent', ]) // Timing is essential in this test as dusk is single threaded, so even if a request is cancelled, // the server will still handle it and take however long it needs. So we need to calculate the // time it takes for the first request to finished as if it was successful, plus the time for // the second request... // Wait for the second poll to have started and be cancelled, and then the first poll request to finish.. ->pause(300) ->assertScript('window.intercepts.length', 3) ->assertScript('window.intercepts', [ 'firstPollRequest-component started', 'firstPollRequest-component sent', 'firstPollRequest-component succeeded', ]) ; } public function test_a_new_island_level_user_action_does_not_cancel_an_old_island_level_user_action_for_the_same_island_it_is_instead_queued_for_execution_after_the_old_action() { Livewire::visit( new class extends Component { public function firstRequest() { usleep(500 * 1000); // 500ms } public function secondRequest() { // Don't sleep the second request... } public function render() { return <<<'HTML' <div> @island('foo') <button wire:click="firstRequest" dusk="first-request">First Request</button> <button wire:click="secondRequest" dusk="second-request">Second Request</button> @endisland </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`)) onCancel(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`)) onSuccess(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`)) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() ->click('@first-request') // Wait for the first request to have started before checking the intercepts... ->pause(10) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'firstRequest-foo started', 'firstRequest-foo sent', ]) ->waitForLivewire()->click('@second-request') ->assertScript('window.intercepts.length', 6) ->assertScript('window.intercepts', [ 'firstRequest-foo started', 'firstRequest-foo sent', 'firstRequest-foo succeeded', 'secondRequest-foo started', 'secondRequest-foo sent', 'secondRequest-foo succeeded', ]) ; } public function test_a_new_island_level_user_action_cancels_an_old_island_level_poll_directive_action_for_the_same_island() { Livewire::visit( new class extends Component { public function pollRequest() { usleep(100 * 1000); // 100ms } public function userRequest() { // Don't sleep the user request... } public function render() { return <<<'HTML' <div> @island('foo') <div wire:poll.200ms="pollRequest"> <button wire:click="userRequest" dusk="user-request">User Request</button> </div> @endisland </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`)) onCancel(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`)) onSuccess(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`)) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() // Wait for the poll to have started.. ->pause(210) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'pollRequest-foo started', 'pollRequest-foo sent', ]) ->waitForLivewire()->click('@user-request') ->assertScript('window.intercepts.length', 6) ->assertScript('window.intercepts', [ 'pollRequest-foo started', 'pollRequest-foo sent', 'pollRequest-foo cancelled', 'userRequest-foo started', 'userRequest-foo sent', 'userRequest-foo succeeded', ]) ; } public function test_a_new_island_level_poll_directive_action_does_not_cancel_an_old_island_level_user_action_for_the_same_island() { Livewire::visit( new class extends Component { public function pollRequest() { // Don't sleep the poll request... } public function userRequest() { usleep(200 * 1000); // 500ms } public function render() { return <<<'HTML' <div> @island('foo') <div wire:poll.400ms="pollRequest"> <button wire:click="userRequest" dusk="user-request">User Request</button> </div> @endisland </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`)) onCancel(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`)) onSuccess(() => window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`)) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() ->pause(250) ->click('@user-request') // Wait for the user request to have started... ->pause(10) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'userRequest-foo started', 'userRequest-foo sent', ]) // Timing is essential in this test as dusk is single threaded, so even if a request is cancelled, // the server will still handle it and take however long it needs. So we need to calculate the // time it takes for the first request to finished as if it was successful, plus the time for // the second request... // Wait for the poll to have started and be cancelled, and then the user request to finish.. ->pause(400) ->assertScript('window.intercepts.length', 3) ->assertScript('window.intercepts', [ 'userRequest-foo started', 'userRequest-foo sent', 'userRequest-foo succeeded', ]) ; } public function test_a_new_island_level_poll_directive_action_does_not_cancel_an_old_island_level_poll_directive_action_instead_it_is_cancelled_for_the_same_island() { Livewire::visit( new class extends Component { public function firstPollRequest() { usleep(200 * 1000); // 500ms } public function secondPollRequest() { // Don't sleep the second poll request... } public function render() { return <<<'HTML' <div> @island('foo') <div wire:poll.400ms="firstPollRequest"> <div wire:poll.500ms="secondPollRequest"></div> </div> @endisland </div @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`) console.log(JSON.stringify(window.intercepts)) }) onCancel(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`) console.log(JSON.stringify(window.intercepts)) }) onSuccess(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`) console.log(JSON.stringify(window.intercepts)) }) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() // Wait for the first poll request to have started... ->pause(410) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'firstPollRequest-foo started', 'firstPollRequest-foo sent', ]) // Timing is essential in this test as dusk is single threaded, so even if a request is cancelled, // the server will still handle it and take however long it needs. So we need to calculate the // time it takes for the first request to finished as if it was successful, plus the time for // the second request... // Wait for the second poll to have started and be cancelled, and then the first poll request to finish.. ->pause(300) ->assertScript('window.intercepts.length', 3) ->assertScript('window.intercepts', [ 'firstPollRequest-foo started', 'firstPollRequest-foo sent', 'firstPollRequest-foo succeeded', ]) ; } public function test_a_island_level_user_action_does_not_cancel_a_component_level_user_action_for_the_same_component() { Livewire::visit( new class extends Component { public function userRequest() { usleep(150 * 1000); // 150ms } public function render() { return <<<'HTML' <div> <button wire:click="userRequest" dusk="component-request">Component Request</button> @island('foo') <button wire:click="userRequest" dusk="island-request">Island Request</button> @endisland </div @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`) console.log(JSON.stringify(window.intercepts)) }) onCancel(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`) console.log(JSON.stringify(window.intercepts)) }) onSuccess(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`) console.log(JSON.stringify(window.intercepts)) }) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() ->click('@component-request') // Wait for the user request to have started... ->pause(50) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'userRequest-component started', 'userRequest-component sent', ]) ->click('@island-request') // Wait for the island request to have started... ->pause(50) ->assertScript('window.intercepts.length', 4) ->assertScript('window.intercepts', [ 'userRequest-component started', 'userRequest-component sent', 'userRequest-foo started', 'userRequest-foo sent', ]) // Timing is essential in this test as dusk is single threaded, so even if a request is cancelled, // the server will still handle it and take however long it needs. So we need to calculate the // time it takes for the first request to finished as if it was successful, plus the time for // the second request... // Wait for both requests to have finished... ->pause(500) ->assertScript('window.intercepts.length', 6) ->assertScript('window.intercepts', [ 'userRequest-component started', 'userRequest-component sent', 'userRequest-foo started', 'userRequest-foo sent', 'userRequest-component succeeded', 'userRequest-foo succeeded', ]) ; } public function test_a_component_level_user_action_does_not_cancel_a_island_level_user_action_for_the_same_component() { Livewire::visit( new class extends Component { public function userRequest() { usleep(150 * 1000); // 150ms } public function render() { return <<<'HTML' <div> <button wire:click="userRequest" dusk="component-request">Component Request</button> @island('foo') <button wire:click="userRequest" dusk="island-request">Island Request</button> @endisland </div @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`) console.log(JSON.stringify(window.intercepts)) }) onCancel(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`) console.log(JSON.stringify(window.intercepts)) }) onSuccess(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`) console.log(JSON.stringify(window.intercepts)) }) }) </script> @endscript HTML; } } ) ->waitForLivewireToLoad() ->click('@island-request') // Wait for the island request to have started... ->pause(50) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'userRequest-foo started', 'userRequest-foo sent', ]) ->click('@component-request') // Wait for the user request to have started... ->pause(50) ->assertScript('window.intercepts.length', 4) ->assertScript('window.intercepts', [ 'userRequest-foo started', 'userRequest-foo sent', 'userRequest-component started', 'userRequest-component sent', ]) // Timing is essential in this test as dusk is single threaded, so even if a request is cancelled, // the server will still handle it and take however long it needs. So we need to calculate the // time it takes for the first request to finished as if it was successful, plus the time for // the second request... // Wait for both requests to have finished... ->pause(500) ->assertScript('window.intercepts.length', 6) ->assertScript('window.intercepts', [ 'userRequest-foo started', 'userRequest-foo sent', 'userRequest-component started', 'userRequest-component sent', 'userRequest-foo succeeded', 'userRequest-component succeeded', ]) ; } public function test_a_island_level_poll_directive_action_does_not_cancel_a_component_level_poll_directive_action_for_the_same_component() { Livewire::visit( new class extends Component { public function pollRequest() { usleep(150 * 1000); // 150ms } public function render() { return <<<'HTML' <div wire:poll.700ms="pollRequest"> @island('foo') <div wire:poll.750ms="pollRequest"> Island content </div> @endisland </div @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onSuccess }) => { let action = [...message.actions][0] window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} started`) onSend(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} sent`) console.log(JSON.stringify(window.intercepts)) }) onCancel(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} cancelled`) console.log(JSON.stringify(window.intercepts)) }) onSuccess(() => { window.intercepts.push(`${action.name}-${action.metadata.island?.name || 'component'} succeeded`)
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportInterceptors/BrowserTest.php
src/Features/SupportInterceptors/BrowserTest.php
<?php namespace Livewire\Features\SupportInterceptors; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_a_global_interceptor_can_be_registered() { Livewire::visit([ new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click="$refresh" dusk="refresh">Refresh</button> <livewire:child /> </div> @script <script> window.intercepts = [] Livewire.interceptMessage(() => { window.intercepts.push('intercept') console.log('intercept', window.intercepts) }) </script> @endscript HTML; } }, 'child' => new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click="$refresh" dusk="child-refresh">Child Refresh</button> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertScript('window.intercepts.length', 0) ->waitForLivewire()->click('@refresh') ->assertScript('window.intercepts.length', 1) ->assertScript('window.intercepts[0]', 'intercept') ->waitForLivewire()->click('@child-refresh') ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts[1]', 'intercept') ; } public function test_a_component_interceptor_can_be_registered() { Livewire::visit([ new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click="$refresh" dusk="refresh">Refresh</button> <livewire:child /> </div> @script <script> window.intercepts = [] this.interceptMessage(() => { window.intercepts.push('intercept') console.log('intercept', window.intercepts) }) </script> @endscript HTML; } }, 'child' => new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> <button wire:click="$refresh" dusk="child-refresh">Child Refresh</button> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertScript('window.intercepts.length', 0) ->waitForLivewire()->click('@refresh') ->assertScript('window.intercepts.length', 1) ->assertScript('window.intercepts[0]', 'intercept') ->waitForLivewire()->click('@child-refresh') // The child component should not have been intercepted... ->assertScript('window.intercepts.length', 1) ->assertScript('window.intercepts[0]', 'intercept') ; } public function test_an_action_scoped_component_interceptor_can_be_registered() { Livewire::visit([ new class extends \Livewire\Component { public function doSomething() {} public function render() { return <<<'HTML' <div> <button wire:click="$refresh" dusk="refresh">Refresh</button> <button wire:click="doSomething" dusk="do-something">Do Something</button> </div> @script <script> window.intercepts = [] this.intercept('doSomething', () => { window.intercepts.push('intercept') console.log('intercept', window.intercepts) }) </script> @endscript HTML; } } ]) ->waitForLivewireToLoad() ->assertScript('window.intercepts.length', 0) // The interceptor should not be triggered when the component is refreshed... ->waitForLivewire()->click('@refresh') ->assertScript('window.intercepts.length', 0) // The interceptor should be triggered when the action is performed... ->waitForLivewire()->click('@do-something') ->assertScript('window.intercepts.length', 1) ->assertScript('window.intercepts[0]', 'intercept') ; } public function test_an_interceptor_can_have_multiple_callbacks() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { sleep(1); } public function throwAnError() { throw new \Exception('Test error'); } public function render() { return <<<'HTML' <div> <button wire:click="$refresh" dusk="refresh">Refresh</button> <button wire:click="slowRequest" dusk="slow-request">Slow Request</button> <button wire:click="throwAnError" dusk="throw-error">Throw Error</button> </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, onSend, onCancel, onError, onSuccess }) => { let action = [...message.actions][0] let method = action.name let directive = action.origin.directive window.intercepts.push(`onInit-${directive.method}`) onSend(() => { window.intercepts.push(`onSend-${directive.method}`) }) onCancel(() => { window.intercepts.push(`onCancel-${directive.method}`) }) onError(() => { window.intercepts.push(`onError-${directive.method}`) }) onSuccess(({ onSync, onMorph, onRender }) => { window.intercepts.push(`onSuccess-${directive.method}`) onSync(() => { window.intercepts.push(`onSync-${directive.method}`) }) onMorph(() => { window.intercepts.push(`onMorph-${directive.method}`) }) onRender(() => { window.intercepts.push(`onRender-${directive.method}`) }) }) }) </script> @endscript HTML; } } ]) ->waitForLivewireToLoad() ->assertScript('window.intercepts.length', 0) // The interceptor should not be triggered when the component is refreshed... ->waitForLivewire()->click('@refresh') ->assertScript('window.intercepts.length', 6) ->assertScript('window.intercepts', [ 'onInit-$refresh', 'onSend-$refresh', 'onSuccess-$refresh', 'onSync-$refresh', 'onMorph-$refresh', 'onRender-$refresh', ]) // Reset... ->tap(fn ($b) => $b->script('window.intercepts = []')) // Next we will test the cancel interceptor... // Trigger the slow request... ->click('@slow-request') // Wait for a moment, then trigger another request... ->pause(100) ->waitForLivewire()->click('@refresh') ->assertScript('window.intercepts.length', 12) // The below results are the combination of the slow request and the refresh request... ->assertScript('window.intercepts', [ 'onInit-slowRequest', 'onSend-slowRequest', 'onSuccess-slowRequest', 'onSync-slowRequest', 'onMorph-slowRequest', 'onRender-slowRequest', 'onInit-$refresh', 'onSend-$refresh', 'onSuccess-$refresh', 'onSync-$refresh', 'onMorph-$refresh', 'onRender-$refresh', ]) // Reset... ->tap(fn ($b) => $b->script('window.intercepts = []')) // Next we will test the error interceptor... // Trigger the error request... ->waitForLivewire()->click('@throw-error') ->assertScript('window.intercepts.length', 3) ->assertScript('window.intercepts', [ 'onInit-throwAnError', 'onSend-throwAnError', 'onError-throwAnError', ]) ; } public function test_an_interceptor_can_cancel_a_message_before_it_is_sent() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { sleep(1); } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="slow-request">Slow Request</button> </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, cancel, onSend, onCancel, onError, onSuccess }) => { let action = [...message.actions][0] let method = action.name let directive = action.origin.directive window.intercepts.push(`onInit-${directive.method}`) onCancel(() => { window.intercepts.push(`onCancel-${directive.method}`) }) cancel() onSend(() => { window.intercepts.push(`onSend-${directive.method}`) }) onError(() => { window.intercepts.push(`onError-${directive.method}`) }) onSuccess(({ onSync, onMorph, onRender }) => { window.intercepts.push(`onSuccess-${directive.method}`) onSync(() => { window.intercepts.push(`onSync-${directive.method}`) }) onMorph(() => { window.intercepts.push(`onMorph-${directive.method}`) }) onRender(() => { window.intercepts.push(`onRender-${directive.method}`) }) }) }) </script> @endscript HTML; } } ]) ->waitForLivewireToLoad() ->assertScript('window.intercepts.length', 0) // The interceptor has a timeout set to cancel the request after 200ms... ->click('@slow-request') // Wait for the requests to be corralled... ->pause(250) ->assertScript('window.intercepts.length', 2) ->assertScript('window.intercepts', [ 'onInit-slowRequest', 'onCancel-slowRequest', ]) ; } public function test_an_interceptor_can_cancel_a_message_request_while_in_flight() { Livewire::visit([ new class extends \Livewire\Component { public function slowRequest() { sleep(1); } public function render() { return <<<'HTML' <div> <button wire:click="slowRequest" dusk="slow-request">Slow Request</button> </div> @script <script> window.intercepts = [] this.interceptMessage(({ message, cancel, onSend, onCancel, onError, onSuccess }) => { let action = [...message.actions][0] let method = action.name let directive = action.origin.directive window.intercepts.push(`onInit-${directive.method}`) setTimeout(() => cancel(), 200) onSend(() => { window.intercepts.push(`onSend-${directive.method}`) }) onCancel(() => { window.intercepts.push(`onCancel-${directive.method}`) }) onError(() => { window.intercepts.push(`onError-${directive.method}`) }) onSuccess(({ onSync, onMorph, onRender }) => { window.intercepts.push(`onSuccess-${directive.method}`) onSync(() => { window.intercepts.push(`onSync-${directive.method}`) }) onMorph(() => { window.intercepts.push(`onMorph-${directive.method}`) }) onRender(() => { window.intercepts.push(`onRender-${directive.method}`) }) }) }) </script> @endscript HTML; } } ]) ->waitForLivewireToLoad() ->assertScript('window.intercepts.length', 0) ->click('@slow-request') // The interceptor has a timeout set to cancel the request after 200ms... ->pause(250) ->assertScript('window.intercepts.length', 3) ->assertScript('window.intercepts', [ 'onInit-slowRequest', 'onSend-slowRequest', 'onCancel-slowRequest', ]) ; } public function test_a_redirect_can_be_intercepted_and_prevented() { Livewire::visit([ new class extends \Livewire\Component { public function redirectToWebsite() { $this->redirect('https://google.com'); } public function render() { return <<<'HTML' <div> <button wire:click="redirectToWebsite" dusk="redirect-to-website">Redirect to Website</button> </div> @script <script> window.stopRedirect = true Livewire.interceptRequest(({ onRedirect }) => { onRedirect(({ url, preventDefault }) => { if (window.stopRedirect) { preventDefault() window.stopRedirect = false } }) }) </script> @endscript HTML; } } ]) ->waitForLivewireToLoad() ->waitForLivewire()->click('@redirect-to-website') ->assertHostIsNot('www.google.com') ->waitForLivewire()->click('@redirect-to-website') ->assertHostIs('www.google.com') ; } public function test_action_interceptors_can_hook_into_action_lifecycle() { Livewire::visit([ new class extends \Livewire\Component { public $counter = 0; public function increment() { $this->counter++; } public function render() { return <<<'HTML' <div> <button wire:click="increment" dusk="increment">Increment</button> <span dusk="counter">{{ $counter }}</span> </div> @script <script> window.interceptLogs = [] Livewire.interceptAction(({ action, onSend, onSuccess, onFinish }) => { window.interceptLogs.push('intercept:' + action.name) onSend(() => { window.interceptLogs.push('onSend:' + action.name) }) onSuccess((result) => { window.interceptLogs.push('onSuccess:' + action.name) }) onFinish(() => { window.interceptLogs.push('onFinish:' + action.name) }) }) </script> @endscript HTML; } } ]) ->waitForLivewireToLoad() ->assertScript('window.interceptLogs.length', 0) ->waitForLivewire()->click('@increment') ->assertSeeIn('@counter', '1') ->assertScript('window.interceptLogs.length', 4) ->assertScript('window.interceptLogs[0]', 'intercept:increment') ->assertScript('window.interceptLogs[1]', 'onSend:increment') ->assertScript('window.interceptLogs[2]', 'onSuccess:increment') ->assertScript('window.interceptLogs[3]', 'onFinish:increment') ; } public function test_action_interceptors_can_handle_errors() { Livewire::visit([ new class extends \Livewire\Component { public function throwError() { throw new \Exception('Test error'); } public function render() { return <<<'HTML' <div> <button wire:click="throwError" dusk="throw">Throw Error</button> </div> @script <script> window.errorLogs = [] Livewire.interceptAction(({ action, onSend, onError, onFinish }) => { onSend(() => { window.errorLogs.push('onSend') }) onError(({ response }) => { window.errorLogs.push('onError:' + response.status) }) onFinish(() => { window.errorLogs.push('onFinish') }) }) </script> @endscript HTML; } } ]) ->waitForLivewireToLoad() ->assertScript('window.errorLogs.length', 0) ->waitForLivewire()->click('@throw') ->pause(100) // Give time for error handling ->assertScript('window.errorLogs.length', 3) ->assertScript('window.errorLogs[0]', 'onSend') ->assertScript('window.errorLogs[1]', 'onError:500') ->assertScript('window.errorLogs[2]', 'onFinish') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPolling/BrowserTest.php
src/Features/SupportPolling/BrowserTest.php
<?php namespace Livewire\Features\SupportPolling; use Tests\BrowserTestCase; use Livewire\Livewire; use Livewire\Component; class BrowserTest extends BrowserTestCase { public function test_polling_requests_are_batched_by_default() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <livewire:child num="1" /> <livewire:child num="2" /> <livewire:child num="3" /> </div> HTML; } }, 'child' => new class extends Component { public $num; public $time; public function boot() { $this->time = LARAVEL_START; } public function render() { return <<<'HTML' <div wire:poll.500ms id="child"> Child {{ $num }} <span dusk="time-{{ $num }}">{{ $time }}</span> </div> HTML; } }]) ->waitForText('Child 1') ->waitForText('Child 2') ->waitForText('Child 3') ->tap(function ($b) { $time1 = (float) $b->text('@time-1'); $time2 = (float) $b->text('@time-2'); $time3 = (float) $b->text('@time-3'); // Times should all be equal $this->assertEquals($time1, $time2); $this->assertEquals($time2, $time3); }) // Wait for a poll to have happened ->pause(500) ->tap(function ($b) { $time1 = (float) $b->text('@time-1'); $time2 = (float) $b->text('@time-2'); $time3 = (float) $b->text('@time-3'); // Times should all be equal $this->assertEquals($time1, $time2); $this->assertEquals($time2, $time3); }) ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportIsolating/BrowserTest.php
src/Features/SupportIsolating/BrowserTest.php
<?php namespace Livewire\Features\SupportIsolating; use Tests\BrowserTestCase; use Livewire\Livewire; use Livewire\Component; use Livewire\Attributes\On; use Livewire\Attributes\Isolate; class BrowserTest extends BrowserTestCase { public function test_components_can_be_marked_as_isolated() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <livewire:child num="1" /> <livewire:child num="2" /> <livewire:child num="3" /> <button wire:click="\$dispatch('trigger')" dusk="trigger">Dispatch trigger</button> </div> HTML; } }, 'child' => new #[Isolate] class extends Component { public $num; public $time; public function mount() { $this->time = LARAVEL_START; } #[On('trigger')] public function react() { $this->time = LARAVEL_START; } public function render() { return <<<'HTML' <div id="child"> Child {{ $num }} <span dusk="time-{{ $num }}">{{ $time }}</span> </div> HTML; } }]) ->waitForText('Child 1') ->waitForText('Child 2') ->waitForText('Child 3') ->tap(function ($b) { $time1 = (float) $b->text('@time-1'); $time2 = (float) $b->text('@time-2'); $time3 = (float) $b->text('@time-3'); $this->assertEquals($time1, $time2); $this->assertEquals($time2, $time3); }) ->waitForLivewire()->click('@trigger') ->tap(function ($b) { $time1 = (float) $b->waitFor('@time-1')->text('@time-1'); $time2 = (float) $b->waitFor('@time-2')->text('@time-2'); $time3 = (float) $b->waitFor('@time-3')->text('@time-3'); $this->assertNotEquals($time1, $time2); $this->assertNotEquals($time2, $time3); }) ; } public function test_lazy_requests_are_isolated_by_default() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <livewire:child num="1" /> <livewire:child num="2" /> <livewire:child num="3" /> </div> HTML; } }, 'child' => new #[\Livewire\Attributes\Lazy] class extends Component { public $num; public $time; public function mount() { $this->time = LARAVEL_START; } public function render() { return <<<'HTML' <div id="child"> Child {{ $num }} <span dusk="time-{{ $num }}">{{ $time }}</span> </div> HTML; } }]) ->waitForText('Child 1') ->waitForText('Child 2') ->waitForText('Child 3') ->tap(function ($b) { $time1 = (float) $b->text('@time-1'); $time2 = (float) $b->text('@time-2'); $time3 = (float) $b->text('@time-3'); $this->assertNotEquals($time1, $time2); $this->assertNotEquals($time2, $time3); }) ; } public function test_lazy_requests_are_isolated_by_default_but_bundled_on_next_request_when_polling() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <livewire:child num="1" /> <livewire:child num="2" /> <livewire:child num="3" /> </div> HTML; } }, 'child' => new #[\Livewire\Attributes\Lazy] class extends Component { public $num; public $time; public function boot() { $this->time = LARAVEL_START; } public function render() { return <<<'HTML' <div wire:poll.500ms id="child"> Child {{ $num }} <span dusk="time-{{ $num }}">{{ $time }}</span> </div> HTML; } }]) ->waitForText('Child 1') ->waitForText('Child 2') ->waitForText('Child 3') ->tap(function ($b) { $time1 = (float) $b->text('@time-1'); $time2 = (float) $b->text('@time-2'); $time3 = (float) $b->text('@time-3'); $this->assertNotEquals($time1, $time2); $this->assertNotEquals($time2, $time3); }) // Wait for a poll to have happened ->pause(500) ->tap(function ($b) { $time1 = (float) $b->text('@time-1'); $time2 = (float) $b->text('@time-2'); $time3 = (float) $b->text('@time-3'); // Times should now all be equal $this->assertEquals($time1, $time2); $this->assertEquals($time2, $time3); }) ; } public function test_lazy_requests_can_be_bundled_with_attribute_parameter() { Livewire::visit([new class extends Component { public function render() { return <<<HTML <div> <livewire:child num="1" /> <livewire:child num="2" /> <livewire:child num="3" /> </div> HTML; } }, 'child' => new #[\Livewire\Attributes\Lazy(isolate: false)] class extends Component { public $num; public $time; public function mount() { $this->time = LARAVEL_START; } public function render() { return <<<'HTML' <div id="child"> Child {{ $num }} <span dusk="time-{{ $num }}">{{ $time }}</span> </div> HTML; } }]) ->waitForText('Child 1') ->waitForText('Child 2') ->waitForText('Child 3') ->tap(function ($b) { $time1 = (float) $b->text('@time-1'); $time2 = (float) $b->text('@time-2'); $time3 = (float) $b->text('@time-3'); $this->assertEquals($time1, $time2); $this->assertEquals($time2, $time3); }) ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportIsolating/SupportIsolating.php
src/Features/SupportIsolating/SupportIsolating.php
<?php namespace Livewire\Features\SupportIsolating; use Livewire\ComponentHook; class SupportIsolating extends ComponentHook { public function dehydrate($context) { if ($this->shouldIsolate()) { $context->addMemo('isolate', true); } } public function shouldIsolate() { return $this->component->getAttributes() ->filter(fn ($i) => is_subclass_of($i, BaseIsolate::class)) ->count() > 0; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportIsolating/BaseIsolate.php
src/Features/SupportIsolating/BaseIsolate.php
<?php namespace Livewire\Features\SupportIsolating; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; #[\Attribute(\Attribute::TARGET_CLASS)] class BaseIsolate extends LivewireAttribute { // }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireText/BrowserTest.php
src/Features/SupportWireText/BrowserTest.php
<?php namespace Livewire\Features\SupportWireText; use Livewire\Component; use Livewire\Livewire; use Tests\BrowserTestCase; class BrowserTest extends BrowserTestCase { public function test_wire_text_shows_on_init() { Livewire::visit(new class extends Component { public $text = 'foo'; public function render() { return <<<'HTML' <div> <div wire:text="text" dusk="label"></div> </div> HTML; } }) ->assertSeeIn('@label', 'foo'); } public function test_wire_text_updates_when_property_changes() { Livewire::visit(new class extends Component { public $text = 'foo'; public function render() { return <<<'HTML' <div> <div wire:text="text" dusk="label"></div> <button wire:click="$set('text', 'bar')" dusk="change">Change</button> </div> HTML; } }) ->assertSeeIn('@label', 'foo') ->waitForLivewire()->click('@change') ->assertSeeIn('@label', 'bar'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportChecksumErrorDebugging/SupportChecksumErrorDebugging.php
src/Features/SupportChecksumErrorDebugging/SupportChecksumErrorDebugging.php
<?php namespace Livewire\Features\SupportChecksumErrorDebugging; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\File; class SupportChecksumErrorDebugging { function boot() { // @todo: dont write to this file unless the command is running... return; $file = storage_path('framework/cache/lw-checksum-log.json'); Artisan::command('livewire:monitor-checksum', function () use ($file) { File::put($file, json_encode(['checksums' => [], 'failure' => null])); $this->info('Monitoring for checksum errors...'); while (true) { $cache = json_decode(File::get($file), true); if ($cache['failure']) { $this->info('Failure: '.$cache['failure']); $cache['failure'] = null; } File::put($file, json_encode($cache)); sleep(1); } })->purpose('Debug checksum errors in Livewire'); on('checksum.fail', function ($checksum, $comparitor, $tamperedSnapshot) use ($file) { $cache = json_decode(File::get($file), true); if (! isset($cache['checksums'][$checksum])) return; $canonicalSnapshot = $cache['checksums'][$checksum]; $good = $this->array_diff_assoc_recursive($canonicalSnapshot, $tamperedSnapshot); $bad = $this->array_diff_assoc_recursive($tamperedSnapshot, $canonicalSnapshot); $cache['failure'] = "\nBefore: ".json_encode($good)."\nAfter: ".json_encode($bad); File::put($file, json_encode($cache)); }); on('checksum.generate', function ($checksum, $snapshot) use ($file) { $cache = json_decode(File::get($file), true); $cache['checksums'][$checksum] = $snapshot; File::put($file, json_encode($cache)); }); } // https://www.php.net/manual/en/function.array-diff-assoc.php#111675 function array_diff_assoc_recursive($array1, $array2) { $difference=array(); foreach($array1 as $key => $value) { if( is_array($value) ) { if( !isset($array2[$key]) || !is_array($array2[$key]) ) { $difference[$key] = $value; } else { $new_diff = $this->array_diff_assoc_recursive($value, $array2[$key]); if( !empty($new_diff) ) $difference[$key] = $new_diff; } } else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) { $difference[$key] = $value; } } return $difference; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportErrorResponses/BrowserTest.php
src/Features/SupportErrorResponses/BrowserTest.php
<?php namespace Livewire\Features\SupportErrorResponses; use Livewire\Component as BaseComponent; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_it_shows_page_expired_dialog_when_session_has_expired() { Livewire::visit(Component::class) ->waitForLivewire()->click('@regenerateSession') ->click('@refresh') // Wait for Livewire to respond, but dusk helper won't // work as dialog box is stopping further execution ->waitForDialog() ->assertDialogOpened("This page has expired.\nWould you like to refresh the page?") // Dismiss dialog so next tests run ->dismissDialog() ; } public function test_it_shows_custom_hook_dialog_using_on_error_response_hook_when_session_has_expired() { Livewire::withQueryParams(['useCustomErrorResponseHook' => true]) ->visit(Component::class) ->waitForLivewire()->click('@regenerateSession') ->click('@refresh') // Wait for Livewire to respond, but dusk helper won't // work as dialog box is stopping further execution ->waitForDialog() ->assertDialogOpened('Page Expired - Error Response') // Dismiss dialog so next tests run ->dismissDialog() ; } } class Component extends BaseComponent { public $useCustomPageExpiredHook = false; public $useCustomErrorResponseHook = false; protected $queryString = [ 'useCustomPageExpiredHook' => ['except' => false], 'useCustomErrorResponseHook' => ['except' => false], ]; public function regenerateSession() { request()->session()->regenerate(); } public function render() { return <<< 'HTML' <div> <button type="button" wire:click="regenerateSession" dusk="regenerateSession">Regenerate Session</button> <button type="button" wire:click="$refresh" dusk="refresh">Refresh</button> @if($useCustomErrorResponseHook) <script> document.addEventListener('livewire:init', () => { Livewire.hook('request', ({ fail, preventDefault }) => { fail(({ status }) => { if (status === 419) { confirm('Page Expired - Error Response') preventDefault() } }) }) }) </script> @endif </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJson/SupportJson.php
src/Features/SupportJson/SupportJson.php
<?php namespace Livewire\Features\SupportJson; use function Livewire\on; use Livewire\ComponentHook; use Illuminate\Validation\ValidationException; class SupportJson extends ComponentHook { public static function provide() { on('call', function ($component, $method, $params, $context, $returnEarly, $metadata, $index) { if (! static::isJsonMethod($component, $method)) return; $component->skipRender(); try { $result = $component->{$method}(...$params); $returnEarly($result); } catch (ValidationException $e) { // Add validation errors to returnsMeta effect keyed by action index $existingMeta = $context->effects['returnsMeta'] ?? []; $existingMeta[$index] = ['errors' => $e->errors()]; $context->addEffect('returnsMeta', $existingMeta); // Return null so the returns array stays aligned $returnEarly(null); } }); } protected static function isJsonMethod($component, $method) { return $component->getAttributes() ->filter(fn ($attr) => $attr instanceof BaseJson) ->filter(fn ($attr) => $attr->getName() === $method) ->isNotEmpty(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportJson/BaseJson.php
src/Features/SupportJson/BaseJson.php
<?php namespace Livewire\Features\SupportJson; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; #[\Attribute(\Attribute::TARGET_METHOD)] class BaseJson extends LivewireAttribute { public function dehydrate($context) { $methodName = $this->getName(); $context->pushMemo('json', $methodName); $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/SupportJson/BrowserTest.php
src/Features/SupportJson/BrowserTest.php
<?php namespace Livewire\Features\SupportJson; use Tests\BrowserTestCase; use Livewire\Livewire; use Livewire\Component; use Livewire\Attributes\Json; use Illuminate\Support\Facades\Validator; class BrowserTest extends BrowserTestCase { public function test_can_call_json_method_and_receive_return_value() { Livewire::visit(new class extends Component { public $result = ''; #[Json] public function getData() { return ['foo' => 'bar']; } public function render() { return <<<'HTML' <div> <button dusk="call" @click="$wire.getData().then(data => { $wire.result = JSON.stringify(data) })">Call</button> <span dusk="result" wire:text="result"></span> </div> HTML; } }) ->waitForLivewireToLoad() ->click('@call') ->waitForTextIn('@result', '{"foo":"bar"}') ->assertSeeIn('@result', '{"foo":"bar"}') ; } public function test_json_method_rejects_with_validation_errors() { Livewire::visit(new class extends Component { public $status = ''; public $validationErrors = ''; #[Json] public function saveData() { Validator::make(['name' => ''], ['name' => 'required'])->validate(); return ['success' => true]; } public function render() { return <<<'HTML' <div> <button dusk="call" @click="$wire.saveData().catch(e => { $wire.status = e.status; $wire.validationErrors = JSON.stringify(e.errors) })">Call</button> <span dusk="status" wire:text="status"></span> <span dusk="validationErrors" wire:text="validationErrors"></span> </div> HTML; } }) ->waitForLivewireToLoad() ->click('@call') ->waitForTextIn('@status', '422') ->assertSeeIn('@status', '422') ->assertSeeIn('@validationErrors', 'name') ; } public function test_json_method_skips_render() { Livewire::visit(new class extends Component { public $count = 0; #[Json] public function getData() { $this->count++; return ['count' => $this->count]; } public function render() { return <<<'HTML' <div> <button dusk="call" @click="$wire.getData()">Call</button> <span dusk="count">{{ $count }}</span> </div> HTML; } }) ->waitForLivewireToLoad() ->assertSeeIn('@count', '0') ->waitForLivewire()->click('@call') ->assertSeeIn('@count', '0') ; } public function test_json_method_can_return_primitive_values() { Livewire::visit(new class extends Component { public $result = ''; #[Json] public function getString() { return 'hello world'; } public function render() { return <<<'HTML' <div> <button dusk="call" @click="$wire.getString().then(data => { $wire.result = data })">Call</button> <span dusk="result" wire:text="result"></span> </div> HTML; } }) ->waitForLivewireToLoad() ->click('@call') ->waitForTextIn('@result', 'hello world') ->assertSeeIn('@result', 'hello world') ; } public function test_multiple_json_methods_with_mixed_success_and_errors() { Livewire::visit(new class extends Component { public $successResult = ''; public $errorStatus = ''; public $errorMessages = ''; #[Json] public function successMethod() { return ['status' => 'success']; } #[Json] public function errorMethod() { Validator::make(['email' => ''], ['email' => 'required|email'])->validate(); return ['status' => 'should not see this']; } public function render() { return <<<'HTML' <div> <button dusk="call-both" @click=" Promise.all([ $wire.successMethod() .then(data => { $wire.successResult = JSON.stringify(data) }) .catch(e => {}), $wire.errorMethod() .then(data => {}) .catch(e => { $wire.errorStatus = e.status; $wire.errorMessages = JSON.stringify(e.errors) }) ]) ">Call Both</button> <span dusk="success-result" wire:text="successResult"></span> <span dusk="error-status" wire:text="errorStatus"></span> <span dusk="error-messages" wire:text="errorMessages"></span> </div> HTML; } }) ->waitForLivewireToLoad() ->click('@call-both') ->waitForTextIn('@success-result', 'success') ->waitForTextIn('@error-status', '422') ->assertSeeIn('@success-result', '{"status":"success"}') ->assertSeeIn('@error-status', '422') ->assertSeeIn('@error-messages', 'email') ; } public function test_json_method_with_try_catch_pattern() { Livewire::visit(new class extends Component { public $result = ''; public $errorMessage = ''; #[Json] public function riskyMethod($shouldFail) { if ($shouldFail) { Validator::make(['name' => ''], ['name' => 'required'])->validate(); } return ['success' => true]; } public function render() { return <<<'HTML' <div> <button dusk="call-success" @click=" (async () => { try { let data = await $wire.riskyMethod(false); $wire.result = JSON.stringify(data); } catch (e) { $wire.errorMessage = 'error: ' + e.status; } })() ">Call Success</button> <button dusk="call-fail" @click=" (async () => { try { let data = await $wire.riskyMethod(true); $wire.result = JSON.stringify(data); } catch (e) { $wire.errorMessage = 'error: ' + e.status; } })() ">Call Fail</button> <span dusk="result" wire:text="result"></span> <span dusk="error" wire:text="errorMessage"></span> </div> HTML; } }) ->waitForLivewireToLoad() ->click('@call-success') ->waitForTextIn('@result', 'success') ->assertSeeIn('@result', '{"success":true}') ->assertDontSeeIn('@error', 'error: 422') ->click('@call-fail') ->waitForTextIn('@error', '422') ->assertSeeIn('@error', 'error: 422') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportMagicActions/SupportMagicActions.php
src/Features/SupportMagicActions/SupportMagicActions.php
<?php namespace Livewire\Features\SupportMagicActions; use Livewire\ComponentHook; use function Livewire\on; class SupportMagicActions extends ComponentHook { public static $magicActions = [ '$refresh', '$set', '$sync', '$commit', ]; public function boot() { on('call', function ($component, $method, $params, $componentContext, $returnEarly, $context) { if (! in_array($method, self::$magicActions)) { return; } $returnEarly(); }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportIslands/HandlesIslands.php
src/Features/SupportIslands/HandlesIslands.php
<?php namespace Livewire\Features\SupportIslands; use Livewire\Mechanisms\ExtendBlade\ExtendBlade; use Livewire\Features\SupportStreaming\SupportStreaming; use Livewire\Features\SupportIslands\Compiler\IslandCompiler; use Livewire\Drawer\Utils; use function Livewire\trigger; trait HandlesIslands { protected $islands = []; protected $islandsHaveMounted = false; protected $islandIsTopLevelRender = false; protected $renderedIslandFragments = []; public function islandIsMounting() { return ! $this->islandsHaveMounted; } public function markIslandsAsMounted() { $this->islandsHaveMounted = true; } public function getIslands() { return $this->islands; } public function setIslands($islands) { $this->islands = $islands; } public function getRenderedIslandFragments() { return $this->renderedIslandFragments; } public function hasRenderedIslandFragments() { return ! empty($this->renderedIslandFragments); } public function renderIslandDirective($name = null, $token = null, $lazy = false, $defer = false, $always = false, $skip = false, $with = []) { // If no name is provided, use the token... $name = $name ?? $token; if ($this->islandIsMounting()) { $this->storeIsland($name, $token); if ($skip) { // Just render the placeholder... $renderedContent = $this->renderIslandView($name, $token, [ '__placeholder' => '', ]); return $this->wrapWithFragmentMarkers($renderedContent,[ 'type' => 'island', 'name' => $name, 'token' => $token, 'mode' => 'morph', ]); } } else { if (! $always) { return $this->renderSkippedIsland($name, $token); } } if (($lazy || $defer) && $this->islandIsMounting()) { $renderedContent = $this->renderIslandView($name, $token, [ '__placeholder' => '', ]); $directive = $lazy ? 'wire:intersect.once' : 'wire:init'; $renderedContent = $this->injectLazyDirective($renderedContent, $name, $directive); } else { // Don't pass directive's $with - it's extracted in the compiled island $renderedContent = $this->renderIslandView($name, $token, []); } return $this->wrapWithFragmentMarkers($renderedContent, [ 'type' => 'island', 'name' => $name, 'token' => $token, 'mode' => 'morph', ]); } public function renderSkippedIsland($name, $token) { return $this->wrapWithFragmentMarkers('', [ 'type' => 'island', 'name' => $name, 'token' => $token, 'mode' => 'skip', ]); } public function renderIsland($name, $content = null, $mode = 'morph', $with = [], $mount = false) { $islands = $this->getIslands(); foreach ($islands as $island) { if ($island['name'] === $name) { // If the island is lazy, we need to mount it, but to ensure any nested islands render, // we need to set the `$islandsHaveMounted` flag to false and reset it back after the // lazy island is mounted... $finish = $this->mountIfNeedsMounting($mount); $token = $island['token']; if (! $token) continue; // Pass runtime $with as __runtimeWith so it overrides directive's with $data = empty($with) ? [] : ['__runtimeWith' => $with]; $renderedContent = $this->wrapWithFragmentMarkers($content ?? $this->renderIslandView($name, $token, $data), [ 'type' => 'island', 'name' => $name, 'token' => $token, 'mode' => $mode, ]); $this->renderedIslandFragments[] = $renderedContent; $finish(); } } } public function streamIsland($name, $content = null, $mode = 'morph', $with = []) { $islands = $this->getIslands(); foreach ($islands as $island) { if ($island['name'] === $name) { $token = $island['token']; // Pass runtime $with as __runtimeWith so it overrides directive's with $data = empty($with) ? [] : ['__runtimeWith' => $with]; $output = $content ?? $this->renderIslandView($name, $token, $data); $renderedContent = $this->wrapWithFragmentMarkers($output, [ 'type' => 'island', 'name' => $name, 'token' => $token, 'mode' => $mode, ]); SupportStreaming::ensureStreamResponseStarted(); SupportStreaming::streamContent([ 'id' => $this->getId(), 'type' => 'island', 'islandFragment' => $renderedContent, ]); } } } public function renderIslandView($name, $token, $data = []) { $path = IslandCompiler::getCachedPathFromToken($token); $view = app('view')->file($path); app(ExtendBlade::class)->startLivewireRendering($this); $properties = Utils::getPublicPropertiesDefinedOnSubclass($this); $scope = array_merge(['__livewire' => $this], $properties); $view->with($scope); $view->with($data); $finish = trigger('renderIsland', $this, $name, $view, $properties); $html = $view->render(); $replaceHtml = function ($newHtml) use (&$html) { $html = $newHtml; }; $finish($html, $replaceHtml); app(ExtendBlade::class)->endLivewireRendering(); return $html; } 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, '|'); } protected function storeIsland($name, $token) { $this->islands[] = [ 'name' => $name, 'token' => $token, ]; } protected function injectLazyDirective($content, $islandName, $directive) { $attributes = $directive.'="__lazyLoadIsland"'; // Fast regex to find first HTML element opening tag (not comments or closing tags) // Matches: <tagname followed by whitespace, >, or /> if (preg_match('/<([a-zA-Z][a-zA-Z0-9-]*)(\s|>|\/>)/', $content, $matches, PREG_OFFSET_CAPTURE)) { $fullMatch = $matches[0][0]; $position = $matches[0][1]; $tagName = $matches[1][0]; $afterTag = $matches[2][0]; // Insert attributes after the tag name $insertion = '<'.$tagName.' '.$attributes.$afterTag; return substr($content, 0, $position) . $insertion . substr($content, $position + strlen($fullMatch)); } // No element found (text-only content), wrap it return '<span '.$attributes.'>'.$content.'</span>'; } protected function mountIfNeedsMounting($mount) { if (! $mount) { return function() {}; } $existingMounted = $this->islandsHaveMounted; $this->islandsHaveMounted = false; return function() use ($existingMounted) { $this->islandsHaveMounted = $existingMounted; }; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportIslands/BrowserTest.php
src/Features/SupportIslands/BrowserTest.php
<?php namespace Livewire\Features\SupportIslands; use Tests\BrowserTestCase; use Livewire\Livewire; class BrowserTest extends BrowserTestCase { public function test_island_directive() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> @island <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertSeeIn('@island-increment', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@island-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@root-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@root-increment', 'Root count: 2') ; } public function test_sibling_islands() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> @island <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland @island <button type="button" wire:click="increment" dusk="sibling-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertSeeIn('@island-increment', 'Count: 0') ->assertSeeIn('@sibling-increment', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@island-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@sibling-increment', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@sibling-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@sibling-increment', 'Count: 2') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@root-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@sibling-increment', 'Count: 2') ->assertSeeIn('@root-increment', 'Root count: 3') ; } public function test_render_nested_islands() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> @island <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @island <button type="button" wire:click="increment" dusk="nested-island-increment">Count: {{ $count }}</button> @endisland @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertSeeIn('@island-increment', 'Count: 0') ->assertSeeIn('@nested-island-increment', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@island-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@nested-island-increment', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@nested-island-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@nested-island-increment', 'Count: 2') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@root-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@nested-island-increment', 'Count: 2') ->assertSeeIn('@root-increment', 'Root count: 3') ; } public function test_always_render_island() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> @island(always: true) <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertSeeIn('@island-increment', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@island-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@root-increment') ->assertSeeIn('@island-increment', 'Count: 2') ->assertSeeIn('@root-increment', 'Root count: 2') ; } public function test_skip_render_island() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> @island(name: 'foo', skip: true) @placeholder <p dusk="island-placeholder">Loading...</p> @endplaceholder <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" wire:island="foo" dusk="foo-increment">Root count: {{ $count }}</button> <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertNotPresent('@island-increment') ->assertPresent('@island-placeholder') ->assertSeeIn('@foo-increment', 'Root count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@foo-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@foo-increment', 'Root count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@island-increment') ->assertSeeIn('@island-increment', 'Count: 2') ->assertSeeIn('@foo-increment', 'Root count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@root-increment') ->assertSeeIn('@island-increment', 'Count: 2') ->assertSeeIn('@foo-increment', 'Root count: 3') ->assertSeeIn('@root-increment', 'Root count: 3') ; } public function test_lazy_island() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function hydrate() { usleep(250000); } // 250ms public function render() { return <<<'HTML' <div> <div style="height: 200vh" dusk="long-content">Long content to push the island off the page...</div> @island(lazy: true) <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertNotPresent('@island-increment') ->assertPresent('@root-increment') ->scrollTo('@root-increment') ->waitForText('Count: 0') ->assertPresent('@island-increment') ->assertPresent('@root-increment') ; } public function test_defer_island() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function hydrate() { usleep(250000); } // 250ms public function render() { return <<<'HTML' <div> @island(defer: true) <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertNotPresent('@island-increment') ->assertPresent('@root-increment') ->waitForText('Count: 0') ->assertPresent('@island-increment') ->assertPresent('@root-increment') ; } public function test_lazy_with_placeholder() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function hydrate() { usleep(250000); } // 250ms public function render() { return <<<'HTML' <div> @island(lazy: true) @placeholder <p>Loading...</p> @endplaceholder <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertNotPresent('@island-increment') ->assertPresent('@root-increment') ->assertSee('Loading...') ->waitForText('Count: 0') ->assertPresent('@island-increment') ->assertPresent('@root-increment') ->assertDontSee('Loading...') ->assertSeeIn('@island-increment', 'Count: 0') ; } public function test_named_islands() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function hydrate() { usleep(250000); } // 250ms public function render() { return <<<'HTML' <div> @island(name: 'foo') <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> <button type="button" wire:click="increment" dusk="foo-increment" wire:island="foo">Foo count: {{ $count }}</button> </div> HTML; } }]) ->assertSeeIn('@island-increment', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->assertSeeIn('@foo-increment', 'Foo count: 0') ->waitForLivewire()->click('@island-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@root-increment', 'Root count: 0') ->assertSeeIn('@foo-increment', 'Foo count: 0') ->waitForLivewire()->click('@root-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@root-increment', 'Root count: 2') ->assertSeeIn('@foo-increment', 'Foo count: 2') ->waitForLivewire()->click('@foo-increment') ->assertSeeIn('@island-increment', 'Count: 3') ->assertSeeIn('@root-increment', 'Root count: 2') ->assertSeeIn('@foo-increment', 'Foo count: 2') ; } public function test_two_islands_with_the_same_name() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> @island(name: 'foo') <div dusk="foo-island-1">Count: {{ $count }}</div> @endisland @island(name: 'foo') <div dusk="foo-island-2">Count: {{ $count }}</div> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> <button type="button" wire:click="increment" dusk="foo-increment" wire:island="foo">Increment Foo</button> </div> HTML; } }]) ->assertSeeIn('@foo-island-1', 'Count: 0') ->assertSeeIn('@foo-island-2', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@root-increment') ->assertSeeIn('@foo-island-1', 'Count: 0') ->assertSeeIn('@foo-island-2', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 1') ->waitForLivewire()->click('@foo-increment') ->assertSeeIn('@foo-island-1', 'Count: 2') ->assertSeeIn('@foo-island-2', 'Count: 2') ->assertSeeIn('@root-increment', 'Root count: 1') ; } public function test_render_island_method() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; $this->renderIsland('foo'); } public function render() { return <<<'HTML' <div> @island(name: 'foo') <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertSeeIn('@island-increment', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@island-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@root-increment') ->assertSeeIn('@island-increment', 'Count: 2') ->assertSeeIn('@root-increment', 'Root count: 2') ; } public function test_stream_island_method() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; $this->streamIsland('foo'); } public function render() { return <<<'HTML' <div> @island(name: 'foo') <button type="button" wire:click="increment" dusk="island-increment">Count: {{ $count }}</button> @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertSeeIn('@island-increment', 'Count: 0') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@island-increment') ->assertSeeIn('@island-increment', 'Count: 1') ->assertSeeIn('@root-increment', 'Root count: 0') ->waitForLivewire()->click('@root-increment') ->assertSeeIn('@island-increment', 'Count: 2') ->assertSeeIn('@root-increment', 'Root count: 2') ; } public function test_append_and_prepend_islands() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> <div dusk="foo-island"> @island(name: 'foo')<div>Count: {{ $count }}</div>@endisland </div> <button type="button" wire:click="increment" dusk="foo-increment" wire:island="foo">Increment</button> <button type="button" wire:click="increment" dusk="foo-prepend-increment" wire:island.prepend="foo">Prepend</button> <button type="button" wire:click="increment" dusk="foo-append-increment" wire:island.append="foo">Append</button> </div> HTML; } }]) ->assertSourceHas('<div>Count: 0</div>') ->waitForLivewire()->click('@foo-increment') ->assertSourceHas('<div>Count: 1</div>') ->waitForLivewire()->click('@foo-prepend-increment') ->assertSourceHas('<div>Count: 2</div><div>Count: 1</div>') ->waitForLivewire()->click('@foo-append-increment') ->assertSourceHas('<div>Count: 2</div><div>Count: 1</div><div>Count: 3</div>') ->waitForLivewire()->click('@foo-prepend-increment') ->assertSourceHas('<div>Count: 4</div><div>Count: 2</div><div>Count: 1</div><div>Count: 3</div>') ->waitForLivewire()->click('@foo-append-increment') ->assertSourceHas('<div>Count: 4</div><div>Count: 2</div><div>Count: 1</div><div>Count: 3</div><div>Count: 5</div>') ; } public function test_streams_append_into_island_over_time() { Livewire::visit([new class extends \Livewire\Component { public function send() { $this->streamIsland('foo', 'Hi, how are you?', mode: 'append'); usleep(250000); $this->streamIsland('foo', ' I hope things are going well.', mode: 'append'); usleep(250000); $this->streamIsland('foo', ' I just wanted to check in.', mode: 'append'); } public function render() { return <<<'HTML' <div> <div dusk="foo-island"> @island(name: 'foo')@endisland </div> <button type="button" wire:click="send" dusk="send">Send</button> </div> HTML; } }]) ->assertPresent('@send') ->assertPresent('@foo-island') ->assertDontSee('Hi, how are you?') ->click('@send') ->waitForText('Hi, how are you?') ->assertSeeIn('@foo-island', 'Hi, how are you?') ->waitForText('I hope things are going well.') ->assertSeeIn('@foo-island', 'Hi, how are you? I hope things are going well.') ->waitForText('I just wanted to check in.') ->assertSeeIn('@foo-island', 'Hi, how are you? I hope things are going well. I just wanted to check in.') ; } public function test_island_works_with_error_bag() { Livewire::visit([new class extends \Livewire\Component { public $foo = ''; public function validateFoo() { $this->validate(['foo' => 'required']); } public function render() { return <<<'HTML' <div> @island <button type="button" wire:click="validateFoo" dusk="island-validate-foo">Validate Foo</button> <div> Error: <div dusk="island-error">{{ $errors->first('foo') }}</div> </div> @endisland <div> Error: <div dusk="root-error">{{ $errors->first('foo') }}</div> </div> </div> HTML; } }]) ->assertDontSeeIn('@island-error', 'The foo field is required.') ->assertDontSeeIn('@root-error', 'The foo field is required.') ->waitForLivewire()->click('@island-validate-foo') ->assertSeeIn('@island-error', 'The foo field is required.') ->assertDontSeeIn('@root-error', 'The foo field is required.') ; } public function test_islands_inside_a_lazy_island_get_rendered_when_the_lazy_island_is_mounted() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function hydrate() { usleep(250000); } // 250ms public function render() { return <<<'HTML' <div> <div style="height: 200vh" dusk="long-content">Long content to push the island off the page...</div> @island(lazy: true) <button type="button" wire:click="increment" dusk="outer-island-increment">Outer Island Count: {{ $count }}</button> @island <button type="button" wire:click="increment" dusk="inner-island-increment">Inner Island Count: {{ $count }}</button> @endisland @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertNotPresent('@outer-island-increment') ->assertNotPresent('@inner-island-increment') ->assertPresent('@root-increment') ->scrollTo('@root-increment') ->waitForText('Outer Island Count: 0') ->assertPresent('@outer-island-increment') ->assertPresent('@inner-island-increment') ->assertPresent('@root-increment') ; } public function test_lazy_islands_inside_a_lazy_island_get_mounted_after_the_outer_lazy_island_is_mounted() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function hydrate() { usleep(250000); } // 250ms public function render() { return <<<'HTML' <div> <div style="height: 200vh" dusk="long-content">Long content to push the island off the page...</div> @island(lazy: true) <button type="button" wire:click="increment" dusk="outer-island-increment">Outer Island Count: {{ $count }}</button> @island(lazy: true) <button type="button" wire:click="increment" dusk="inner-island-increment">Inner Island Count: {{ $count }}</button> @endisland @endisland <button type="button" wire:click="increment" dusk="root-increment">Root count: {{ $count }}</button> </div> HTML; } }]) ->assertNotPresent('@outer-island-increment') ->assertNotPresent('@inner-island-increment') ->assertPresent('@root-increment') ->scrollTo('@root-increment') ->waitForText('Outer Island Count: 0') ->assertPresent('@outer-island-increment') ->assertNotPresent('@inner-island-increment') ->assertPresent('@root-increment') ->waitForText('Inner Island Count: 0') ->assertPresent('@inner-island-increment') ->assertPresent('@root-increment') ; } public function test_island_with_lazy_and_always_updates_with_the_component_when_the_component_makes_a_request() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } public function render() { return <<<'HTML' <div> <button type="button" wire:click="increment" dusk="root-increment">Count: {{ $count }}</button> @island(lazy: true, always: true) <button type="button" wire:click="increment" dusk="island-increment">Island Count: {{ $count }}</button> @endisland </div> @script <script> window.requestCount = 0 this.interceptMessage(() => { window.requestCount++ }) </script> @endscript HTML; } }]) ->waitForLivewireToLoad() ->waitForText('Island Count: 0') ->assertScript('window.requestCount', 1) // Initial lazy island load ->assertSeeIn('@root-increment', 'Count: 0') ->assertSeeIn('@island-increment', 'Island Count: 0') ->tap(fn ($b) => $b->script('window.requestCount = 0')) // Reset counter ->waitForLivewire()->click('@root-increment') ->pause(100) ->assertScript('window.requestCount', 1) // Should be only 1 request for both component and island ->assertSeeIn('@root-increment', 'Count: 1') ->assertSeeIn('@island-increment', 'Island Count: 1') ; } public function test_renderless_attribute_skips_island_render() { Livewire::visit([new class extends \Livewire\Component { public $count = 0; public function increment() { $this->count++; } #[\Livewire\Attributes\Renderless] public function incrementRenderless() { $this->count++; } public function render() { return <<<'HTML' <div> @island(name: 'foo') <div dusk="island-count">Count: {{ $count }}</div> @endisland <button type="button" wire:click="increment" dusk="increment" wire:island="foo">Increment</button> <button type="button" wire:click="incrementRenderless" dusk="increment-renderless" wire:island="foo">Increment Renderless</button> </div> HTML; } }]) ->assertSeeIn('@island-count', 'Count: 0') ->waitForLivewire()->click('@increment') ->assertSeeIn('@island-count', 'Count: 1') ->waitForLivewire()->click('@increment-renderless') // The count was incremented server-side but the island should NOT re-render... ->assertSeeIn('@island-count', 'Count: 1') ->waitForLivewire()->click('@increment') // Now the island should show the updated count (including the renderless increment)... ->assertSeeIn('@island-count', 'Count: 3') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportIslands/UnitTest.php
src/Features/SupportIslands/UnitTest.php
<?php namespace Livewire\Features\SupportIslands; use Tests\TestCase; use Livewire\Livewire; class UnitTest extends TestCase { public function test_render_island_directives() { Livewire::test(new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> Outside island @island Inside island @island Nested island @endisland after @endisland </div> HTML; } }) ->assertDontSee('@island') ->assertDontSee('@endisland') ->assertSee('Outside island') ->assertSee('Inside island') ->assertSee('Nested island') ->assertSee('!--[if FRAGMENT:') ->assertSee('!--[if ENDFRAGMENT:'); } public function test_island_with_raw_block() { Livewire::test(new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> Outside island @island <div> @php $foo = 'bar'; @endphp Inside island: {{ $foo }} </div> @endisland </div> HTML; } }) ->assertSee('Inside island: bar') ; } public function test_island_with_parameter_provides_scope() { Livewire::test(new class extends \Livewire\Component { public $componentData = 'component value'; public function render() { return <<<'HTML' <div> @island(with: ['bar' => 'baz', 'number' => 42]) <div> bar: {{ $bar ?? 'not set' }} number: {{ $number ?? 'not set' }} </div> @endisland </div> HTML; } }) ->assertSee('bar: baz') ->assertSee('number: 42'); } public function test_island_with_parameter_can_reference_component_properties() { Livewire::test(new class extends \Livewire\Component { public $myData = 'from component'; public function render() { return <<<'HTML' <div> @island(with: ['data' => $this->myData]) <div>data: {{ $data ?? 'not set' }}</div> @endisland </div> HTML; } }) ->assertSee('data: from component'); } public function test_island_with_empty_parameter_still_renders() { Livewire::test(new class extends \Livewire\Component { public function render() { return <<<'HTML' <div> @island(name: 'test') <div>content without with parameter</div> @endisland </div> HTML; } }) ->assertSee('content without with parameter'); } public function test_island_with_parameter_overrides_component_properties() { Livewire::test(new class extends \Livewire\Component { public $count = 999; public function render() { return <<<'HTML' <div> @island(with: ['count' => 123]) <div>count: {{ $count }}</div> @endisland </div> HTML; } }) ->assertSee('count: 123') ->assertDontSee('count: 999'); } public function test_runtime_with_overrides_directive_with() { Livewire::test(new class extends \Livewire\Component { public $count = 999; public function refreshWithData() { $this->renderIsland('test', null, 'morph', ['count' => 456]); } public function render() { return <<<'HTML' <div> @island(name: 'test', with: ['count' => 123]) <div>count: {{ $count }}</div> @endisland <button wire:click="refreshWithData">Refresh</button> </div> HTML; } }) ->assertSee('count: 123') ->call('refreshWithData'); // After calling refreshWithData, the island should show the runtime value // Note: we can't easily assert on the fragment, but we can verify no errors occur } public function test_precedence_order() { Livewire::test(new class extends \Livewire\Component { public $value = 'component'; public function render() { return <<<'HTML' <div> @island(with: ['value' => 'directive']) <div>value: {{ $value }}</div> @endisland </div> HTML; } }) ->assertSee('value: directive') ->assertDontSee('value: component'); } public function test_runtime_with_works_on_island_without_directive_with() { Livewire::test(new class extends \Livewire\Component { public function refreshWithData() { $this->renderIsland('plain', null, 'morph', ['data' => 'runtime']); } public function render() { return <<<'HTML' <div> @island(name: 'plain') <div>data: {{ $data ?? 'not set' }}</div> @endisland <button wire:click="refreshWithData">Refresh</button> </div> HTML; } }) ->assertSee('data: not set') ->call('refreshWithData'); } public function test_runtime_with_works_on_island_with_no_parameters() { Livewire::test(new class extends \Livewire\Component { public function refreshWithData() { // Find the token for the unnamed island $islands = $this->getIslands(); $token = $islands[0]['token'] ?? null; if ($token) { $this->renderIsland($token, null, 'morph', ['data' => 'runtime']); } } public function render() { return <<<'HTML' <div> @island <div>data: {{ $data ?? 'not set' }}</div> @endisland <button wire:click="refreshWithData">Refresh</button> </div> HTML; } }) ->assertSee('data: not set') ->call('refreshWithData'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportIslands/SupportIslands.php
src/Features/SupportIslands/SupportIslands.php
<?php namespace Livewire\Features\SupportIslands; use Livewire\Features\SupportIslands\Compiler\IslandCompiler; use Illuminate\Support\Facades\Blade; use Livewire\ComponentHook; class SupportIslands extends ComponentHook { public static function provide() { static::registerInlineIslandPrecompiler(); static::registerIslandDirective(); } public static function registerIslandDirective() { Blade::directive('island', function ($expression) { return "<?php if (isset(\$__livewire)) echo \$__livewire->renderIslandDirective({$expression}); ?>"; }); } public static function registerInlineIslandPrecompiler() { Blade::prepareStringsForCompilationUsing(function ($content) { // Shortcut out if there are no islands in the content... if (! str_contains($content, '@endisland')) return $content; $pathSignature = Blade::getPath() ?: crc32($content); return IslandCompiler::compile($pathSignature, $content); }); } function call($method, $params, $returnEarly, $metadata, $componentContext) { if (! isset($metadata['island'])) return; $island = $metadata['island']; $mount = false; if ($method === '__lazyLoadIsland') { $mount = true; $returnEarly(); } // if metadata contains an island, then we should render it... return function (...$params) use ($island, $componentContext, $mount) { ['name' => $name, 'mode' => $mode] = $island; $islands = $this->component->getIslands(); $islands = array_filter($islands, fn ($island) => $island['name'] === $name); if (empty($islands)) return; // If #[Renderless] attribute was used, don't render the island... if ($this->storeGet('skipIslandsRender', false)) return; $this->component->skipRender(); $this->component->renderIsland( name: $name, mode: $mode, mount: $mount, ); }; } public function dehydrate($context) { $context->addMemo('islands', $this->component->getIslands()); if ($this->component->hasRenderedIslandFragments()) { $context->addEffect('islandFragments', $this->component->getRenderedIslandFragments()); } } public function hydrate($memo) { $this->component->markIslandsAsMounted(); $islands = $memo['islands'] ?? null; if (! $islands) return; $this->component->setIslands($islands ?? []); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportIslands/Compiler/IslandCompiler.php
src/Features/SupportIslands/Compiler/IslandCompiler.php
<?php namespace Livewire\Features\SupportIslands\Compiler; use Illuminate\Support\Facades\File; use Illuminate\Support\Arr; class IslandCompiler { protected string $mutableContents; public function __construct( public string $pathSignature, public string $contents, ) { $this->mutableContents = $contents; } public static function compile(string $pathSignature, string $contents): string { $compiler = new self($pathSignature, $contents); return $compiler->process(); } public function process(): string { $compiler = $this->getHackedBladeCompiler(); $currentNestingLevel = 1; $maxNestingLevel = $currentNestingLevel; $startDirectiveCount = 1; $compiler->directive('island', function ($expression) use (&$currentNestingLevel, &$maxNestingLevel, &$startDirectiveCount) { $maxNestingLevel = max($maxNestingLevel, $currentNestingLevel); return '[STARTISLAND:' . $startDirectiveCount++ . ':' . $currentNestingLevel++ . ']('.$expression.')'; }); $compiler->directive('endisland', function () use (&$currentNestingLevel) { return '[ENDISLAND:' . --$currentNestingLevel . ']'; }); if ($currentNestingLevel !== 1) { throw new \Exception('Start @island directive found without a matching @endisland directive'); } $result = $compiler->compileStatementsMadePublic($this->mutableContents); for ($i=$maxNestingLevel; $i >= $currentNestingLevel; $i--) { $result = preg_replace_callback('/(\[STARTISLAND:([0-9]+):' . $i . '\])\((.*?)\)(.*?)(\[ENDISLAND:' . $i . '\])/s', function ($matches) use ($i) { $occurrence = $matches[2]; $innerContent = $matches[4]; $expression = $matches[3]; if (str_contains($innerContent, '@placeholder')) { $innerContent = str_replace('@placeholder', '<'.'?php if (isset($__placeholder)) { ob_start(); } if (isset($__placeholder)): ?'.'>', $innerContent); $innerContent = str_replace('@endplaceholder', '<'.'?php endif; if (isset($__placeholder)) { echo ob_get_clean(); return; } ?'.'>', $innerContent); } else { $innerContent = '<'.'?php if (isset($__placeholder)) { echo $__placeholder; return; } ?'.'>' . "\n\n" . $innerContent; } return $this->compileIsland( occurrence: $occurrence, nestingLevel: $i, expression: $expression, innerContent: $innerContent, ); }, $result); } return $result; } public function compileIsland(int $occurrence, int $nestingLevel, string $expression, string $innerContent): string { // Get the cached path for the extracted island... $hash = $this->getPathBasedHash($this->pathSignature); $token = $hash . '-' . $occurrence; $cachedPath = self::getCachedPathFromToken($token); // Build the output directive for the island... $output = '@island'; if (trim($expression) === '') { $output .= '(token: \'' . $token . '\')'; } else { $output .= '(' . $expression . ', token: \'' . $token . '\')'; } // Inject scope provider code at the top of the island view... $scopeProviderCode = $this->generateScopeProviderCode($expression); $innerContent = $scopeProviderCode . $innerContent; // Ensure the cached directory exists... File::ensureDirectoryExists(dirname($cachedPath)); // Write the cached island to the file system... file_put_contents($cachedPath, $innerContent); app('livewire.compiler')->cacheManager->mutateFileModificationTime($cachedPath); return $output; } protected function generateScopeProviderCode(string $expression): string { $directiveWithExtraction = ''; // Only extract directive's "with" if there's an expression if (trim($expression) !== '') { $directiveWithExtraction = <<<PHP // Extract directive's "with" parameter (overrides component properties) \$__islandScope = (function(\$name = null, \$token = null, \$lazy = false, \$defer = false, \$always = false, \$skip = false, \$with = []) { return \$with; })({$expression}); if (!empty(\$__islandScope)) { extract(\$__islandScope, EXTR_OVERWRITE); } PHP; } // Always include runtime "with" extraction (even if directive has no parameters) return <<<PHP <?php {$directiveWithExtraction}// Extract runtime "with" parameter if provided (overrides everything) if (isset(\$__runtimeWith) && is_array(\$__runtimeWith) && !empty(\$__runtimeWith)) { extract(\$__runtimeWith, EXTR_OVERWRITE); } ?> PHP; } public static function getCachedPathFromToken(string $token): string { $cachedDirectory = app('livewire.compiler')->cacheManager->cacheDirectory; return $cachedDirectory . '/islands/' . $token . '.blade.php'; } public function getPathBasedHash(string $path): string { return app('livewire.compiler')->cacheManager->getHash( $this->pathSignature, ); } public function getHackedBladeCompiler() { $instance = new class ( app('files'), storage_path('framework/views/livewire'), ) extends \Illuminate\View\Compilers\BladeCompiler { /** * Make this method public... */ public function compileStatementsMadePublic($template) { return $this->compileStatements($template); } /** * Tweak this method to only process custom directives so we * can restrict rendering solely to @island related directives... */ protected function compileStatement($match) { if (str_contains($match[1], '@')) { $match[0] = isset($match[3]) ? $match[1].$match[3] : $match[1]; } elseif (isset($this->customDirectives[$match[1]])) { $match[0] = $this->callCustomDirective($match[1], Arr::get($match, 3)); } elseif (method_exists($this, $method = 'compile'.ucfirst($match[1]))) { // Don't process through built-in directive methods... // $match[0] = $this->$method(Arr::get($match, 3)); // Just return the original match... return $match[0]; } else { return $match[0]; } return isset($match[3]) ? $match[0] : $match[0].$match[2]; } }; return $instance; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportCSP/BrowserTest.php
src/Features/SupportCSP/BrowserTest.php
<?php namespace Livewire\Features\SupportCSP; use Tests\BrowserTestCase; use Livewire\Component; use Livewire\Livewire; class BrowserTest extends BrowserTestCase { public static function tweakApplicationHook() { return function () { config(['livewire.csp_safe' => true]); }; } public function test_complex_expression_is_invalid_with_csp() { Livewire::visit(new class extends Component { public $count = 0; public function setCount($count) { $this->count = $count; } public function render() { return <<<'HTML' <div> <span dusk="count">{{ $count }}</span> <button dusk="set-count" wire:click="setCount($wire.count + (() => 1)())">+</button> </div> HTML; } }) ->assertSee('0') ->assertConsoleLogHasNoErrors() ->click('@set-count') ->assertConsoleLogHasErrors() ; } public function test_basic_counter_component_works_with_csp() { Livewire::visit(new class extends Component { public $count = 0; public function increment() { $this->count++; } public function decrement() { $this->count--; } public function render() { return <<<'HTML' <div> <span dusk="count">{{ $count }}</span> <button dusk="increment" wire:click="increment">+</button> <button dusk="decrement" wire:click="decrement">-</button> </div> HTML; } }) ->assertSee('0') ->waitForLivewire()->click('@increment') ->assertSee('1') ->waitForLivewire()->click('@increment') ->assertSee('2') ->waitForLivewire()->click('@decrement') ->assertSee('1') ; } public function test_wire_model_works_with_csp() { Livewire::visit(new class extends Component { public $message = ''; public $number = 0; public function render() { return <<<'HTML' <div> <input dusk="message" type="text" wire:model="message" placeholder="Type something..."> <span dusk="output">{{ $message }}</span> <input dusk="number" type="number" wire:model="number"> <span dusk="number-output">{{ $number }}</span> <button dusk="refresh" wire:click="$refresh">Refresh</button> </div> HTML; } }) ->type('@message', 'Hello CSP') ->waitForLivewire()->click('@refresh') ->assertSee('Hello CSP') ->type('@number', '42') ->waitForLivewire()->click('@refresh') ->assertSee('42') ; } public function test_wire_model_live_works_with_csp() { Livewire::visit(new class extends Component { public $search = ''; public function render() { return <<<'HTML' <div> <input dusk="search" type="text" wire:model.live="search" placeholder="Search..."> <div dusk="results">Results: {{ strlen($search) }} characters</div> </div> HTML; } }) ->assertSee('Results: 0 characters') ->type('@search', 'test') ->waitForText('Results: 4 characters') ->type('@search', 'testing') ->waitForText('Results: 7 characters') ; } public function test_wire_submit_works_with_csp() { Livewire::visit(new class extends Component { public $name = ''; public $submitted = false; public function submit() { $this->submitted = true; } public function render() { return <<<'HTML' <div> <form wire:submit="submit"> <input dusk="name" type="text" wire:model="name" placeholder="Enter name"> <button dusk="submit" type="submit">Submit</button> </form> @if($submitted) <div dusk="success">Form submitted with: {{ $name }}</div> @endif </div> HTML; } }) ->assertDontSee('Form submitted with:') ->type('@name', 'John Doe') ->waitForLivewire()->click('@submit') ->waitForText('Form submitted with: John Doe') ; } public function test_wire_loading_works_with_csp() { Livewire::visit(new class extends Component { public function slowAction() { sleep(1); } public function render() { return <<<'HTML' <div> <button dusk="slow-button" wire:click="slowAction">Slow Action</button> <div dusk="loading" wire:loading>Loading...</div> <div dusk="loading-target" wire:loading.remove wire:target="slowAction">Ready</div> </div> HTML; } }) ->assertSee('Ready') ->assertDontSee('Loading...') ->click('@slow-button') ->waitForText('Loading...') ->assertDontSee('Ready') ->waitForText('Ready', 5) ->assertDontSee('Loading...') ; } public function test_wire_dirty_works_with_csp() { Livewire::visit(new class extends Component { public $text = ''; public function render() { return <<<'HTML' <div> <input dusk="text" type="text" wire:model="text"> <div dusk="dirty" wire:dirty>Unsaved changes</div> <div dusk="clean" wire:dirty.remove>All saved</div> <button dusk="refresh" wire:click="$refresh">Refresh</button> </div> HTML; } }) ->assertSee('All saved') ->assertDontSee('Unsaved changes') ->type('@text', 'test') ->assertSee('Unsaved changes') ->assertDontSee('All saved') ->waitForLivewire()->click('@refresh') ->assertSee('All saved') ->assertDontSee('Unsaved changes') ; } public function test_conditional_rendering_works_with_csp() { Livewire::visit(new class extends Component { public $show = false; public function toggle() { $this->show = !$this->show; } public function render() { return <<<'HTML' <div> <button dusk="toggle" wire:click="toggle">Toggle</button> @if($show) <div dusk="content">This content is visible</div> @else <div dusk="hidden">This content is hidden</div> @endif </div> HTML; } }) ->assertSee('This content is hidden') ->assertDontSee('This content is visible') ->waitForLivewire()->click('@toggle') ->assertSee('This content is visible') ->assertDontSee('This content is hidden') ->waitForLivewire()->click('@toggle') ->assertSee('This content is hidden') ->assertDontSee('This content is visible') ; } public function test_multiple_actions_work_with_csp() { Livewire::visit(new class extends Component { public $counter = 0; public $message = ''; public function increment() { $this->counter++; } public function updateMessage($text) { $this->message = $text; } public function resetProperties() { $this->counter = 0; $this->message = ''; } public function render() { return <<<'HTML' <div> <div dusk="counter">Count: {{ $counter }}</div> <div dusk="message">Message: {{ $message }}</div> <button dusk="increment" wire:click="increment">Increment</button> <button dusk="set-message" wire:click="updateMessage('Hello World')">Set Message</button> <button dusk="reset" wire:click="resetProperties">Reset</button> </div> HTML; } }) ->assertSee('Count: 0') ->assertSee('Message:') ->waitForLivewire()->click('@increment') ->assertSee('Count: 1') ->waitForLivewire()->click('@set-message') ->assertSee('Message: Hello World') ->waitForLivewire()->click('@increment') ->assertSee('Count: 2') ->waitForLivewire()->click('@reset') ->assertSee('Count: 0') ->assertSee('Message:') ; } public function test_wire_keydown_works_with_csp() { Livewire::visit(new class extends Component { public $pressed = false; public function handleEnter() { $this->pressed = true; } public function render() { return <<<'HTML' <div> <input dusk="input" type="text" wire:keydown.enter="handleEnter" placeholder="Press Enter"> @if($pressed) <div dusk="pressed">Enter was pressed!</div> @endif </div> HTML; } }) ->assertDontSee('Enter was pressed!') ->keys('@input', '{enter}') ->waitForText('Enter was pressed!') ; } public function test_wire_model_dot_notation_works_with_csp() { Livewire::visit(new class extends Component { public $user = [ 'name' => '', 'email' => '', 'profile' => [ 'bio' => '', 'age' => 0 ] ]; public function render() { return <<<'HTML' <div> <input dusk="name" type="text" wire:model="user.name" placeholder="Name"> <input dusk="email" type="email" wire:model="user.email" placeholder="Email"> <textarea dusk="bio" wire:model="user.profile.bio" placeholder="Bio"></textarea> <input dusk="age" type="number" wire:model="user.profile.age" placeholder="Age"> <div dusk="output"> <div>Name: {{ $user['name'] }}</div> <div>Email: {{ $user['email'] }}</div> <div>Bio: {{ $user['profile']['bio'] }}</div> <div>Age: {{ $user['profile']['age'] }}</div> </div> <button dusk="refresh" wire:click="$refresh">Refresh</button> </div> HTML; } }) ->type('@name', 'John Doe') ->type('@email', 'john@example.com') ->type('@bio', 'Software developer') ->type('@age', '30') ->waitForLivewire()->click('@refresh') ->assertSee('Name: John Doe') ->assertSee('Email: john@example.com') ->assertSee('Bio: Software developer') ->assertSee('Age: 30') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPageComponents/MissingLayoutException.php
src/Features/SupportPageComponents/MissingLayoutException.php
<?php namespace Livewire\Features\SupportPageComponents; use Exception; class MissingLayoutException extends Exception { function __construct(string $layout) { parent::__construct('Livewire page component layout view not found: ['.$layout.']'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPageComponents/BaseLayout.php
src/Features/SupportPageComponents/BaseLayout.php
<?php namespace Livewire\Features\SupportPageComponents; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; #[\Attribute] class BaseLayout extends LivewireAttribute { function __construct( public $name, public $params = [], ) {} }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPageComponents/UnitTest.php
src/Features/SupportPageComponents/UnitTest.php
<?php namespace Livewire\Features\SupportPageComponents; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Route; use Illuminate\Http\Response; use Illuminate\Http\Request; use Livewire\Component; use Livewire\Livewire; class UnitTest extends \Tests\TestCase { public function test_uses_standard_app_layout_by_default() { Route::get('/configurable-layout', ComponentForConfigurableLayoutTest::class); $this ->withoutExceptionHandling() ->get('/configurable-layout') ->assertSee('foo') ->assertDontSee('baz'); } public function test_can_configure_a_default_layout() { config()->set('livewire.component_layout', 'layouts.app-with-baz-hardcoded'); Route::get('/configurable-layout', ComponentForConfigurableLayoutTest::class); $this ->get('/configurable-layout') ->assertSee('foo') ->assertSee('baz'); } public function test_can_configure_the_default_layout_to_a_class_based_component_layout() { config()->set('livewire.component_layout', \LegacyTests\AppLayout::class); Route::get('/configurable-layout', ComponentForConfigurableLayoutTest::class); $this ->withoutExceptionHandling() ->get('/configurable-layout') ->assertSee('foo') ->assertSee('bar') ->assertDontSee('baz'); } public function test_can_show_params_with_a_configured_class_based_component_layout() { config()->set('livewire.component_layout', \LegacyTests\AppLayout::class); Route::get('/configurable-layout', ComponentForConfigurableLayoutTestWithCustomParams::class); $this ->get('/configurable-layout') ->assertSee('foo') ->assertSee('bar') ->assertSee('baz'); } public function test_can_set_custom_slot_for_a_configured_class_based_component_layout() { config()->set('livewire.component_layout', \LegacyTests\AppLayout::class); Route::get('/configurable-layout', ComponentForConfigurableLayoutTestWithCustomSlot::class); $this ->get('/configurable-layout') ->assertSee('foo') ->assertSee('bar'); } public function test_can_configure_the_default_layout_to_an_anonymous_component_layout() { config()->set('livewire.component_layout', 'layouts.app-anonymous-component'); Route::get('/configurable-layout', ComponentForConfigurableLayoutTest::class); $this ->get('/configurable-layout') ->assertSee('foo') ->assertSee('bar') ->assertDontSee('baz'); } public function test_can_show_params_with_a_configured_anonymous_component_layout() { config()->set('livewire.component_layout', 'layouts.app-anonymous-component'); Route::get('/configurable-layout', ComponentForConfigurableLayoutTestWithCustomParams::class); $this ->get('/configurable-layout') ->assertSee('foo') ->assertSee('bar') ->assertSee('baz'); } public function test_can_set_custom_slot_for_a_configured_anonymous_component_layout() { config()->set('livewire.component_layout', 'layouts.app-anonymous-component'); Route::get('/configurable-layout', ComponentForConfigurableLayoutTestWithCustomSlot::class); $this ->get('/configurable-layout') ->assertSee('foo') ->assertSee('bar'); } public function test_can_show_params_with_a_configured_anonymous_component_layout_that_has_a_required_prop() { config()->set('livewire.component_layout', 'layouts.app-anonymous-component-with-required-prop'); Route::get('/configurable-layout', ComponentForConfigurableLayoutTestWithCustomParams::class); $this ->get('/configurable-layout') ->assertSee('foo') ->assertSee('bar') ->assertSee('baz'); } public function test_can_override_optional_props_with_a_configured_anonymous_component_layout() { config()->set('livewire.component_layout', 'layouts.app-anonymous-component'); Route::get('/configurable-layout', ComponentForConfigurableLayoutTestWithCustomFooParam::class); $this ->get('/configurable-layout') ->assertSee('foo') ->assertDontSee('bar') ->assertSee('baz'); } public function test_can_pass_attributes_to_a_configured_class_based_component_layout() { config()->set('livewire.component_layout', \LegacyTests\AppLayout::class); Route::get('/configurable-layout', ComponentForConfigurableLayoutTestWithCustomAttributes::class); $this ->get('/configurable-layout') ->assertSee('class="foo"', false) ->assertSee('id="foo"', false); } public function test_can_use_a_configured_class_based_component_layout_with_properties() { config()->set('livewire.component_layout', \LegacyTests\AppLayoutWithProperties::class); Route::get('/configurable-layout', ComponentForConfigurableLayoutTest::class); $this ->get('/configurable-layout') ->assertSee('foo') ->assertSee('bar'); } public function test_can_pass_attributes_to_a_configured_anonymous_component_layout() { config()->set('livewire.component_layout', 'layouts.app-anonymous-component'); Route::get('/configurable-layout', ComponentForConfigurableLayoutTestWithCustomAttributes::class); $this ->get('/configurable-layout') ->assertSee('class="foo"', false); } public function test_can_extend_a_blade_layout() { $this->withoutExceptionHandling(); Livewire::component(ComponentWithExtendsLayout::class); Route::get('/foo', ComponentWithExtendsLayout::class); $this->get('/foo')->assertSee('baz'); } public function test_can_set_custom_section() { Livewire::component(ComponentWithCustomSection::class); Route::get('/foo', ComponentWithCustomSection::class); $this->withoutExceptionHandling()->get('/foo')->assertSee('baz'); } public function test_can_set_custom_layout() { Livewire::component(ComponentWithCustomLayout::class); Route::get('/foo', ComponentWithCustomLayout::class); $this->withoutExceptionHandling()->get('/foo')->assertSee('baz'); } public function test_can_set_custom_slot_for_a_layout() { Livewire::component(ComponentWithCustomSlotForLayout::class); Route::get('/foo', ComponentWithCustomSlotForLayout::class); $this->withoutExceptionHandling()->get('/foo')->assertSee('baz'); } public function test_can_show_params_with_a_custom_class_based_component_layout() { Livewire::component(ComponentWithClassBasedComponentLayout::class); Route::get('/foo', ComponentWithClassBasedComponentLayout::class); $this->withoutExceptionHandling()->get('/foo') ->assertSee('bar') ->assertSee('baz'); } public function test_can_show_params_set_in_the_constructor_of_a_custom_class_based_component_layout() { Livewire::component(ComponentWithClassBasedComponentLayoutAndParams::class); Route::get('/foo', ComponentWithClassBasedComponentLayoutAndParams::class); $this->withoutExceptionHandling()->get('/foo') ->assertSee('bar') ->assertSee('baz'); } public function test_can_show_attributes_with_a_custom_class_based_component_layout() { Livewire::component(ComponentWithClassBasedComponentLayoutAndAttributes::class); Route::get('/foo', ComponentWithClassBasedComponentLayoutAndAttributes::class); $this->withoutExceptionHandling()->get('/foo') ->assertSee('class="foo"', false); } public function test_can_show_params_with_a_custom_anonymous_component_layout() { Livewire::component(ComponentWithAnonymousComponentLayout::class); Route::get('/foo', ComponentWithAnonymousComponentLayout::class); $this->withoutExceptionHandling()->get('/foo') ->assertSee('bar') ->assertSee('baz'); } public function test_can_show_attributes_with_a_custom_anonymous_component_layout() { Livewire::component(ComponentWithAnonymousComponentLayoutAndAttributes::class); Route::get('/foo', ComponentWithAnonymousComponentLayoutAndAttributes::class); $this->withoutExceptionHandling()->get('/foo') ->assertSee('class="foo"', false) ->assertSee('id="foo"', false); } public function test_can_show_the_params() { Livewire::component(ComponentWithCustomParams::class); Route::get('/foo', ComponentWithCustomParams::class); $this->withoutExceptionHandling()->get('/foo') ->assertSee('foo'); } public function test_can_show_params_with_custom_layout() { Livewire::component(ComponentWithCustomParamsAndLayout::class); Route::get('/foo', ComponentWithCustomParamsAndLayout::class); $this->withoutExceptionHandling()->get('/foo') ->assertSee('livewire'); } public function test_route_supports_laravels_missing_fallback_function(): void { Route::get('awesome-js/{framework}', ComponentWithModel::class) ->missing(function (Request $request) { $this->assertEquals(request(), $request); return redirect()->to('awesome-js/alpine'); }); $this->get('/awesome-js/jquery')->assertRedirect('/awesome-js/alpine'); } public function test_can_pass_parameters_to_a_layout_file() { Livewire::component(ComponentForRouteRegistration::class); Route::get('/foo', ComponentForRouteRegistration::class); $this->withoutExceptionHandling()->get('/foo')->assertSee('baz'); } public function test_can_handle_requests_after_application_is_created() { Livewire::component(ComponentForRouteRegistration::class); Route::get('/foo', ComponentForRouteRegistration::class); // After application is created, // request()->route() is null $this->createApplication(); $this->withoutExceptionHandling()->get('/foo')->assertSee('baz'); } public function test_component_uses_alias_instead_of_full_name_if_registered() { Livewire::component('component-alias', ComponentForRouteRegistration::class); Route::get('/foo', ComponentForRouteRegistration::class); $this->withoutExceptionHandling()->get('/foo') ->assertSee('component-alias'); } public function test_can_configure_layout_using_layout_attribute() { Route::get('/configurable-layout', ComponentForRenderLayoutAttribute::class); $this ->withoutExceptionHandling() ->get('/configurable-layout') ->assertSee('bob') ->assertSee('baz'); } public function test_can_configure_layout_using_layout_attribute_on_class_instead_of_render_method() { Route::get('/configurable-layout', ComponentForClassLayoutAttribute::class); $this ->withoutExceptionHandling() ->get('/configurable-layout') ->assertSee('bob') ->assertSee('baz'); } public function test_can_configure_layout_using_layout_attribute_on_parent_class() { Route::get('/configurable-layout', ComponentForParentClassLayoutAttribute::class); $this ->withoutExceptionHandling() ->get('/configurable-layout') ->assertSee('bob') ->assertSee('baz'); } public function test_can_configure_title_using_title_attribute() { Route::get('/configurable-layout', ComponentForTitleAttribute::class); $this ->withoutExceptionHandling() ->get('/configurable-layout') ->assertSee('bob') ->assertSee('some-title'); } public function test_can_use_layout_slots_in_full_page_components() { Route::get('/configurable-layout', ComponentWithMultipleLayoutSlots::class); $this ->withoutExceptionHandling() ->get('/configurable-layout') ->assertDontSeeText('No Header') ->assertDontSeeText('No Footer') ->assertSee('I am a header - foo') ->assertSee('Hello World') ->assertSee('I am a footer - foo'); } public function test_can_modify_response() { Route::get('/configurable-layout', ComponentWithCustomResponseHeaders::class); $this ->get('/configurable-layout') ->assertHeader('x-livewire', 'awesome'); } public function test_can_configure_title_in_render_method_and_layout_using_layout_attribute() { Route::get('/configurable-layout', ComponentWithClassBasedComponentTitleAndLayoutAttribute::class); $this ->withoutExceptionHandling() ->get('/configurable-layout') ->assertSee('some-title'); } public function test_can_push_to_stacks() { Route::get('/layout-with-stacks', ComponentWithStacks::class); $this ->withoutExceptionHandling() ->get('/layout-with-stacks') ->assertSee('I am a style') ->assertSee('I am a script 1') ->assertDontSee('I am a script 2'); } public function test_can_use_multiple_slots_with_same_name() { $this->markTestSkipped('Skipping this test because it passes when run in isolation but fails when run with other tests'); Route::get('/slots', ComponentWithTwoHeaderSlots::class); $this ->withoutExceptionHandling() ->get('/slots') ->assertSee('No Header') ->assertSee('The component header'); } public function can_access_route_parameters_without_mount_method() { Route::get('/route-with-params/{myId}', ComponentForRouteWithoutMountParametersTest::class); $this->get('/route-with-params/123')->assertSeeText('123'); } public function test_can_access_route_parameters_with_mount_method() { Route::get('/route-with-params/{myId}', ComponentForRouteWithMountParametersTest::class); $this->get('/route-with-params/123')->assertSeeText('123'); } } class ComponentForRouteWithoutMountParametersTest extends Component { public $myId; public function render() { return <<<'HTML' <div> {{ $myId }} </div> HTML; } } class ComponentForRouteWithMountParametersTest extends Component { public $myId; public function mount() { } public function render() { return <<<'HTML' <div> {{ $myId }} </div> HTML; } } class ComponentForConfigurableLayoutTest extends Component { public $name = 'foo'; public function render() { return view('show-name'); } } class ComponentForConfigurableLayoutTestWithCustomParams extends Component { public $name = 'foo'; public function render() { return view('show-name')->layoutData([ 'bar' => 'baz', ]); } } class ComponentForConfigurableLayoutTestWithCustomSlot extends Component { public $name = 'foo'; public function render() { return view('show-name')->slot('bar'); } } class ComponentForConfigurableLayoutTestWithCustomFooParam extends Component { public $name = 'foo'; public function render() { return view('show-name')->layoutData([ 'foo' => 'baz', ]); } } class ComponentForConfigurableLayoutTestWithCustomAttributes extends Component { public $name = 'foo'; public function render() { return view('show-name')->layoutData([ 'attributes' => [ 'class' => 'foo', ] ]); } } class ComponentWithExtendsLayout extends Component { public function render() { return view('null-view')->extends('layouts.app-extends', [ 'bar' => 'baz' ]); } } class ComponentWithCustomSection extends Component { public $name = 'baz'; public function render() { return view('show-name')->extends('layouts.app-custom-section')->section('body'); } } class ComponentWithCustomLayout extends Component { public function render() { return view('null-view')->layout('layouts.app-with-bar', [ 'bar' => 'baz' ]); } } class ComponentWithCustomSlotForLayout extends Component { public $name = 'baz'; public function render() { return view('show-name')->layout('layouts.app-custom-slot')->slot('main'); } } class ComponentWithClassBasedComponentLayout extends Component { public function render() { return view('null-view')->layout(\LegacyTests\AppLayout::class, [ 'bar' => 'baz' ]); } } class ComponentWithClassBasedComponentLayoutAndParams extends Component { public function render() { return view('null-view')->layout(\LegacyTests\AppLayoutWithConstructor::class, [ 'bar' => 'baz' ]); } } class ComponentWithClassBasedComponentLayoutAndAttributes extends Component { public function render() { return view('null-view')->layout(\LegacyTests\AppLayout::class, [ 'attributes' => [ 'class' => 'foo', ], ]); } } class ComponentWithAnonymousComponentLayout extends Component { public function render() { return view('null-view')->layout('layouts.app-anonymous-component', [ 'bar' => 'baz' ]); } } class ComponentWithAnonymousComponentLayoutAndAttributes extends Component { public function render() { return view('null-view')->layout('layouts.app-anonymous-component', [ 'attributes' => [ 'class' => 'foo', ], ]); } } class ComponentWithCustomParams extends Component { public function render() { return view('null-view')->layout('layouts.old-app')->layoutData([ 'customParam' => 'foo' ]); } } class ComponentWithCustomParamsAndLayout extends Component { public function render() { return view('null-view')->layout('layouts.data-test')->layoutData([ 'title' => 'livewire', ]); } } class ComponentWithCustomResponseHeaders extends Component { public function render() { return view('null-view')->response(fn(Response $response) => $response->header('x-livewire', 'awesome')); } } class FrameworkModel extends Model { public function resolveRouteBinding($value, $field = null) { throw new ModelNotFoundException; } } class ComponentForRouteRegistration extends Component { public $name = 'bar'; public function render() { return view('show-name')->layout('layouts.app-with-bar', [ 'bar' => 'baz', ]); } } class ComponentForRenderLayoutAttribute extends Component { public $name = 'bob'; #[BaseLayout('layouts.app-with-bar', ['bar' => 'baz'])] public function render() { return view('show-name'); } } #[BaseLayout('layouts.app-with-bar', ['bar' => 'baz'])] class ComponentForClassLayoutAttribute extends Component { public $name = 'bob'; public function render() { return view('show-name'); } } class ComponentForParentClassLayoutAttribute extends ComponentForClassLayoutAttribute { // } class ComponentForTitleAttribute extends Component { public $name = 'bob'; #[BaseTitle('some-title')] #[BaseLayout('layouts.app-with-title')] public function render() { return view('show-name'); } } class ComponentWithMultipleLayoutSlots extends Component { public function render() { return view('show-layout-slots', [ 'bar' => 'foo', ])->layout('layouts.app-layout-with-slots'); } } class ComponentWithTwoHeaderSlots extends Component { public function render() { return view('show-double-header-slot') ->layout('layouts.app-layout-with-slots'); } } class ComponentWithModel extends Component { public FrameworkModel $framework; } #[BaseLayout('layouts.app-with-title')] class ComponentWithClassBasedComponentTitleAndLayoutAttribute extends Component { public function render() { return view('null-view') ->title('some-title'); } } #[BaseLayout('layouts.app-layout-with-stacks')] class ComponentWithStacks extends Component { public function render() { return <<<'HTML' <div> Contents </div> @push('styles') <div>I am a style</div> @endpush @foreach([1, 2] as $attempt) @once @push('scripts') <div>I am a script {{ $attempt }}</div> @endpush @endonce @endforeach HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPageComponents/BaseTitle.php
src/Features/SupportPageComponents/BaseTitle.php
<?php namespace Livewire\Features\SupportPageComponents; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; #[\Attribute] class BaseTitle extends LivewireAttribute { function __construct( public $content, ) {} }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPageComponents/HandlesPageComponents.php
src/Features/SupportPageComponents/HandlesPageComponents.php
<?php namespace Livewire\Features\SupportPageComponents; trait HandlesPageComponents { function __invoke() { // Here's we're hooking into the "__invoke" method being called on a component. // This way, users can pass Livewire components into Routes as if they were // simple invokable controllers. Ex: Route::get('...', SomeLivewireComponent::class); $html = null; $layoutConfig = SupportPageComponents::interceptTheRenderOfTheComponentAndRetreiveTheLayoutConfiguration(function () use (&$html) { $params = SupportPageComponents::gatherMountMethodParamsFromRouteParameters($this); $name = $this->getName() !== null ? $this->getName() : $this::class; $html = app('livewire')->mount($name, $params); }); $layoutConfig = $layoutConfig ?: new PageComponentConfig; $layoutConfig->normalizeViewNameAndParamsForBladeComponents(); $response = response(SupportPageComponents::renderContentsIntoLayout($html, $layoutConfig)); if (is_callable($layoutConfig->response)) { call_user_func($layoutConfig->response, $response); } return $response; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPageComponents/PageComponentConfig.php
src/Features/SupportPageComponents/PageComponentConfig.php
<?php namespace Livewire\Features\SupportPageComponents; use Illuminate\View\AnonymousComponent; use Livewire\Mechanisms\HandleComponents\ViewContext; class PageComponentConfig { public $slots = []; public $viewContext = null; public $response; function __construct( public $type = 'component', public $view = '', public $slotOrSection = 'slot', public $params = [], ) { $this->view = $view ?: config('livewire.component_layout'); $this->viewContext = new ViewContext; } function mergeParams($toMerge) { $this->params = array_merge($toMerge, $this->params); } function normalizeViewNameAndParamsForBladeComponents() { // If a user passes the class name of a Blade component to the // layout macro (or uses inside their config), we need to // convert it to it's "view" name so Blade doesn't break. $view = $this->view; $params = $this->params; $attributes = $params['attributes'] ?? []; unset($params['attributes']); if (is_subclass_of($view, \Illuminate\View\Component::class)) { $layout = app()->makeWith($view, $params); $view = $layout->resolveView()->name(); $params = array_merge($params, $layout->resolveView()->getData()); } else { $layout = new AnonymousComponent($view, $params); } $layout->withAttributes($attributes); $params = array_merge($params, $layout->data()); $this->view = $view; $this->params = $params; // Remove default slot if present... if (isset($this->slots['default'])) unset($this->slots['default']); return $this; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportPageComponents/SupportPageComponents.php
src/Features/SupportPageComponents/SupportPageComponents.php
<?php namespace Livewire\Features\SupportPageComponents; use function Livewire\{on, off, once}; use Livewire\Drawer\ImplicitRouteBinding; use Livewire\ComponentHook; use Illuminate\View\View; use Illuminate\Support\Facades\Blade; use Illuminate\Database\Eloquent\ModelNotFoundException; class SupportPageComponents extends ComponentHook { static function provide() { static::registerLayoutViewMacros(); static::resolvePageComponentRouteBindings(); } static function registerLayoutViewMacros() { View::macro('layoutData', function ($data = []) { if (! isset($this->layoutConfig)) $this->layoutConfig = new PageComponentConfig; $this->layoutConfig->mergeParams($data); return $this; }); View::macro('section', function ($section) { if (! isset($this->layoutConfig)) $this->layoutConfig = new PageComponentConfig; $this->layoutConfig->slotOrSection = $section; return $this; }); View::macro('title', function ($title) { if (! isset($this->layoutConfig)) $this->layoutConfig = new PageComponentConfig; $this->layoutConfig->mergeParams(['title' => $title]); return $this; }); View::macro('slot', function ($slot) { if (! isset($this->layoutConfig)) $this->layoutConfig = new PageComponentConfig; $this->layoutConfig->slotOrSection = $slot; return $this; }); View::macro('extends', function ($view, $params = []) { if (! isset($this->layoutConfig)) $this->layoutConfig = new PageComponentConfig; $this->layoutConfig->type = 'extends'; $this->layoutConfig->slotOrSection = 'content'; $this->layoutConfig->view = $view; $this->layoutConfig->mergeParams($params); return $this; }); View::macro('layout', function ($view, $params = []) { if (! isset($this->layoutConfig)) $this->layoutConfig = new PageComponentConfig; $this->layoutConfig->type = 'component'; $this->layoutConfig->slotOrSection = 'slot'; $this->layoutConfig->view = $view; $this->layoutConfig->mergeParams($params); return $this; }); View::macro('response', function (callable $callback) { if (! isset($this->layoutConfig)) $this->layoutConfig = new PageComponentConfig; $this->layoutConfig->response = $callback; return $this; }); } static function interceptTheRenderOfTheComponentAndRetreiveTheLayoutConfiguration($callback) { $layoutConfig = null; $slots = []; // Only run this handler once for the parent-most component. Otherwise child components // will run this handler too and override the configured layout... $handler = once(function ($target, $view, $data) use (&$layoutConfig, &$slots) { $layoutAttr = $target->getAttributes()->whereInstanceOf(BaseLayout::class)->first(); $titleAttr = $target->getAttributes()->whereInstanceOf(BaseTitle::class)->first(); if ($layoutAttr) { $view->layout($layoutAttr->name, $layoutAttr->params); } if ($titleAttr) { $view->title($titleAttr->content); } $layoutConfig = $view->layoutConfig ?? new PageComponentConfig; return function ($html, $replace, $viewContext) use ($view, $layoutConfig) { // Gather up any slots and sections declared in the component template and store them // to be later forwarded into the layout component itself... $layoutConfig->viewContext = $viewContext; }; }); on('render', $handler); on('render.placeholder', $handler); $callback(); off('render', $handler); off('render.placeholder', $handler); return $layoutConfig; } static function gatherMountMethodParamsFromRouteParameters($component) { // This allows for route parameters like "slug" in /post/{slug}, // to be passed into a Livewire component's mount method... $route = request()->route(); if (! $route) return []; try { $params = (new ImplicitRouteBinding(app())) ->resolveAllParameters($route, new $component); } catch (ModelNotFoundException $exception) { if (method_exists($route,'getMissing') && $route->getMissing()) { abort( $route->getMissing()(request()) ); } throw $exception; } return $params; } static function renderContentsIntoLayout($content, $layoutConfig) { try { if ($layoutConfig->type === 'component') { return Blade::render(<<<'HTML' <?php $layout->viewContext->mergeIntoNewEnvironment($__env); ?> @component($layout->view, $layout->params) @slot($layout->slotOrSection) {!! $content !!} @endslot <?php // Manually forward slots defined in the Livewire template into the layout component... foreach ($layout->viewContext->slots[-1] ?? [] as $name => $slot) { $__env->slot($name, attributes: $slot->attributes->getAttributes()); echo $slot->toHtml(); $__env->endSlot(); } ?> @endcomponent HTML, [ 'content' => $content, 'layout' => $layoutConfig, ]); } else { return Blade::render(<<<'HTML' <?php $layout->viewContext->mergeIntoNewEnvironment($__env); ?> @extends($layout->view, $layout->params) @section($layout->slotOrSection) {!! $content !!} @endsection HTML, [ 'content' => $content, 'layout' => $layoutConfig, ]); } } catch (\Illuminate\View\ViewException $e) { $layout = $layoutConfig->view; if (str($e->getMessage())->startsWith('View ['.$layout.'] not found.')) { throw new MissingLayoutException($layout); } else { throw $e; } } } // This needs to exist so that authorization middleware (and other middleware) have access // to implicit route bindings based on the Livewire page component. Otherwise, Laravel // has no implicit binding references because the action is __invoke with no params protected static function resolvePageComponentRouteBindings() { // This method was introduced into Laravel 10.37.1 for this exact purpose... if (static::canSubstituteImplicitBindings()) { app('router')->substituteImplicitBindingsUsing(function ($container, $route, $default) { // If the current route is a Livewire page component... if ($componentClass = static::routeActionIsAPageComponent($route)) { // Resolve and set all page component parameters to the current route... (new \Livewire\Drawer\ImplicitRouteBinding($container)) ->resolveAllParameters($route, new $componentClass); } else { // Otherwise, run the default Laravel implicit binding system... $default(); } }); } } public static function canSubstituteImplicitBindings() { return method_exists(app('router'), 'substituteImplicitBindingsUsing'); } protected static function routeActionIsAPageComponent($route) { $action = $route->action; if (! $action) return false; $uses = $action['uses'] ?? false; if (! $uses) return; if (is_string($uses)) { $class = str($uses)->before('@')->toString(); $method = str($uses)->after('@')->toString(); if (is_subclass_of($class, \Livewire\Component::class) && $method === '__invoke') { return $class; } } return false; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireConfirm/BrowserTest.php
src/Features/SupportWireConfirm/BrowserTest.php
<?php namespace Livewire\Features\SupportWireConfirm; use Tests\BrowserTestCase; use Livewire\Component; use Livewire\Livewire; class BrowserTest extends BrowserTestCase { public function test_can_confirm_an_action() { Livewire::visit(new class extends Component { public $confirmed = false; public function someAction() { $this->confirmed = true; } public function render() { return <<<'HTML' <div> <button type="button" dusk="button" wire:click="someAction" wire:confirm>Confirm</button> @if ($confirmed) <span dusk="success">Confirmed!</span> @endif </div> HTML; } }) ->assertDontSee('Confirmed!') ->click('@button') ->assertDialogOpened('Are you sure?') ->dismissDialog() ->pause(500) ->assertDontSee('Confirmed!') ->click('@button') ->assertDialogOpened('Are you sure?') ->acceptDialog() ->waitForText('Confirmed!') ; } public function test_can_confirm_an_action_when_used_with_submit_directive() { $browser = Livewire::visit(new class extends Component { public $confirmed = false; public function someAction() { $this->confirmed = true; } public function render() { return <<<'HTML' <div> <form wire:submit="someAction" wire:confirm> <input type="text" dusk="input"> <input type="checkbox" dusk="checkbox"> <button type="submit" dusk="button">Confirm</button> @if ($confirmed) <span dusk="success">Confirmed!</span> @endif </form> </div> HTML; } }) ->assertDontSee('Confirmed!') ->click('@button') ->assertDialogOpened('Are you sure?') ->dismissDialog() ->pause(500) ->assertDontSee('Confirmed!'); // ensure the form is still interactable $this->assertEquals(null, $browser->attribute('@button', 'disabled')); // and so should the input $this->assertEquals(null, $browser->attribute('@input', 'readonly')); $this->assertEquals(null, $browser->attribute('@checkbox', 'disabled')); $browser->click('@button') ->assertDialogOpened('Are you sure?') ->acceptDialog() ->waitForText('Confirmed!') ; } public function test_custom_confirm_message() { Livewire::visit(new class extends Component { public $confirmed = false; public function someAction() { $this->confirmed = true; } public function render() { return <<<'HTML' <div> <button type="button" dusk="button" wire:click="someAction" wire:confirm="Foo bar">Confirm</button> @if ($confirmed) <span dusk="success">Confirmed!</span> @endif </div> HTML; } }) ->click('@button') ->assertDialogOpened('Foo bar') ; } public function test_can_prompt_a_user_for_a_match() { Livewire::visit(new class extends Component { public $confirmed = false; public function someAction() { $this->confirmed = true; } public function render() { return <<<'HTML' <div> <button type="button" dusk="button" wire:click="someAction" wire:confirm.prompt="Type foobar|foobar" >Confirm</button> @if ($confirmed) <span dusk="success">Confirmed!</span> @endif </div> HTML; } }) ->click('@button') ->assertDialogOpened('Type foobar') ->dismissDialog() ->pause(500) ->assertDontSee('Confirmed!') ->click('@button') ->assertDialogOpened('Type foobar') ->typeInDialog('foob') ->acceptDialog() ->pause(500) ->assertDontSee('Confirmed!') ->click('@button') ->assertDialogOpened('Type foobar') ->typeInDialog('foobar') ->acceptDialog() ->waitForText('Confirmed!') ; } public function test_can_prompt_a_user_for_a_match_when_used_with_submit_directive() { $browser = Livewire::visit(new class extends Component { public $confirmed = false; public function someAction() { $this->confirmed = true; } public function render() { return <<<'HTML' <div> <form wire:submit="someAction" wire:confirm.prompt="Type foobar|foobar"> <input type="text" dusk="input"> <input type="checkbox" dusk="checkbox"> <button type="submit" dusk="button">Confirm</button> @if ($confirmed) <span dusk="success">Confirmed!</span> @endif </form> </div> HTML; } }) ->click('@button') ->assertDialogOpened('Type foobar') ->dismissDialog() ->pause(500) ->assertDontSee('Confirmed!'); // ensure the form is still interactable $this->assertEquals(null, $browser->attribute('@button', 'disabled')); // and so should the input $this->assertEquals(null, $browser->attribute('@input', 'readonly')); $this->assertEquals(null, $browser->attribute('@checkbox', 'disabled')); $browser->click('@button') ->assertDialogOpened('Type foobar') ->typeInDialog('foob') ->acceptDialog() ->pause(500) ->assertDontSee('Confirmed!') ->click('@button') ->assertDialogOpened('Type foobar') ->typeInDialog('foobar') ->acceptDialog() ->waitForText('Confirmed!') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFormObjects/FormObjectSynth.php
src/Features/SupportFormObjects/FormObjectSynth.php
<?php namespace Livewire\Features\SupportFormObjects; use Livewire\Drawer\Utils; use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; use Livewire\Features\SupportAttributes\AttributeCollection; use function Livewire\wrap; class FormObjectSynth extends Synth { public static $key = 'form'; static function match($target) { return $target instanceof Form; } function dehydrate($target, $dehydrateChild) { $data = $target->toArray(); foreach ($data as $key => $child) { $data[$key] = $dehydrateChild($key, $child); } return [$data, ['class' => get_class($target)]]; } function hydrate($data, $meta, $hydrateChild) { // Verify class extends Form even though checksum protects this... if (! isset($meta['class']) || ! is_a($meta['class'], Form::class, true)) { throw new \Exception('Livewire: Invalid form object class.'); } $form = new $meta['class']($this->context->component, $this->path); $callBootMethod = static::bootFormObject($this->context->component, $form, $this->path); foreach ($data as $key => $child) { if ($child === null && Utils::propertyIsTypedAndUninitialized($form, $key)) { continue; } $form->$key = $hydrateChild($key, $child); } $callBootMethod(); return $form; } function set(&$target, $key, $value) { if ($value === null && Utils::propertyIsTyped($target, $key) && ! Utils::getProperty($target, $key)->getType()->allowsNull()) { unset($target->$key); } else { $target->$key = $value; } } public static function bootFormObject($component, $form, $path) { $component->mergeOutsideAttributes( AttributeCollection::fromComponent($component, $form, $path . '.') ); return function () use ($form) { wrap($form)->boot(); }; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFormObjects/HandlesFormObjects.php
src/Features/SupportFormObjects/HandlesFormObjects.php
<?php namespace Livewire\Features\SupportFormObjects; trait HandlesFormObjects { public function getFormObjects() { $forms = []; foreach ($this->all() as $key => $value) { if ($value instanceof Form) { $forms[] = $value; } } return $forms; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFormObjects/UnitTest.php
src/Features/SupportFormObjects/UnitTest.php
<?php namespace Livewire\Features\SupportFormObjects; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Stringable; use Livewire\Attributes\Validate; use Livewire\Component; use Livewire\Form; use Livewire\Livewire; use PHPUnit\Framework\Assert; use Sushi\Sushi; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { function test_can_use_a_form_object() { Livewire::test(new class extends TestComponent { public PostFormStub $form; }) ->assertSetStrict('form.title', '') ->assertSetStrict('form.content', '') ->set('form.title', 'Some Title') ->set('form.content', 'Some content...') ->assertSetStrict('form.title', 'Some Title') ->assertSetStrict('form.content', 'Some content...') ; } function test_can_reset_form_object_property() { Livewire::test(new class extends TestComponent { public PostFormStub $form; public function resetForm() { $this->reset('form.title', 'form.content'); } }) ->assertSetStrict('form.title', '') ->assertSetStrict('form.content', '') ->set('form.title', 'Some Title') ->set('form.content', 'Some content...') ->call('resetForm') ->assertSetStrict('form.title', '') ->assertSetStrict('form.content', '') ; } function test_can_reset_form_object_property_to_defaults() { Livewire::test(new class extends TestComponent { public PostFormStubWithDefaults $form; public function resetForm() { $this->reset('form.title', 'form.content'); } }) ->assertSetStrict('form.title', 'foo') ->assertSetStrict('form.content', 'bar') ->set('form.title', 'Some Title') ->set('form.content', 'Some content...') ->call('resetForm') ->assertSetStrict('form.title', 'foo') ->assertSetStrict('form.content', 'bar') ; } function test_can_reset_form_object_handle_dot_notation_with_asterisk_wildcard() { Livewire::test(new class extends TestComponent { public PostFormStubWithArrayDefaults $form; public function resetForm() { $this->reset([ 'form.content.*', ]); } }) ->assertSetStrict('form.content', [1 => true, 2 => false, 'foo' => ['bar' => 'baz']]) ->call('resetForm') ; } function test_can_reset_form_object_handle_nested_dot_notation() { Livewire::test(new class extends TestComponent { public PostFormStubWithArrayDefaults $form; public function resetForm() { $this->reset([ 'form.content.foo', ]); } }) ->assertSetStrict('form.content', [1 => true, 2 => false, 'foo' => ['bar' => 'baz']]) ->call('resetForm') ; } function test_set_form_object_with_typed_nullable_properties() { Livewire::test(new class extends Component { public PostFormWithTypedProperties $form; public function render() { return <<<'BLADE' <div> Title: "{{ $form->title }}" Content: "{{ $form->content }}" </div> BLADE; } }) ->assertSetStrict('form.title', null) ->assertSetStrict('form.content', null) ->assertSee('Title: ""', false) ->assertSee('Content: ""', false) ->set('form.title', 'Some Title') ->set('form.content', 'Some content...') ->assertSetStrict('form.title', 'Some Title') ->assertSetStrict('form.content', 'Some content...') ->assertSee('Title: "Some Title"', false) ->assertSee('Content: "Some content..."', false) ->set('form.title', null) ->set('form.content', null) ->assertSetStrict('form.title', null) ->assertSetStrict('form.content', null) ->assertSee('Title: ""', false) ->assertSee('Content: ""', false); ; } function test_form_object_update_lifecycle_hooks_are_called() { $component = Livewire::test( new class extends TestComponent { public LifecycleHooksForm $form; public function mount(array $expected = []) { $this->form->expected = $expected; } }, [ 'expected' => [ 'updating' => [[ 'foo' => 'bar', ]], 'updated' => [[ 'foo' => 'bar', ]], 'updatingFoo' => ['bar'], 'updatedFoo' => ['bar'], ], ] )->set('form.foo', 'bar'); $this->assertEquals([ 'updating' => true, 'updated' => true, 'updatingFoo' => true, 'updatedFoo' => true, 'updatingBar' => false, 'updatingBarBaz' => false, 'updatedBar' => false, 'updatedBarBaz' => false, ], $component->form->lifecycles); } function test_form_object_update_nested_lifecycle_hooks_are_called() { $component = Livewire::test( new class extends TestComponent { public LifecycleHooksForm $form; public function mount(array $expected = []) { $this->form->expected = $expected; } }, [ 'expected' => [ 'updating' => [ ['bar.foo' => 'baz',], ['bar.cocktail.soft' => 'Shirley Ginger'], ['bar.cocktail.soft' => 'Shirley Cumin'] ], 'updated' => [ ['bar.foo' => 'baz',], ['bar.cocktail.soft' => 'Shirley Ginger'], ['bar.cocktail.soft' => 'Shirley Cumin'] ], 'updatingBar' => [ ['foo' => [null, 'baz']], ['cocktail.soft' => [null, 'Shirley Ginger']], ['cocktail.soft' => ['Shirley Ginger', 'Shirley Cumin']] ], 'updatedBar' => [ ['foo' => 'baz'], ['cocktail.soft' => 'Shirley Ginger'], ['cocktail.soft' => 'Shirley Cumin'] ], ], ] ); $component->set('form.bar.foo', 'baz'); $component->set('form.bar.cocktail.soft', 'Shirley Ginger'); $component->set('form.bar.cocktail.soft', 'Shirley Cumin'); $this->assertEquals([ 'updating' => true, 'updated' => true, 'updatingFoo' => false, 'updatedFoo' => false, 'updatingBar' => true, 'updatingBarBaz' => false, 'updatedBar' => true, 'updatedBarBaz' => false, ], $component->form->lifecycles); } function test_can_validate_a_form_object() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form; function save() { $this->form->validate(); } }) ->assertSetStrict('form.title', '') ->assertSetStrict('form.content', '') ->assertHasNoErrors() ->call('save') ->assertHasErrors('form.title') ->assertHasErrors('form.content') ; } function test_can_validate_a_form_with_the_general_validate_function() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form; function save() { $this->validate(); } }) ->call('save') ->tap(function ($component) { $this->assertCount(1, $component->errors()->get('form.title')); $this->assertCount(1, $component->errors()->get('form.content')); }) ; } function test_can_validate_a_specific_rule_has_errors_in_a_form_object() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form; function save() { $this->validate(); } }) ->assertSetStrict('form.title', '') ->assertHasNoErrors() ->call('save') ->assertHasErrors(['form.title' => 'required']) ; } function test_can_validate_a_form_object_with_validate_only() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form; function save() { $this->form->validateOnly('title'); } }) ->assertHasNoErrors() ->call('save') ->assertHasErrors('form.title') ->assertHasNoErrors('form.content') ; } function test_can_validate_a_specific_rule_for_form_object_with_validate_only() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form; function save() { $this->form->validateOnly('title'); } }) ->assertHasNoErrors() ->call('save') ->assertHasErrors(['form.title' => 'required']); ; } function test_can_validate_a_specific_rule_has_errors_on_update_in_a_form_object() { Livewire::test(new class extends TestComponent { public PostFormValidateOnUpdateStub $form; }) ->assertHasNoErrors() ->set('form.title', 'foo') ->assertHasErrors(['form.title' => 'min']) ; } function test_can_validate_a_form_object_with_root_component_validate_only() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form; function save() { $this->validateOnly('form.title'); } }) ->assertHasNoErrors() ->call('save') ->assertHasErrors('form.title') ->assertHasNoErrors('form.content') ; } function test_can_validate_a_form_object_using_rule_attributes() { Livewire::test(new class extends TestComponent { public PostFormRuleAttributeStub $form; function save() { $this->form->validate(); } }) ->assertSetStrict('form.title', '') ->assertSetStrict('form.content', '') ->assertHasNoErrors() ->call('save') ->assertHasErrors('form.title') ->assertHasErrors('form.content') ->set('form.title', 'title...') ->set('form.content', 'content...') ->assertHasNoErrors() ->call('save') ; } function test_multiple_forms_show_all_errors() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form1; public PostFormValidateStub $form2; function save() { $this->validate(); } function render() { return '<div>{{ $errors }}</div>'; } }) ->assertHasNoErrors() ->call('save') ->assertHasErrors('form1.title') ->assertHasErrors('form1.content') ->assertHasErrors('form2.title') ->assertHasErrors('form2.content') ->assertSee('The title field is required') ->assertSee('The content field is required') ->set('form1.title', 'Valid Title 1') ->set('form1.content', 'Valid Content 1') ->set('form2.title', 'Valid Title 2') ->set('form2.content', 'Valid Content 2') ->call('save') ->assertHasNoErrors(); } function test_can_validate_a_form_object_using_rule_attribute_with_custom_name() { Livewire::test(new class extends TestComponent { public PostFormRuleAttributeWithCustomNameStub $form; function save() { $this->form->validate(); } }) ->assertSetStrict('form.name', '') ->assertHasNoErrors() ->call('save') ->assertHasErrors('form.name') ->set('form.name', 'Mfawa...') ->assertHasNoErrors() ->call('save') ; } public function test_validation_errors_persist_across_validation_errors() { $component = Livewire::test(new class extends Component { public FormWithLiveValidation $form; function save() { $this->form->validate(); } function render() { return '<div>{{ $errors }}</div>'; } }); $component->assertDontSee('The title field is required') ->assertDontSee('The content field is required') ->set('form.title', '') ->assertSee('The title field is required') ->assertDontSee('The content field is required') ->set('form.content', '') ->assertSee('The title field is required') ->assertSee('The content field is required'); } function test_can_reset_property() { Livewire::test(new class extends TestComponent { public PostFormStub $form; function save() { $this->form->reset('title'); } }) ->set('form.title', 'Some title...') ->set('form.content', 'Some content...') ->assertSetStrict('form.title', 'Some title...') ->assertSetStrict('form.content', 'Some content...') ->call('save') ->assertHasNoErrors() ->assertSetStrict('form.title', '') ->assertSetStrict('form.content', 'Some content...') ; } function test_can_reset_all_properties() { Livewire::test(new class extends TestComponent { public PostFormStub $form; function save() { $this->form->reset(); } }) ->set('form.title', 'Some title...') ->set('form.content', 'Some content...') ->assertSetStrict('form.title', 'Some title...') ->assertSetStrict('form.content', 'Some content...') ->call('save') ->assertHasNoErrors() ->assertSetStrict('form.title', '') ->assertSetStrict('form.content', '') ; } function test_all_properties_are_available_in_rules_method() { Livewire::test(new class extends TestComponent { public PostFormWithRulesStub $form; public function mount() { $this->form->setPost(42); } function save() { $this->form->validate(); } }) ->assertSetStrict('form.post', 42) ->call('save') ->assertSetStrict('form.post', 42) ->assertHasErrors() ; } function test_can_get_only_specific_properties() { $component = new class extends Component {}; $form = new PostFormStub($component, 'foobar'); $this->assertEquals( ['title' => ''], $form->only('title') ); $this->assertEquals( ['content' => ''], $form->except(['title']) ); $this->assertEquals( ['title' => '', 'content' => ''], $form->only('title', 'content') ); } function test_can_get_properties_except() { $component = new class extends Component {}; $form = new PostFormStub($component, 'foobar'); $this->assertEquals( ['content' => ''], $form->except('title') ); $this->assertEquals( ['content' => ''], $form->except(['title']) ); $this->assertEquals( [], $form->except('title', 'content') ); } function test_validation_can_show_a_form_object_dynamic_validation_attributes() { Livewire::test(new class extends Component { public PostFormDynamicValidationAttributesStub $withDynamicValidationAttributesForm; function save() { $this->withDynamicValidationAttributesForm->validate(); } public function render() { return <<<'HTML' <div> {{ $errors }} </div> HTML; } }) ->set('withDynamicValidationAttributesForm.title', '') ->set('withDynamicValidationAttributesForm.content', '') ->call('save') ->assertSee('Custom Title') ->assertSee('Custom Content') ; } function test_multiple_form_objects_in_component_not_interfering_between() { Livewire::test(new class extends Component { public PostFormDynamicValidationAttributesStub $firstForm; public PostFormDynamicMessagesAndAttributesStub $secondForm; function saveFirstForm() { $this->firstForm->validate(); } function saveSecondForm() { $this->secondForm->validate(); } public function render() { return <<<'HTML' <div>{{ $errors }}</div> HTML; } }) ->set('firstForm.title', '') ->set('firstForm.content', '') ->call('saveFirstForm') ->assertSee('Custom Title') ->assertSee('The Custom Title field is required') ->assertSee('Custom Content') ->assertSee('The Custom Content field is required') ->assertDontSee('Name') ->assertDontSee('Body') ->set('secondForm.title', '') ->set('secondForm.content', '') ->call('saveSecondForm') ->assertSee('Name') ->assertSee('Name is required to fill') ->assertSee('Body') ->assertSee('Body is must to fill') ->assertDontSee('Custom Title') ->assertDontSee('Custom Content') ; } function test_validation_showing_a_form_object_dynamic_messages() { Livewire::test(new class extends Component { public PostFormDynamicMessagesStub $form; function save() { $this->form->validate(); } public function render() { return <<<'HTML' <div>{{ $errors }}</div> HTML; } }) ->set('form.title', '') ->set('form.content', 'Livewire') ->call('save') ->assertSee('title is must to fill') ->assertSee('content need at least 10 letters') ; } public function test_can_fill_a_form_object_from_model() { Livewire::test(new class extends TestComponent { public PostForFormObjectTesting $post; public PostFormStub $form; public function mount() { $this->post = PostForFormObjectTesting::first(); } public function fillForm() { $this->form->fill($this->post); } }) ->assertSetStrict('form.title', '') ->assertSetStrict('form.content', '') ->call('fillForm') ->assertSetStrict('form.title', 'A Title') ->assertSetStrict('form.content', 'Some content') ; } public function test_can_fill_a_form_object_from_array() { Livewire::test(new class extends TestComponent { public PostFormStub $form; public function fillForm() { $this->form->fill([ 'title' => 'Title from array', 'content' => 'Content from array', ]); } }) ->assertSetStrict('form.title', '') ->assertSetStrict('form.content', '') ->call('fillForm') ->assertSetStrict('form.title', 'Title from array') ->assertSetStrict('form.content', 'Content from array') ; } function test_form_object_validation_runs_alongside_component_validation() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form; #[Validate('required')] public $username = ''; function save() { $this->validate(); } }) ->assertHasNoErrors() ->call('save') ->assertHasErrors('form.title') ->assertHasErrors('form.content') ->assertHasErrors('username') ; } function test_form_object_validation_wont_run_if_rules_are_passed_into_validate() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form; public $username = ''; function save() { $this->validate(['username' => 'required']); } }) ->assertHasNoErrors() ->call('save') ->assertHasNoErrors('form.title') ->assertHasNoErrors('form.content') ->assertHasErrors('username') ; } function test_allows_form_object_without_rules_without_throwing_an_error() { Livewire::test(new class extends TestComponent { public PostFormWithoutRules $form; public $username = ''; public function rules() { return [ 'username' => 'required', ]; } function save() { $this->validate(); } }) ->assertHasNoErrors() ->call('save') ->assertHasErrors('username') ; } function test_allows_form_object_without_rules_but_can_still_validate_it_with_its_own_rules() { Livewire::test(new class extends TestComponent { public PostFormWithoutRules $form; public $username = ''; public function rules() { return [ 'username' => 'required', 'form.title' => 'required', ]; } function save() { $this->validate(); } }) ->assertHasNoErrors() ->call('save') ->assertHasErrors('username') ->assertHasErrors('form.title') ; } function test_form_object_without_rules_can_still_be_validated_and_return_proper_data() { Livewire::test(new class extends TestComponent { public PostFormWithoutRules $form; public $username = ''; public function rules() { return [ 'username' => 'required', 'form.title' => 'required', ]; } function save() { $data = $this->validate(); \PHPUnit\Framework\Assert::assertEquals('foo', data_get($data, 'username')); \PHPUnit\Framework\Assert::assertEquals('bar', data_get($data, 'form.title')); \PHPUnit\Framework\Assert::assertEquals('not-found', data_get($data, 'form.content', 'not-found')); } }) ->assertHasNoErrors() ->set('username', 'foo') ->set('form.title', 'bar') ->call('save') ->assertHasNoErrors('username') ; } function test_resetting_validation_errors_resets_form_objects_as_well() { Livewire::test(new class extends TestComponent { public PostFormValidateStub $form; #[Validate('required')] public $username = ''; function save() { $this->validate(); } function resetVal() { $this->resetValidation(); } }) ->assertHasNoErrors() ->call('save') ->assertHasErrors('form.title') ->assertHasErrors('form.content') ->call('resetVal') ->assertHasNoErrors('form.title') ->assertHasNoErrors('form.content') ; } function test_can_intercept_form_object_validator_instance() { Livewire::test(new class extends TestComponent { public PostFormValidateWithInterceptStub $form; function save() { $this->validate(); } function resetVal() { $this->resetValidation(); } }) ->assertHasNoErrors() ->set('form.title', '"title with quotes"') ->set('form.content', 'content') ->call('save') ->assertHasErrors('form.title') ->assertHasNoErrors('form.content') ; } function test_can_reset_and_return_property_with_pull_method() { Livewire::test(new class extends TestComponent { public ResetPropertiesForm $form; public $pullResult; function test(...$args) { $this->pullResult = $this->form->proxyPull(...$args); } }) ->assertSet('form.foo', 'bar') ->assertSet('form.bob', 'lob') ->set('form.foo', 'baz') ->assertSet('form.foo', 'baz') ->call('test', 'foo') ->assertSet('form.foo', 'bar') ->assertSet('pullResult', 'baz'); } function test_can_pull_all_properties() { $component = Livewire::test(new class extends TestComponent { public ResetPropertiesForm $form; public $pullResult; function test(...$args) { $this->pullResult = $this->form->proxyPull(...$args); } }) ->assertSet('form.foo', 'bar') ->set('form.foo', 'baz') ->assertSet('form.foo', 'baz') ->assertSet('pullResult', null) ->call('test'); $this->assertEquals('baz', $component->pullResult['foo']); $this->assertEquals('lob', $component->pullResult['bob']); } function test_can_pull_some_properties() { Livewire::test(new class extends TestComponent { public ResetPropertiesForm $form; function formResetExcept(...$args) { $this->form->resetExcept(...$args); } }) ->assertSet('form.foo', 'bar') ->set('form.foo', 'baz') ->assertSet('form.foo', 'baz') ->assertSet('form.bob', 'lob') ->set('form.bob', 'loc') ->assertSet('form.bob', 'loc') ->call('formResetExcept', ['foo']) ->assertSet('form.foo', 'baz') ->assertSet('form.bob', 'lob') ->set('form.foo', 'bar2') ->set('form.bob', 'lob2') ->call('formResetExcept', ['foo', 'bob']) ->assertSet('form.foo', 'bar2') ->assertSet('form.bob', 'lob2'); } function test_form_object_synth_rejects_non_form_classes() { $this->expectException(\Exception::class); $this->expectExceptionMessage('Invalid form object class'); $component = Livewire::test(new class extends TestComponent { public PostFormStub $form; }); // Create a synth instance and try to hydrate with a non-Form class $synth = new FormObjectSynth( new \Livewire\Mechanisms\HandleComponents\ComponentContext($component->instance()), 'form' ); // This should throw because stdClass doesn't extend Form $synth->hydrate(['title' => 'test'], ['class' => \stdClass::class], fn($k, $v) => $v); } } class PostFormStub extends Form { public $title = ''; public $content = ''; } class PostFormStubWithDefaults extends Form { public $title = 'foo'; public $content = 'bar'; } class PostFormStubWithArrayDefaults extends Form { public $title = 'foo'; public $content = [ 1 => true, 2 => false, 'foo' => ['bar' => 'baz'], ]; } class PostFormWithTypedProperties extends Form { public ?string $title = null; public ?string $content = null; } class PostFormWithRulesStub extends Form { public ?int $post = null; public $title = ''; public $content = ''; public function setPost($model) { $this->post = $model; } public function rules() { Assert::assertEquals(42, $this->post, 'post should be available to run more complex rules'); return [ 'title' => 'required', 'content' => 'required', ]; } } class PostFormValidateStub extends Form { public $title = ''; public $content = ''; protected $rules = [ 'title' => 'required', 'content' => 'required', ]; } class PostFormValidateOnUpdateStub extends Form { #[Validate] public $title = ''; protected $rules = [ 'title' => 'min:5', ]; } class PostFormWithoutRules extends Form { public $title = ''; public $content = ''; } class PostFormValidateWithInterceptStub extends Form { public $title = ''; public $content = ''; protected $rules = [ 'title' => 'required', 'content' => 'required', ]; public function boot() { $this->withValidator(function ($validator) { $validator->after(function ($validator) { if (str($this->title)->startsWith('"')) { $validator->errors()->add('title', 'Titles cannot start with quotations'); } }); }); } } class PostFormRuleAttributeStub extends Form { #[Validate('required')] public $title = ''; #[Validate('required')] public $content = ''; } class PostFormRuleAttributeWithCustomNameStub extends Form { #[Validate( rule: [ 'required', 'min:3', 'max:255' ], as: 'my name' )] public $name = ''; } class PostFormDynamicValidationAttributesStub extends Form { #[Validate('required')] public $title = ''; #[Validate('required')] public $content = ''; public function validationAttributes() { return [ 'title' => 'Custom Title', 'content' => 'Custom Content', ]; } } class PostFormDynamicMessagesStub extends Form { #[Validate('required')] public $title = ''; #[Validate(['required', 'min:10'])] public $content = ''; public function messages() { return [ 'title.required' => ':attribute is must to fill', 'content.min' => ':attribute need at least 10 letters', ]; } } class PostFormDynamicMessagesAndAttributesStub extends Form { #[Validate('required')] public $title = ''; #[Validate('required')] public $content = ''; public function validationAttributes() { return [ 'title' => 'Name', 'content' => 'Body', ]; } public function messages() { return [ 'title' => ':attribute is required to fill', 'content' => ':attribute is must to fill', ]; } } class PostForFormObjectTesting extends Model { use Sushi; protected $rows = [ [ 'title' => 'A Title', 'content' => 'Some content', ], ]; } class FormWithLiveValidation extends Form { #[Validate] public $title = 'title'; #[Validate] public $content = 'content'; public function rules() { return [ 'title' => [ 'required', ], 'content' => [ 'required', ], ]; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
true
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFormObjects/SupportFormObjects.php
src/Features/SupportFormObjects/SupportFormObjects.php
<?php namespace Livewire\Features\SupportFormObjects; use ReflectionClass; use Livewire\ComponentHook; use ReflectionNamedType; use function Livewire\wrap; class SupportFormObjects extends ComponentHook { public static function provide() { app('livewire')->propertySynthesizer( FormObjectSynth::class ); } function boot() { $this->initializeFormObjects(); } public function update($formName, $fullPath, $newValue) { $form = $this->getProperty($formName); if (! $form instanceof Form) { return; } if (! str($fullPath)->contains('.')) { return; } $path = str($fullPath)->after('.')->__toString(); $name = str($path); $propertyName = $name->studly()->before('.'); $keyAfterFirstDot = $name->contains('.') ? $name->after('.')->__toString() : null; $keyAfterLastDot = $name->contains('.') ? $name->afterLast('.')->__toString() : null; $beforeMethod = 'updating'.$propertyName; $afterMethod = 'updated'.$propertyName; $beforeNestedMethod = $name->contains('.') ? 'updating'.$name->replace('.', '_')->studly() : false; $afterNestedMethod = $name->contains('.') ? 'updated'.$name->replace('.', '_')->studly() : false; $this->callFormHook($form, 'updating', [$path, $newValue]); $this->callFormHook($form, $beforeMethod, [$newValue, $keyAfterFirstDot]); $this->callFormHook($form, $beforeNestedMethod, [$newValue, $keyAfterLastDot]); return function () use ($form, $path, $afterMethod, $afterNestedMethod, $keyAfterFirstDot, $keyAfterLastDot, $newValue) { $this->callFormHook($form, 'updated', [$path, $newValue]); $this->callFormHook($form, $afterMethod, [$newValue, $keyAfterFirstDot]); $this->callFormHook($form, $afterNestedMethod, [$newValue, $keyAfterLastDot]); }; } protected function initializeFormObjects() { foreach ((new ReflectionClass($this->component))->getProperties() as $property) { // Public properties only... if ($property->isPublic() !== true) continue; // Uninitialized properties only... if ($property->isInitialized($this->component)) continue; $type = $property->getType(); if (! $type instanceof ReflectionNamedType) continue; $typeName = $type->getName(); // "Form" object property types only... if (! is_subclass_of($typeName, Form::class)) continue; $form = new $typeName( $this->component, $name = $property->getName() ); $callBootMethod = FormObjectSynth::bootFormObject($this->component, $form, $name); $property->setValue($this->component, $form); $callBootMethod(); } } protected function callFormHook($form, $name, $params = []) { if (method_exists($form, $name)) { wrap($form)->$name(...$params); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportFormObjects/Form.php
src/Features/SupportFormObjects/Form.php
<?php namespace Livewire\Features\SupportFormObjects; use Livewire\Features\SupportValidation\HandlesValidation; use Illuminate\Validation\ValidationException; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\MessageBag; use function Livewire\invade; use Illuminate\Support\Arr; use Livewire\Drawer\Utils; use Livewire\Component; class Form implements Arrayable { use HandlesValidation { validate as parentValidate; validateOnly as parentValidateOnly; } function __construct( protected Component $component, protected $propertyName ) {} public function getComponent() { return $this->component; } public function getPropertyName() { return $this->propertyName; } public function validate($rules = null, $messages = [], $attributes = []) { try { return $this->parentValidate($rules, $messages, $attributes); } catch (ValidationException $e) { invade($e->validator)->messages = $this->prefixErrorBag(invade($e->validator)->messages); invade($e->validator)->failedRules = $this->prefixArray(invade($e->validator)->failedRules); throw $e; } } public function validateOnly($field, $rules = null, $messages = [], $attributes = [], $dataOverrides = []) { try { return $this->parentValidateOnly($field, $rules, $messages, $attributes, $dataOverrides); } catch (ValidationException $e) { invade($e->validator)->messages = $this->prefixErrorBag(invade($e->validator)->messages)->merge( $this->getComponent()->getErrorBag() ); invade($e->validator)->failedRules = $this->prefixArray(invade($e->validator)->failedRules); throw $e; } } protected function runSubValidators() { // This form object IS the sub-validator. // Let's skip it... } protected function prefixErrorBag($bag) { $raw = $bag->toArray(); $raw = Arr::prependKeysWith($raw, $this->getPropertyName().'.'); return new MessageBag($raw); } protected function prefixArray($array) { return Arr::prependKeysWith($array, $this->getPropertyName().'.'); } public function addError($key, $message) { $this->component->addError($this->propertyName . '.' . $key, $message); } public function resetErrorBag($field = null) { $fields = (array) $field; foreach ($fields as $idx => $field) { $fields[$idx] = $this->propertyName . '.' . $field; } $this->getComponent()->resetErrorBag($fields); } public function all() { return $this->toArray(); } public function only($properties) { $results = []; foreach (is_array($properties) ? $properties : func_get_args() as $property) { $results[$property] = $this->hasProperty($property) ? $this->getPropertyValue($property) : null; } return $results; } public function except($properties) { $properties = is_array($properties) ? $properties : func_get_args(); return array_diff_key($this->all(), array_flip($properties)); } public function hasProperty($prop) { return property_exists($this, Utils::beforeFirstDot($prop)); } public function getPropertyValue($name) { $value = $this->{Utils::beforeFirstDot($name)}; if (Utils::containsDots($name)) { return data_get($value, Utils::afterFirstDot($name)); } return $value; } public function fill($values) { $publicProperties = array_keys($this->all()); if ($values instanceof Model) { $values = $values->toArray(); } foreach ($values as $key => $value) { if (in_array(Utils::beforeFirstDot($key), $publicProperties)) { data_set($this, $key, $value); } } } public function reset(...$properties) { $properties = count($properties) && is_array($properties[0]) ? $properties[0] : $properties; if (empty($properties)) $properties = array_keys($this->all()); $freshInstance = new static($this->getComponent(), $this->getPropertyName()); foreach ($properties as $property) { data_set($this, $property, data_get($freshInstance, $property)); } } public function resetExcept(...$properties) { if (count($properties) && is_array($properties[0])) { $properties = $properties[0]; } $keysToReset = array_diff(array_keys($this->all()), $properties); if($keysToReset === []) { return; } $this->reset($keysToReset); } public function pull($properties = null) { $wantsASingleValue = is_string($properties); $properties = is_array($properties) ? $properties : func_get_args(); $beforeReset = match (true) { empty($properties) => $this->all(), $wantsASingleValue => $this->getPropertyValue($properties[0]), default => $this->only($properties), }; $this->reset($properties); return $beforeReset; } public function toArray() { return Utils::getPublicProperties($this); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireRef/BrowserTest.php
src/Features/SupportWireRef/BrowserTest.php
<?php namespace Livewire\Features\SupportWireRef; use Livewire\Attributes\On; use Livewire\Component; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_can_stream_to_a_ref() { Livewire::visit([ new class extends Component { public $streamed = false; public function send() { $this->stream('testing...', ref: 'target'); $this->streamed = true; } public function render() { return <<<'HTML' <div> <div wire:ref="target" dusk="target">{{ $streamed ? 'testing...' : '' }}</div> <button wire:click="send" dusk="send-button">Send</button> </div> HTML; } }, ]) ->waitForLivewireToLoad() ->waitForLivewire()->click('@send-button') // Wait for children to update... ->pause(50) ->assertConsoleLogHasNoErrors() ->assertSeeIn('@target', 'testing...'); } public function test_can_dispatch_an_event_to_a_ref() { Livewire::visit([ new class extends Component { public function send() { $this->dispatch('test', ref: 'child2'); } public function render() { return <<<'HTML' <div> <livewire:child wire:ref="child1" name="child1" /> <livewire:child wire:ref="child2" name="child2" /> <button wire:click="send" dusk="send-button">Send</button> </div> HTML; } }, 'child' => new class extends Component { public $received = false; public $name; #[On('test')] public function test() { $this->received = true; } public function render() { return <<<'HTML' <div> {{ $name }} <p dusk="{{ $name }}-received-output">{{ $received ? 'true' : 'false' }}</p> </div> HTML; } } ]) ->waitForLivewireToLoad() ->waitForLivewire()->click('@send-button') // Wait for children to update... ->pause(50) ->assertConsoleLogHasNoErrors() ->assertSeeIn('@child1-received-output', 'false') ->assertSeeIn('@child2-received-output', 'true'); } public function test_a_dispatch_to_a_non_existent_ref_logs_an_error_in_the_console() { Livewire::visit([ new class extends Component { public function send() { $this->dispatch('test', ref: 'child9999'); } public function render() { return <<<'HTML' <div> <livewire:child wire:ref="child1" name="child1" /> <livewire:child wire:ref="child2" name="child2" /> <button wire:click="send" dusk="send-button">Send</button> </div> HTML; } }, 'child' => new class extends Component { public $received = false; public $name; #[On('test')] public function test() { $this->received = true; } public function render() { return <<<'HTML' <div> {{ $name }} <p dusk="{{ $name }}-received-output">{{ $received ? 'true' : 'false' }}</p> </div> HTML; } } ]) ->waitForLivewireToLoad() ->waitForLivewire()->click('@send-button') // Wait for children to update... ->pause(50) ->assertConsoleLogHasErrors() ->assertSeeIn('@child1-received-output', 'false') ->assertSeeIn('@child2-received-output', 'false'); } public function test_can_use_dispatch_ref_magic_to_dispatch_an_event_to_a_ref() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <livewire:child wire:ref="child1" name="child1" /> <livewire:child wire:ref="child2" name="child2" /> <button wire:click="$refs['child1'].$wire.dispatchSelf('test')" dusk="send-button">Send</button> </div> HTML; } }, 'child' => new class extends Component { public $received = false; public $name; #[On('test')] public function test() { $this->received = true; } public function render() { return <<<'HTML' <div> {{ $name }} <p dusk="{{ $name }}-received-output">{{ $received ? 'true' : 'false' }}</p> </div> HTML; } } ]) ->waitForLivewireToLoad() ->waitForLivewire()->click('@send-button') // Wait for children to update... ->pause(50) ->assertConsoleLogHasNoErrors() ->assertSeeIn('@child1-received-output', 'true') ->assertSeeIn('@child2-received-output', 'false'); } public function test_use_refs_magic_to_get_nested_component() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <livewire:child wire:ref="child" /> <p wire:text="$refs.child.textContent" dusk="child-ref-output"></p> </div> HTML; } }, 'child' => new class extends Component { public function render() { return <<<'HTML' <div> Child </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertConsoleLogHasNoErrors() ->assertSeeIn('@child-ref-output', 'Child'); } public function test_refs_magic_logs_an_error_in_the_console_if_the_ref_is_not_a_component_but_is_used_as_one() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <div wire:ref="child"></div> <p wire:text="$refs.child.save()" dusk="child-ref-output"></p> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertConsoleLogHasErrors() ; } public function test_refs_magic_logs_an_error_in_the_console_if_the_ref_is_not_found() { Livewire::visit([ new class extends Component { public function render() { return <<<'HTML' <div> <p wire:text="$refs.child?.textContent" dusk="child-ref-output"></p> </div> HTML; } } ]) ->waitForLivewireToLoad() ->assertConsoleLogHasErrors() ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Features/SupportWireRef/SupportWireRef.php
src/Features/SupportWireRef/SupportWireRef.php
<?php namespace Livewire\Features\SupportWireRef; use Livewire\ComponentHook; use Livewire\Drawer\Utils; class SupportWireRef extends ComponentHook { public function mount($params) { if (isset($params['wire:ref'])) { $this->storeSet('ref', $params['wire:ref']); } } public function dehydrate($context) { if ($this->storeHas('ref')) { $context->addMemo('ref', $this->storeGet('ref')); } } public function hydrate($memo) { $ref = $memo['ref'] ?? null; if (! $ref) return; $this->storeSet('ref', $ref); } public function render($view, $data) { return function ($html, $replaceHtml) { $ref = $this->storeGet('ref'); if (! $ref) return; $replaceHtml(Utils::insertAttributesIntoHtmlRoot($html, [ 'wire:ref' => $ref, ])); }; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false