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/Compiler/Fixtures/sfc-component.blade.php
src/Compiler/Fixtures/sfc-component.blade.php
<?php use Livewire\Component; new class extends Component { public $message = 'Hello World'; }; ?> <div>{{ $message }}</div> <script> console.log('Hello from script'); </script>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Fixtures/sfc-component-without-trailing-semicolon.blade.php
src/Compiler/Fixtures/sfc-component-without-trailing-semicolon.blade.php
<?php use Livewire\Component; new class extends Component { public $message = 'Hello World'; } ?> <div>{{ $message }}</div> <script> console.log('Hello from script'); </script>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Fixtures/sfc-component-with-blade-script.blade.php
src/Compiler/Fixtures/sfc-component-with-blade-script.blade.php
<?php use Livewire\Component; new class extends Component { public $message = 'Hello World'; }; ?> <div>{{ $message }}</div> @script <script> console.log('Hello from script'); </script> @endscript
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Fixtures/sfc-component-with-placeholder-in-island.blade.php
src/Compiler/Fixtures/sfc-component-with-placeholder-in-island.blade.php
<?php use Livewire\Component; new class extends Component { public $message = 'Hello World'; }; ?> <div> @island(lazy: true) @placeholder <div>Loading...</div> @endplaceholder @endisland {{ $message }} </div> <script> console.log('Hello from script'); </script>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Fixtures/test.php
src/Compiler/Fixtures/test.php
<?php use Livewire\Component; return new class extends Component { public $message = 'Hello World'; };
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Fixtures/sfc-component-with-placeholder.blade.php
src/Compiler/Fixtures/sfc-component-with-placeholder.blade.php
<?php use Livewire\Component; new class extends Component { public $message = 'Hello World'; }; ?> @placeholder <div>Loading...</div> @endplaceholder <div>{{ $message }}</div> <script> console.log('Hello from script'); </script>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Fixtures/mfc-component/mfc-component.blade.php
src/Compiler/Fixtures/mfc-component/mfc-component.blade.php
<div>{{ $message }}</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Fixtures/mfc-component/mfc-component.php
src/Compiler/Fixtures/mfc-component/mfc-component.php
<?php use Livewire\Component; new class extends Component { public $message = 'Hello World'; };
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Parser/SingleFileParser.php
src/Compiler/Parser/SingleFileParser.php
<?php namespace Livewire\Compiler\Parser; use Livewire\Compiler\Compiler; class SingleFileParser extends Parser { public function __construct( public string $path, public string $contents, public ?string $scriptPortion, public string $classPortion, public ?string $placeholderPortion, public string $viewPortion, ) {} public static function parse(Compiler $compiler, string $path): self { $contents = file_get_contents($path); $mutableContents = $compiler->prepareViewForCompilation($contents, $path); $scriptPortion = static::extractScriptPortion($mutableContents); $classPortion = static::extractClassPortion($mutableContents); $placeholderPortion = static::extractPlaceholderPortion($mutableContents); $viewPortion = trim($mutableContents); return new self( $path, $contents, $scriptPortion, $classPortion, $placeholderPortion, $viewPortion, ); } public static function extractClassPortion(string &$contents): string { $pattern = '/<\?php\s*.*?\s*\?>/s'; $classPortion = static::extractPattern($pattern, $contents); if ($classPortion === false) { throw new \Exception('Class contents not found'); } return $classPortion; } public static function extractScriptPortion(string &$contents): ?string { // Get the view portion (everything after the PHP class) $viewContents = static::getViewPortion($contents); // Remove @script/@endscript blocks (let Livewire handle these normally) $viewContents = preg_replace('/@script\s*.*?@endscript/s', '', $viewContents); // Remove @assets/@endassets blocks (let Livewire handle these normally) $viewContents = preg_replace('/@assets\s*.*?@endassets/s', '', $viewContents); // Find script tags that are at the start of a line $pattern = '/(?:^|\n)\s*(<script\b[^>]*>.*?<\/script>)/s'; preg_match_all($pattern, $viewContents, $matches); if (empty($matches[1])) { return null; } // Take the last script tag (most likely to be at root level) $scriptTag = end($matches[1]); // Remove it from the original contents $contents = str_replace($scriptTag, '', $contents); return $scriptTag; } private static function getViewPortion(string $contents): string { // Remove the PHP class portion to get just the view $classPattern = '/<\?php\s*.*?\s*\?>/s'; $viewContents = preg_replace($classPattern, '', $contents); return trim($viewContents); } protected static function extractPattern(string $pattern, string &$contents): string | false { if (preg_match($pattern, $contents, $matches)) { $match = $matches[0]; $contents = str_replace($match, '', $contents); return $match; } return false; } public function generateClassContents(?string $viewFileName = null, ?string $placeholderFileName = null, ?string $scriptFileName = null): string { $classContents = trim($this->classPortion); $classContents = $this->stripTrailingPhpTag($classContents); $classContents = $this->ensureAnonymousClassHasReturn($classContents); $classContents = $this->ensureAnonymousClassHasTrailingSemicolon($classContents); if ($viewFileName) { $classContents = $this->injectViewMethod($classContents, $viewFileName); } if ($placeholderFileName) { $classContents = $this->injectPlaceholderMethod($classContents, $placeholderFileName); } if ($scriptFileName) { $classContents = $this->injectScriptMethod($classContents, $scriptFileName); } return $classContents; } /** * Generate the class contents for a multi-file component (this is used for the upgrade command). */ public function generateClassContentsForMultiFile(): string { $classContents = trim($this->classPortion); $classContents = $this->stripTrailingPhpTag($classContents); $classContents = $this->ensureAnonymousClassHasTrailingSemicolon($classContents); return $classContents; } public function generateViewContents(): string { $viewContents = trim($this->viewPortion); $viewContents = $this->injectUseStatementsFromClassPortion($viewContents, $this->classPortion); return $viewContents; } public function generateViewContentsForMultiFile(): string { $viewContents = trim($this->viewPortion); if ($this->placeholderPortion) { $viewContents = $this->injectPlaceholderDirective($viewContents, $this->placeholderPortion); } return $viewContents; } protected function injectPlaceholderDirective(string $viewContents, string $placeholderPortion): string { return '@placeholder' . $placeholderPortion . '@endplaceholder' . "\n\n" . $viewContents; } public function generateScriptContents(): ?string { if ($this->scriptPortion === null) return null; $scriptContents = ''; $pattern = '/<script\b([^>]*)>(.*?)<\/script>/s'; if (preg_match($pattern, $this->scriptPortion, $matches)) { $scriptContents = trim($matches[2]); } // Hoist imports to the top $imports = []; $scriptContents = preg_replace_callback( '/^import\s+.+?;?\s*$/m', function ($match) use (&$imports) { $imports[] = trim($match[0]); return ''; // Remove from original position }, $scriptContents ); // Clean up any extra whitespace left by removed imports $scriptContents = trim($scriptContents); // Build the final script with hoisted imports and export function $hoistedImports = empty($imports) ? '' : implode("\n", $imports) . "\n"; return <<<JS {$hoistedImports} export function run(\$wire, \$js) { {$scriptContents} } JS; } public function generateScriptContentsForMultiFile(): ?string { if ($this->scriptPortion === null) return null; $scriptContents = ''; $pattern = '/<script\b([^>]*)>(.*?)<\/script>/s'; if (preg_match($pattern, $this->scriptPortion, $matches)) { $scriptContents = $matches[2]; } return $this->cleanupJavaScriptIndentation($scriptContents); } protected function cleanupJavaScriptIndentation(string $source): string { $lines = explode("\n", $source); if (empty($lines)) { return $source; } // Find the minimum indentation level (excluding empty lines) $minIndentation = null; foreach ($lines as $line) { if (trim($line) === '') { continue; // Skip empty lines } // Count leading whitespace $indentation = strlen($line) - strlen(ltrim($line)); if ($minIndentation === null || $indentation < $minIndentation) { $minIndentation = $indentation; } } // If no indentation found, return as-is if ($minIndentation === null || $minIndentation === 0) { return $source; } // Remove the minimum indentation from all lines $cleanedLines = []; foreach ($lines as $line) { if (trim($line) === '') { $cleanedLines[] = $line; // Keep empty lines as-is } else { $cleanedLines[] = substr($line, $minIndentation); } } return implode("\n", $cleanedLines); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Parser/MultiFileParser.php
src/Compiler/Parser/MultiFileParser.php
<?php namespace Livewire\Compiler\Parser; use Livewire\Compiler\Compiler; class MultiFileParser extends Parser { public function __construct( public string $path, public ?string $scriptPortion, public string $classPortion, public string $viewPortion, public ?string $placeholderPortion, ) {} public static function parse(Compiler $compiler, string $path): self { $name = basename($path); // Strip out the emoji if it exists... $name = preg_replace('/⚡[\x{FE0E}\x{FE0F}]?/u', '', $name); $classPath = $path . '/' . $name . '.php'; $viewPath = $path . '/' . $name . '.blade.php'; $scriptPath = $path . '/' . $name . '.js'; if (! file_exists($classPath)) { throw new \Exception('Class file not found: ' . $classPath); } if (! file_exists($viewPath)) { throw new \Exception('View file not found: ' . $viewPath); } $scriptPortion = file_exists($scriptPath) ? file_get_contents($scriptPath) : null; $classPortion = file_get_contents($classPath); $viewPortion = $compiler->prepareViewForCompilation(file_get_contents($viewPath), $viewPath); $placeholderPortion = static::extractPlaceholderPortion($viewPortion); return new self( $path, $scriptPortion, $classPortion, $viewPortion, $placeholderPortion, ); } public function generateClassContents(?string $viewFileName = null, ?string $placeholderFileName = null, ?string $scriptFileName = null): string { $classContents = trim($this->classPortion); $classContents = $this->stripTrailingPhpTag($classContents); $classContents = $this->ensureAnonymousClassHasReturn($classContents); $classContents = $this->ensureAnonymousClassHasTrailingSemicolon($classContents); if ($viewFileName) { $classContents = $this->injectViewMethod($classContents, $viewFileName); } if ($placeholderFileName) { $classContents = $this->injectPlaceholderMethod($classContents, $placeholderFileName); } if ($scriptFileName) { $classContents = $this->injectScriptMethod($classContents, $scriptFileName); } return $classContents; } public function generateViewContents(): string { return trim($this->viewPortion); } public function generateScriptContents(): ?string { // Return null if there's no script content if ($this->scriptPortion === null || trim($this->scriptPortion) === '') { return null; } $scriptContents = trim($this->scriptPortion); return <<<JS export function run(\$wire, \$js) { {$scriptContents} } JS; } /** * Generate the complete single-file component contents (this is used for the convert command). */ public function generateContentsForSingleFile(): string { // Clean up the class contents $classContents = trim($this->classPortion); // Remove the return statement if present $classContents = preg_replace('/return\s+new\s+class\s*\(/s', 'new class(', $classContents); // Ensure trailing semicolon is present if (! str_ends_with($classContents, ';')) { $classContents .= ';'; } // Ensure it starts with opening PHP tag $phpOpen = '<' . '?php'; if (! str_starts_with($classContents, $phpOpen)) { $classContents = $phpOpen . "\n\n" . $classContents; } // Ensure it ends with closing PHP tag $phpClose = '?' . '>'; if (! str_ends_with($classContents, $phpClose)) { $classContents .= "\n" . $phpClose; } $sfcContents = $classContents . "\n\n" . trim($this->viewPortion); // Add script section if present if ($this->scriptPortion !== null && trim($this->scriptPortion) !== '') { $indentedScript = $this->addJavaScriptIndentation(trim($this->scriptPortion)); $sfcContents .= "\n\n<script>\n" . $indentedScript . "\n</script>"; } return $sfcContents; } protected function addJavaScriptIndentation(string $source): string { $lines = explode("\n", $source); if (empty($lines)) { return $source; } // Add 4 spaces to each non-empty line $indentedLines = []; foreach ($lines as $line) { if (trim($line) === '') { $indentedLines[] = $line; // Keep empty lines as-is } else { $indentedLines[] = ' ' . $line; } } return implode("\n", $indentedLines); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Compiler/Parser/Parser.php
src/Compiler/Parser/Parser.php
<?php namespace Livewire\Compiler\Parser; class Parser { public static function extractPlaceholderPortion(string &$contents): ?string { $islandsPattern = '/(@'.'island.*?@endisland)/s'; $replacements = []; $contents = preg_replace_callback($islandsPattern, function($matches) use (&$replacements) { $key = 'ISLANDREPLACEMENT:' . count($replacements); $replacements[$key] = $matches[0]; return $key; }, $contents); $placeholderPattern = '/@'.'placeholder(.*?)@endplaceholder/s'; $placeholderPortion = null; if (preg_match($placeholderPattern, $contents, $matches)) { $fullMatch = $matches[0]; $placeholderPortion = $matches[1]; $contents = str_replace($fullMatch, '', $contents); } foreach ($replacements as $key => $replacement) { $contents = str_replace($key, $replacement, $contents); } return $placeholderPortion ?? null; } public function generatePlaceholderContents(): ?string { return $this->placeholderPortion ?? null; } protected function stripTrailingPhpTag(string $contents): string { if (str_ends_with($contents, '?>')) { return substr($contents, 0, -2); } return $contents; } protected function ensureAnonymousClassHasReturn(string $contents): string { // Find the position of the first "new"... if (preg_match('/\bnew\b/', $contents, $newMatch, PREG_OFFSET_CAPTURE)) { $newPosition = $newMatch[0][1]; // Check if "return new" exists and find where "new" starts in that match... $hasReturnNew = preg_match('/\breturn\s+(new\b)/', $contents, $returnNewMatch, PREG_OFFSET_CAPTURE); // If "return new" does not exist or "new" is not at the same position as "return new", add "return"... if (!$hasReturnNew || $returnNewMatch[1][1] !== $newPosition) { $contents = substr_replace($contents, 'return ', $newPosition, 0); } } return $contents; } protected function ensureAnonymousClassHasTrailingSemicolon(string $contents): string { if (!preg_match('/\bnew\b/', $contents)) { return $contents; } // Find last closing brace and ensure it has a trailing semicolon if (preg_match('/}(?:\s*)$/', $contents)) { return preg_replace('/}(\s*)$/', '};$1', $contents); } if (preg_match('/}(?:\s*);/', $contents)) { return $contents; } // If we get here, we have a closing brace followed by other content return $contents; } protected function injectViewMethod(string $contents, string $viewFileName): string { $pattern = '/}(\s*);/'; preg_match_all($pattern, $contents, $matches, PREG_OFFSET_CAPTURE); $lastMatch = end($matches[0]); if ($lastMatch) { $position = $lastMatch[1]; return substr_replace($contents, <<<PHP protected function view(\$data = []) { return app('view')->file('{$viewFileName}', \$data); } } PHP , $position, 1); } return $contents; } protected function injectPlaceholderMethod(string $contents, string $placeholderFileName): string { $pattern = '/}(\s*);/'; preg_match_all($pattern, $contents, $matches, PREG_OFFSET_CAPTURE); $lastMatch = end($matches[0]); if ($lastMatch) { $position = $lastMatch[1]; return substr_replace($contents, <<<PHP public function placeholder() { return app('view')->file('{$placeholderFileName}'); } } PHP , $position, 1); } return $contents; } protected function injectScriptMethod(string $contents, string $scriptFileName): string { $pattern = '/}(\s*);/'; preg_match_all($pattern, $contents, $matches, PREG_OFFSET_CAPTURE); $lastMatch = end($matches[0]); if ($lastMatch) { $position = $lastMatch[1]; return substr_replace($contents, <<<PHP public function scriptModuleSrc() { return '{$scriptFileName}'; } } PHP , $position, 1); } return $contents; } protected function injectUseStatementsFromClassPortion(string $contents, string $classPortion): string { // Extract everything between <?php and "new" if (preg_match('/\<\?php(.*?)new/s', $classPortion, $matches)) { $preamble = $matches[1]; // Extract all use statements if (preg_match_all('/use\s+[^;]+;/s', $preamble, $useMatches)) { $useStatements = implode("\n", $useMatches[0]); } } // Only add PHP tags and use statements if we found any if (isset($useStatements) && $useStatements) { $contents = "<?php\n" . $useStatements . "\n?>\n\n" . $contents; } return $contents; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/DataStore.php
src/Mechanisms/DataStore.php
<?php namespace Livewire\Mechanisms; use WeakMap; class DataStore extends Mechanism { protected $lookup; function __construct() { $this->lookup = new WeakMap; } function set($instance, $key, $value) { if (! isset($this->lookup[$instance])) { $this->lookup[$instance] = []; } $this->lookup[$instance][$key] = $value; } function has($instance, $key, $iKey = null) { if (! isset($this->lookup[$instance])) { return false; } if (! isset($this->lookup[$instance][$key])) { return false; } if ($iKey !== null) { return !! ($this->lookup[$instance][$key][$iKey] ?? false); } return true; } function get($instance, $key, $default = null) { if (! isset($this->lookup[$instance])) { return value($default); } if (! isset($this->lookup[$instance][$key])) { return value($default); } return $this->lookup[$instance][$key]; } function find($instance, $key, $iKey = null, $default = null) { if (! isset($this->lookup[$instance])) { return value($default); } if (! isset($this->lookup[$instance][$key])) { return value($default); } if ($iKey !== null && ! isset($this->lookup[$instance][$key][$iKey])) { return value($default); } return $iKey !== null ? $this->lookup[$instance][$key][$iKey] : $this->lookup[$instance][$key]; } function push($instance, $key, $value, $iKey = null) { if (! isset($this->lookup[$instance])) { $this->lookup[$instance] = []; } if (! isset($this->lookup[$instance][$key])) { $this->lookup[$instance][$key] = []; } if ($iKey) { $this->lookup[$instance][$key][$iKey] = $value; } else { $this->lookup[$instance][$key][] = $value; } } function unset($instance, $key, $iKey = null) { if (! isset($this->lookup[$instance])) { return; } if (! isset($this->lookup[$instance][$key])) { return; } if ($iKey !== null) { // Set a local variable to avoid the "indirect modification" error. $keyValue = $this->lookup[$instance][$key]; unset($keyValue[$iKey]); $this->lookup[$instance][$key] = $keyValue; } else { // Set a local variable to avoid the "indirect modification" error. $instanceValue = $this->lookup[$instance]; unset($instanceValue[$key]); $this->lookup[$instance] = $instanceValue; } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/Mechanism.php
src/Mechanisms/Mechanism.php
<?php namespace Livewire\Mechanisms; abstract class Mechanism { function register() { app()->instance(static::class, $this); } function boot() { // } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/RenderComponent.php
src/Mechanisms/RenderComponent.php
<?php namespace Livewire\Mechanisms; use Illuminate\Support\Facades\Blade; class RenderComponent extends Mechanism { function boot() { Blade::directive('livewire', [static::class, 'livewire']); } public static function livewire($expression) { $key = null; $slots = null; // Extract key parameter $keyPattern = '/,\s*?key\(([\s\S]*)\)/'; // everything between ",key(" and ")" $expression = preg_replace_callback($keyPattern, function ($match) use (&$key) { $key = trim($match[1]) ?: $key; return ''; }, $expression); // Extract slots parameter (4th parameter) $slotsPattern = '/,\s*?(\$__slots\s*\?\?\s*\[\])/'; // match $__slots ?? [] $expression = preg_replace_callback($slotsPattern, function ($match) use (&$slots) { $slots = trim($match[1]); return ''; }, $expression); if (is_null($key)) { $key = 'null'; } if (is_null($slots)) { $slots = '[]'; } $deterministicBladeKey = app(\Livewire\Mechanisms\ExtendBlade\DeterministicBladeKeys::class)->generate(); $deterministicBladeKey = "'{$deterministicBladeKey}'"; return <<<EOT <?php \$__split = function (\$name, \$params = []) { return [\$name, \$params]; }; [\$__name, \$__params] = \$__split($expression); \$key = $key; \$__componentSlots = $slots; \$key ??= \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::generateKey($deterministicBladeKey, \$key); \$__html = app('livewire')->mount(\$__name, \$__params, \$key, \$__componentSlots); echo \$__html; unset(\$__html); unset(\$__name); unset(\$__params); unset(\$__componentSlots); unset(\$__split); if (isset(\$__slots)) unset(\$__slots); ?> EOT; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/ClearCachedFiles.php
src/Mechanisms/ClearCachedFiles.php
<?php namespace Livewire\Mechanisms; class ClearCachedFiles extends Mechanism { function boot() { // Hook into Laravel's view:clear command to also clear Livewire compiled files if (app()->runningInConsole()) { app('events')->listen(\Illuminate\Console\Events\CommandFinished::class, function ($event) { if ($event->command === 'view:clear' && $event->exitCode === 0) { app('livewire.compiler')->clearCompiled($event->output); } }); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/ComponentContext.php
src/Mechanisms/HandleComponents/ComponentContext.php
<?php namespace Livewire\Mechanisms\HandleComponents; use AllowDynamicProperties; #[AllowDynamicProperties] class ComponentContext { public $effects = []; public $memo = []; public function __construct( public $component, public $mounting = false, ) {} public function isMounting() { return $this->mounting; } public function addEffect($key, $value) { if (is_array($key)) { foreach ($key as $iKey => $iValue) $this->addEffect($iKey, $iValue); return; } $this->effects[$key] = $value; } public function pushEffect($key, $value, $iKey = null) { if (! isset($this->effects[$key])) $this->effects[$key] = []; if ($iKey) { $this->effects[$key][$iKey] = $value; } else { $this->effects[$key][] = $value; } } public function addMemo($key, $value) { $this->memo[$key] = $value; } public function pushMemo($key, $value, $iKey = null) { if (! isset($this->memo[$key])) $this->memo[$key] = []; if ($iKey) { $this->memo[$key][$iKey] = $value; } else { $this->memo[$key][] = $value; } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Checksum.php
src/Mechanisms/HandleComponents/Checksum.php
<?php namespace Livewire\Mechanisms\HandleComponents; use Illuminate\Support\Facades\RateLimiter; use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException; use function Livewire\trigger; class Checksum { protected static $maxFailures = 10; protected static $decaySeconds = 600; // 10 minutes static function verify($snapshot) { // Check if this IP is already blocked due to too many failures static::enforceRateLimit(); $checksum = $snapshot['checksum']; unset($snapshot['checksum']); trigger('checksum.verify', $checksum, $snapshot); if ($checksum !== $comparitor = self::generate($snapshot)) { trigger('checksum.fail', $checksum, $comparitor, $snapshot); static::recordFailure(); throw new CorruptComponentPayloadException; } } protected static function enforceRateLimit() { $key = static::rateLimitKey(); if (RateLimiter::tooManyAttempts($key, static::$maxFailures)) { $seconds = RateLimiter::availableIn($key); throw new TooManyRequestsHttpException( $seconds, 'Too many invalid Livewire requests. Please try again later.' ); } } protected static function recordFailure() { RateLimiter::hit(static::rateLimitKey(), static::$decaySeconds); } protected static function rateLimitKey(): string { return 'livewire-checksum-failures:' . request()->ip(); } static function generate($snapshot) { $hashKey = app('encrypter')->getKey(); // Remove the children from the memo in the snapshot, as it is actually Ok // if the "children" tracking is tampered with. This way JavaScript can // modify children as it needs to for dom-diffing purposes... unset($snapshot['memo']['children']); $checksum = hash_hmac('sha256', json_encode($snapshot), $hashKey); trigger('checksum.generate', $checksum, $snapshot); return $checksum; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/BaseRenderless.php
src/Mechanisms/HandleComponents/BaseRenderless.php
<?php namespace Livewire\Mechanisms\HandleComponents; use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute; use function Livewire\store; #[\Attribute] class BaseRenderless extends LivewireAttribute { function call() { store($this->component)->set('skipIslandsRender', true); $this->component->skipRender(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/BrowserTest.php
src/Mechanisms/HandleComponents/BrowserTest.php
<?php namespace Livewire\Mechanisms\HandleComponents; use Livewire\Attributes\Computed; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_corrupt_component_payload_exception_is_no_longer_thrown_from_data_incompatible_with_javascript() { Livewire::visit(new class extends \Livewire\Component { public $subsequentRequest = false; public $negativeZero = -0; public $associativeArrayWithStringAndNumericKeys = [ '2' => 'two', 'three' => 'three', 1 => 'one', ]; public $unorderedNumericArray = [ 3 => 'three', 1 => 'one', 2 => 'two' ]; public $integerLargerThanJavascriptsMaxSafeInteger = 999_999_999_999_999_999; public $unicodeString = 'â'; public $arrayWithUnicodeString = ['â']; public $recursiveArrayWithUnicodeString = ['â', ['â']]; public function hydrate() { $this->subsequentRequest = true; } public function render() { return <<<'HTML' <div> <div> @if ($subsequentRequest) Subsequent request @else Initial request @endif </div> <div> <span dusk="negativeZero">{{ $negativeZero }}</span> </div> <button type="button" wire:click="$refresh" dusk="refresh">Refresh</button> </div> HTML; } }) ->assertSee('Initial request') ->waitForLivewire()->click('@refresh') ->assertSee('Subsequent request') ; } public function test_it_converts_empty_strings_to_null_for_integer_properties() { Livewire::visit(new class extends \Livewire\Component { public ?int $number = 5; public function render() { return <<<'HTML' <div> <input type="text" wire:model.live="number" dusk="numberInput" /> <div dusk="number">{{ $number }}</div> </div> HTML; } }) ->assertSeeIn('@number', 5) ->waitForLivewire()->keys('@numberInput', '{backspace}') ->assertSeeNothingIn('@number', '') ; } public function test_it_uses_the_synthesizers_for_multiple_types_property_updates() { Livewire::visit(new class extends \Livewire\Component { public string|int $localValue = 15; public function render() { return <<<'HTML' <div> <input type="text" dusk="localInput" wire:model.live.debounce.100ms="localValue"> <span dusk="localValue">{{ $localValue }}</span> </div> HTML; } }) ->waitForText(15) ->assertSee(15) ->type('@localInput', 25) ->waitForText(25) ->assertSee(25) ; } public function test_it_uses_the_synthesizers_for_enum_property_updates_when_initial_state_is_null() { Livewire::visit(new class extends \Livewire\Component { public Suit $selected; #[Computed] public function cases() { return Suit::cases(); } public function render() { return <<<'HTML' <div> <select wire:model.live="selected" dusk="selectInput"> @foreach($this->cases() as $suit) <option value="{{ $suit->value }}">{{ $suit }}</option> @endforeach </select> <span dusk="selected">{{ $selected }}</span> </div> HTML; } }) ->assertSeeNothingIn('@selected') ->waitForLivewire()->select('@selectInput', 'D') ->assertSeeIn('@selected', 'D') ; } } enum Suit: string { case Hearts = 'H'; case Diamonds = 'D'; case Clubs = 'C'; case Spades = 'S'; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/ViewContext.php
src/Mechanisms/HandleComponents/ViewContext.php
<?php namespace Livewire\Mechanisms\HandleComponents; use function Livewire\invade; class ViewContext { function __construct( public $slots = [], public $pushes = [], public $prepends = [], public $sections = [], ) {} function extractFromEnvironment($__env) { $factory = invade($__env); $this->slots = $factory->slots; $this->pushes = $factory->pushes; $this->prepends = $factory->prepends; $this->sections = $factory->sections; } function mergeIntoNewEnvironment($__env) { $factory = invade($__env); $factory->slots = $this->slots; $factory->pushes = $this->pushes; $factory->prepends = $this->prepends; $factory->sections = $this->sections; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/CorruptComponentPayloadException.php
src/Mechanisms/HandleComponents/CorruptComponentPayloadException.php
<?php namespace Livewire\Mechanisms\HandleComponents; use Livewire\Exceptions\BypassViewHandler; class CorruptComponentPayloadException extends \Exception { use BypassViewHandler; public function __construct() { parent::__construct( "Livewire encountered corrupt data when trying to hydrate a component. \n". "Ensure that the [name, id, data] of the Livewire component wasn't tampered with between requests." ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/UnitTest.php
src/Mechanisms/HandleComponents/UnitTest.php
<?php namespace Livewire\Mechanisms\HandleComponents; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Route; use Illuminate\Support\Stringable; use Livewire\Component; use Livewire\Form; use Livewire\Livewire; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_it_restores_laravel_middleware_after_livewire_test() { // Run a basic Livewire test first to ensure Livewire has disabled // trim strings and convert empty strings to null middleware Livewire::test(BasicComponent::class) ->set('name', 'test') ->assertSetStrict('name', 'test'); // Then make a standard laravel test and ensure that the input has // had trim strings re-applied Route::post('laravel', function() { return 'laravel' . request()->input('name') . 'laravel'; }); $this->post('laravel', ['name' => ' aaa ']) ->assertSee('laravelaaalaravel'); } public function test_synthesized_property_types_are_preserved_after_update() { Livewire::test(new class extends TestComponent { public $foo; public $isStringable; public function mount() { $this->foo = str('bar'); } public function checkStringable() { $this->isStringable = $this->foo instanceof Stringable; } }) ->assertSet('foo', 'bar') ->call('checkStringable') ->assertSetStrict('isStringable', true) ->set('foo', 'baz') ->assertSet('foo', 'baz') ->call('checkStringable') ->assertSetStrict('isStringable', true) ; } public function test_uninitialized_integer_can_be_set_to_empty_string() { Livewire::test(new class extends Component { public int $count; public function render() { return <<<'HTML' <div> <h1 dusk="count">count: {{ $count }};</h1> </div> HTML; } }) ->assertSee('count: ;') ->set('count', 1) ->assertSee('count: 1;') ->set('count', '') ->assertSee('count: ;') ; } public function test_uninitialized_integer_in_a_form_object_can_be_set_to_empty_string() { Livewire::test(new class extends Component { public CountForm $form; public function render() { return <<<'HTML' <div> <!-- --> </div> HTML; } }) ->assertSetStrict('form.count', null) ->set('form.count', 1) ->assertSetStrict('form.count', 1) ->set('form.count', '') ->assertSetStrict('form.count', null) ; } public function test_it_uses_the_synthesizers_for_enum_property_updates_when_initial_state_is_null() { Livewire::test(new class extends \Livewire\Component { public ?UnitSuit $selected; #[\Livewire\Attributes\Computed] public function cases() { return UnitSuit::cases(); } public function render() { return <<<'HTML' <div> <select wire:model.live="selected" dusk="selectInput"> @foreach($this->cases() as $suit) <option value="{{ $suit->value }}">{{ $suit }}</option> @endforeach </select> <span dusk="selected">{{ $selected }}</span> </div> HTML; } }) ->assertSetStrict('selected', null) ->set('selected', 'D') ->assertSetStrict('selected', UnitSuit::Diamonds) ->set('selected', null) ->assertSetStrict('selected', null) ; } public function test_it_uses_the_synthesizers_for_enum_property_updates_when_initial_state_is_null_inside_form_object() { Livewire::test(new class extends \Livewire\Component { public SuitForm $form; public function render() { return <<<'HTML' <div> <!-- --> </div> HTML; } }) ->assertSetStrict('form.selected', null) ->set('form.selected', 'D') ->assertSetStrict('form.selected', UnitSuit::Diamonds) ->set('form.selected', null) ->assertSetStrict('form.selected', null) ; } public function test_it_bypasses_synthesizer_hydration_when_deleting() { Livewire::test(new class extends \Livewire\Component { public $suits; public $dates; public $objects; public function mount() { $this->suits = UnitSuit::cases(); $this->objects = [ (object) ['foo' => 'bar'], (object) ['bing' => 'buzz'], (object) ['ping' => 'pong'], ]; $this->dates = [ Carbon::make('2001-01-01'), Carbon::make('2002-02-02'), Carbon::make('2003-03-03'), ]; } public function render() { return <<<'HTML' <div> <!-- --> </div> HTML; } }) // simulate a client side unsets by setting the '__rm__' value ->set('objects.1', '__rm__') ->assertSet('objects', [ 0 => (object) ['foo' => 'bar'], 2 => (object) ['ping' => 'pong'], ]) ->set('dates.1', '__rm__') ->assertSet('dates', [ 0 => Carbon::make('2001-01-01'), 2 => Carbon::make('2003-03-03'), ]) ->set('suits.1', '__rm__') ->assertSetStrict('suits', [ 0 => UnitSuit::Hearts, 2 => UnitSuit::Clubs, 3 => UnitSuit::Spades, ]) ; } public function test_it_leaves_camel_case_params_when_matching_component_properties() { Livewire::test( new class extends \Tests\TestComponent { public $fooBar; }, ['fooBar' => 'baz'] ) ->assertSet('fooBar', 'baz'); } public function test_it_leaves_snake_case_params_when_matching_component_properties() { Livewire::test( new class extends \Tests\TestComponent { public $foo_bar; }, ['foo_bar' => 'baz'] ) ->assertSet('foo_bar', 'baz'); } public function test_it_converts_kebab_case_params_to_camel_case_when_matching_component_properties() { Livewire::test( new class extends \Tests\TestComponent { public $fooBar; public function render() { return '<div>fooBar: {{ $fooBar }}</div>'; } }, ['foo-bar' => 'baz'] ) ->assertSet('fooBar', 'baz'); } public function test_kebab_case_params_are_left_as_kebab_if_it_does_not_match_component_property_and_is_stored_in_html_attributes() { Livewire::test( new class extends \Tests\TestComponent { }, ['data-foo' => 'bar'] ) ->tap(function ($component) { $this->assertEquals(['data-foo' => 'bar'], $component->instance()->getHtmlAttributes()); }); } } class BasicComponent extends TestComponent { public $name; } class ComponentWithStringPropertiesStub extends TestComponent { public $emptyString = ''; public $oneSpace = ' '; } enum UnitSuit: string { case Hearts = 'H'; case Diamonds = 'D'; case Clubs = 'C'; case Spades = 'S'; } class CountForm extends Form { public int $count; } class SuitForm extends Form { public UnitSuit $selected; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/SecurityPolicy.php
src/Mechanisms/HandleComponents/SecurityPolicy.php
<?php namespace Livewire\Mechanisms\HandleComponents; class SecurityPolicy { /** * Classes that should never be instantiated by Livewire synthesizers. * These are known-dangerous classes that could be exploited if an attacker * somehow bypassed the checksum protection. */ protected static $deniedClasses = [ // Console commands - could execute arbitrary system commands 'Illuminate\Console\Command', 'Symfony\Component\Console\Command\Command', // Process execution - direct system command execution 'Symfony\Component\Process\Process', // Known serialization gadgets 'Illuminate\Broadcasting\PendingBroadcast', 'Illuminate\Foundation\Testing\PendingCommand', // Queue jobs - could execute arbitrary code 'Illuminate\Queue\CallQueuedClosure', // Notifications - could send arbitrary notifications 'Illuminate\Notifications\Notification', ]; /** * Validate that a class is safe to instantiate. * Throws an exception if the class is in the denylist. */ public static function validateClass(string $class): void { foreach (static::$deniedClasses as $denied) { if (is_a($class, $denied, true)) { throw new \Exception("Livewire: Class [{$class}] is not allowed to be instantiated."); } } } /** * Add classes to the denylist at runtime. */ public static function denyClasses(array $classes): void { static::$deniedClasses = array_merge(static::$deniedClasses, $classes); } /** * Get the current denylist (useful for testing). */ public static function getDeniedClasses(): array { return static::$deniedClasses; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/HandleComponents.php
src/Mechanisms/HandleComponents/HandleComponents.php
<?php namespace Livewire\Mechanisms\HandleComponents; use function Livewire\{store, trigger, wrap }; use ReflectionUnionType; use Livewire\Mechanisms\Mechanism; use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth; use Livewire\Exceptions\PublicPropertyNotFoundException; use Livewire\Exceptions\MethodNotFoundException; use Livewire\Exceptions\MaxNestingDepthExceededException; use Livewire\Exceptions\TooManyCallsException; use Livewire\Drawer\Utils; use Illuminate\Support\Facades\View; class HandleComponents extends Mechanism { protected $propertySynthesizers = [ Synthesizers\CarbonSynth::class, Synthesizers\CollectionSynth::class, Synthesizers\StringableSynth::class, Synthesizers\EnumSynth::class, Synthesizers\StdClassSynth::class, Synthesizers\ArraySynth::class, Synthesizers\IntSynth::class, Synthesizers\FloatSynth::class ]; // Performance optimization: Cache which synthesizer matches which type protected $synthesizerTypeCache = []; public static $renderStack = []; public static $componentStack = []; public function registerPropertySynthesizer($synth) { foreach ((array) $synth as $class) { array_unshift($this->propertySynthesizers, $class); } } public function mount($name, $params = [], $key = null, $slots = []) { $parent = app('livewire')->current(); $component = app('livewire')->new($name); // Separate params into component properties and HTML attributes... [$componentParams, $htmlAttributes] = $this->separateParamsAndAttributes($component, $params); if ($html = $this->shortCircuitMount($name, $componentParams, $key, $parent, $slots, $htmlAttributes)) return $html; if (! empty($slots)) { $component->withSlots($slots, $parent); } if (! empty($htmlAttributes)) { $component->withHtmlAttributes($htmlAttributes); } $this->pushOntoComponentStack($component); $context = new ComponentContext($component, mounting: true); if (config('app.debug')) $start = microtime(true); $finish = trigger('mount', $component, $componentParams, $key, $parent, $htmlAttributes); if (config('app.debug')) trigger('profile', 'mount', $component->getId(), [$start, microtime(true)]); if (config('app.debug')) $start = microtime(true); $html = $this->render($component, '<div></div>'); if (config('app.debug')) trigger('profile', 'render', $component->getId(), [$start, microtime(true)]); if (config('app.debug')) $start = microtime(true); trigger('dehydrate', $component, $context); $snapshot = $this->snapshot($component, $context); if (config('app.debug')) trigger('profile', 'dehydrate', $component->getId(), [$start, microtime(true)]); trigger('destroy', $component, $context); $html = Utils::insertAttributesIntoHtmlRoot($html, [ 'wire:snapshot' => $snapshot, 'wire:effects' => $context->effects, ]); $this->popOffComponentStack(); return $finish($html, $snapshot); } protected function separateParamsAndAttributes($component, $params) { $componentParams = []; $htmlAttributes = []; // Get component's properties and mount method parameters $componentProperties = Utils::getPublicPropertiesDefinedOnSubclass($component); $mountParams = $this->getMountMethodParameters($component); foreach ($params as $key => $value) { $processedKey = $key; // Convert only kebab-case params to camelCase for matching... if (str($processedKey)->contains('-')) { $processedKey = str($processedKey)->camel()->toString(); } // Check if this is a reserved param if ($this->isReservedParam($key)) { $componentParams[$key] = $value; } // Check if this maps to a component property or mount param elseif ( array_key_exists($processedKey, $componentProperties) || in_array($processedKey, $mountParams) || is_numeric($key) // if the key is numeric, it's likely a mount parameter... ) { $componentParams[$processedKey] = $value; } else { // Keep as HTML attribute (preserve kebab-case) $htmlAttributes[$key] = $value; } } return [$componentParams, $htmlAttributes]; } protected function isReservedParam($key) { $exact = ['lazy', 'defer', 'lazy.bundle', 'defer.bundle', 'wire:ref']; $startsWith = ['@']; // Check exact matches if (in_array($key, $exact)) { return true; } // Check starts_with patterns foreach ($startsWith as $prefix) { if (str_starts_with($key, $prefix)) { return true; } } return false; } protected function getMountMethodParameters($component) { if (! method_exists($component, 'mount')) { return []; } $reflection = new \ReflectionMethod($component, 'mount'); $parameters = []; foreach ($reflection->getParameters() as $parameter) { $parameters[] = $parameter->getName(); } return $parameters; } protected function shortCircuitMount($name, $params, $key, $parent, $slots, $htmlAttributes) { $newHtml = null; trigger('pre-mount', $name, $params, $key, $parent, function ($html) use (&$newHtml) { $newHtml = $html; }, $slots, $htmlAttributes); return $newHtml; } public function update($snapshot, $updates, $calls) { $data = $snapshot['data']; $memo = $snapshot['memo']; if (config('app.debug')) $start = microtime(true); [ $component, $context ] = $this->fromSnapshot($snapshot); $this->pushOntoComponentStack($component); trigger('hydrate', $component, $memo, $context); $this->updateProperties($component, $updates, $data, $context); if (config('app.debug')) trigger('profile', 'hydrate', $component->getId(), [$start, microtime(true)]); $this->callMethods($component, $calls, $context); if (config('app.debug')) $start = microtime(true); if ($html = $this->render($component)) { $context->addEffect('html', $html); if (config('app.debug')) trigger('profile', 'render', $component->getId(), [$start, microtime(true)]); } if (config('app.debug')) $start = microtime(true); trigger('dehydrate', $component, $context); $snapshot = $this->snapshot($component, $context); if (config('app.debug')) trigger('profile', 'dehydrate', $component->getId(), [$start, microtime(true)]); trigger('destroy', $component, $context); $this->popOffComponentStack(); return [ $snapshot, $context->effects ]; } public function fromSnapshot($snapshot) { Checksum::verify($snapshot); trigger('snapshot-verified', $snapshot); $data = $snapshot['data']; $name = $snapshot['memo']['name']; $id = $snapshot['memo']['id']; $component = app('livewire')->new($name, id: $id); $context = new ComponentContext($component); $this->hydrateProperties($component, $data, $context); return [ $component, $context ]; } public function snapshot($component, $context = null) { $context ??= new ComponentContext($component); $data = $this->dehydrateProperties($component, $context); $snapshot = [ 'data' => $data, 'memo' => [ 'id' => $component->getId(), 'name' => $component->getName(), ...$context->memo, ], ]; $snapshot['checksum'] = Checksum::generate($snapshot); return $snapshot; } protected function dehydrateProperties($component, $context) { $data = Utils::getPublicPropertiesDefinedOnSubclass($component); foreach ($data as $key => $value) { $data[$key] = $this->dehydrate($value, $context, $key); } return $data; } protected function dehydrate($target, $context, $path) { if (Utils::isAPrimitive($target)) return $target; $synth = $this->propertySynth($target, $context, $path); [ $data, $meta ] = $synth->dehydrate($target, function ($name, $child) use ($context, $path) { return $this->dehydrate($child, $context, "{$path}.{$name}"); }); $meta['s'] = $synth::getKey(); return [ $data, $meta ]; } protected function hydrateProperties($component, $data, $context) { foreach ($data as $key => $value) { if (! property_exists($component, $key)) continue; $child = $this->hydrate($value, $context, $key); // Typed properties shouldn't be set back to "null". It will throw an error... if ((new \ReflectionProperty($component, $key))->getType() && is_null($child)) continue; $component->$key = $child; } } protected function hydrate($valueOrTuple, $context, $path) { if (! Utils::isSyntheticTuple($value = $tuple = $valueOrTuple)) return $value; [$value, $meta] = $tuple; // Nested properties get set as `__rm__` when they are removed. We don't want to hydrate these. if ($this->isRemoval($value) && str($path)->contains('.')) { return $value; } // Validate class against denylist before any synthesizer can instantiate it... if (isset($meta['class'])) { SecurityPolicy::validateClass($meta['class']); } $synth = $this->propertySynth($meta['s'], $context, $path); return $synth->hydrate($value, $meta, function ($name, $child) use ($context, $path) { return $this->hydrate($child, $context, "{$path}.{$name}"); }); } protected function hydratePropertyUpdate($valueOrTuple, $context, $path) { if (! Utils::isSyntheticTuple($value = $tuple = $valueOrTuple)) return $value; [$value, $meta] = $tuple; // Nested properties get set as `__rm__` when they are removed. We don't want to hydrate these. if ($this->isRemoval($value) && str($path)->contains('.')) { return $value; } // Validate class against denylist before any synthesizer can instantiate it... if (isset($meta['class'])) { SecurityPolicy::validateClass($meta['class']); } $synth = $this->propertySynth($meta['s'], $context, $path); return $synth->hydrate($value, $meta, function ($name, $child) { return $child; }); } protected function render($component, $default = null) { if ($html = store($component)->get('skipRender', false)) { $html = value(is_string($html) ? $html : $default); if (! $html) return; return Utils::insertAttributesIntoHtmlRoot($html, [ 'wire:id' => $component->getId(), 'wire:name' => $component->getName(), ]); } [ $view, $properties ] = $this->getView($component); return $this->trackInRenderStack($component, function () use ($component, $view, $properties) { $finish = trigger('render', $component, $view, $properties); $revertA = Utils::shareWithViews('__livewire', $component); $revertB = Utils::shareWithViews('_instance', $component); // @deprecated $viewContext = new ViewContext; $html = $view->render(function ($view) use ($viewContext) { // Extract leftover slots, sections, and pushes before they get flushed... $viewContext->extractFromEnvironment($view->getFactory()); }); $revertA(); $revertB(); $html = Utils::insertAttributesIntoHtmlRoot($html, [ 'wire:id' => $component->getId(), 'wire:name' => $component->getName(), ]); $replaceHtml = function ($newHtml) use (&$html) { $html = $newHtml; }; $html = $finish($html, $replaceHtml, $viewContext); return $html; }); } protected function getView($component) { $viewPath = config('livewire.view_path', resource_path('views/livewire')); $dotName = $component->getName(); $fileName = str($dotName)->replace('.', '/')->__toString(); $viewOrString = null; if (method_exists($component, 'render')) { $viewOrString = wrap($component)->render(); } elseif ($component->hasProvidedView()) { $viewOrString = $component->getProvidedView(); } else { $viewOrString = View::file($viewPath . '/' . $fileName . '.blade.php'); } $properties = Utils::getPublicPropertiesDefinedOnSubclass($component); $view = Utils::generateBladeView($viewOrString, $properties); return [ $view, $properties ]; } protected function trackInRenderStack($component, $callback) { array_push(static::$renderStack, $component); return tap($callback(), function () { array_pop(static::$renderStack); }); } protected function updateProperties($component, $updates, $data, $context) { $finishes = []; foreach ($updates as $path => $value) { $value = $this->hydrateForUpdate($data, $path, $value, $context); // We only want to run "updated" hooks after all properties have // been updated so that each individual hook has the ability // to overwrite the updated states of other properties... $finishes[] = $this->updateProperty($component, $path, $value, $context); } foreach ($finishes as $finish) { $finish(); } } public function updateProperty($component, $path, $value, $context) { $segments = explode('.', $path); $maxDepth = config('livewire.payload.max_nesting_depth'); if ($maxDepth !== null && count($segments) > $maxDepth) { throw new MaxNestingDepthExceededException($path, $maxDepth); } $property = array_shift($segments); $finish = trigger('update', $component, $path, $value); // Ensure that it's a public property, not on the base class first... if (! in_array($property, array_keys(Utils::getPublicPropertiesDefinedOnSubclass($component)))) { throw new PublicPropertyNotFoundException($property, $component->getName()); } // If this isn't a "deep" set, set it directly, otherwise we have to // recursively get up and set down the value through the synths... if (empty($segments)) { $this->setComponentPropertyAwareOfTypes($component, $property, $value); } else { $propertyValue = $component->$property; $this->setComponentPropertyAwareOfTypes($component, $property, $this->recursivelySetValue($property, $propertyValue, $value, $segments, 0, $context) ); } return $finish; } protected function hydrateForUpdate($raw, $path, $value, $context) { $meta = $this->getMetaForPath($raw, $path); // If we have meta data already for this property, let's use that to get a synth... if ($meta) { return $this->hydratePropertyUpdate([$value, $meta], $context, $path); } // If we don't, let's check to see if it's a typed property and fetch the synth that way... $parent = str($path)->contains('.') ? data_get($context->component, str($path)->beforeLast('.')->toString()) : $context->component; $childKey = str($path)->afterLast('.'); if ($parent && is_object($parent) && property_exists($parent, $childKey) && Utils::propertyIsTyped($parent, $childKey)) { $type = Utils::getProperty($parent, $childKey)->getType(); $types = $type instanceof ReflectionUnionType ? $type->getTypes() : [$type]; foreach ($types as $type) { $synth = $this->getSynthesizerByType($type->getName(), $context, $path); if ($synth) return $synth->hydrateFromType($type->getName(), $value); } } return $value; } protected function getMetaForPath($raw, $path) { $segments = explode('.', $path); $first = array_shift($segments); [$data, $meta] = Utils::isSyntheticTuple($raw) ? $raw : [$raw, null]; if ($path !== '') { $value = $data[$first] ?? null; return $this->getMetaForPath($value, implode('.', $segments)); } return $meta; } protected function recursivelySetValue($baseProperty, $target, $leafValue, $segments, $index = 0, $context = null) { $isLastSegment = count($segments) === $index + 1; $property = $segments[$index]; $path = implode('.', array_slice($segments, 0, $index + 1)); $synth = $this->propertySynth($target, $context, $path); if ($isLastSegment) { $toSet = $leafValue; } else { $propertyTarget = $synth->get($target, $property); // "$path" is a dot-notated key. This means we may need to drill // down and set a value on a deeply nested object. That object // may not exist, so let's find the first one that does... // Here's we've determined we're trying to set a deeply nested // value on an object/array that doesn't exist, so we need // to build up that non-existant nesting structure first. if ($propertyTarget === null) $propertyTarget = []; $toSet = $this->recursivelySetValue($baseProperty, $propertyTarget, $leafValue, $segments, $index + 1, $context); } $method = ($this->isRemoval($leafValue) && $isLastSegment) ? 'unset' : 'set'; $pathThusFar = collect([$baseProperty, ...$segments])->slice(0, $index + 1)->join('.'); $fullPath = collect([$baseProperty, ...$segments])->join('.'); $synth->$method($target, $property, $toSet, $pathThusFar, $fullPath); return $target; } protected function setComponentPropertyAwareOfTypes($component, $property, $value) { try { $component->$property = $value; } catch (\TypeError $e) { // If an "int" is being set to empty string, unset the property (making it null). // This is common in the case of `wire:model`ing an int to a text field... // If a value is being set to "null", do the same... if ($value === '' || $value === null) { unset($component->$property); } else { throw $e; } } } protected function callMethods($root, $calls, $componentContext) { $maxCalls = config('livewire.payload.max_calls'); if ($maxCalls !== null && count($calls) > $maxCalls) { throw new TooManyCallsException(count($calls), $maxCalls); } $returns = []; foreach ($calls as $idx => $call) { $method = $call['method']; $params = $call['params']; $metadata = $call['metadata'] ?? []; $earlyReturnCalled = false; $earlyReturn = null; $returnEarly = function ($return = null) use (&$earlyReturnCalled, &$earlyReturn) { $earlyReturnCalled = true; $earlyReturn = $return; }; $finish = trigger('call', $root, $method, $params, $componentContext, $returnEarly, $metadata, $idx); if ($earlyReturnCalled) { $returns[] = $finish($earlyReturn); continue; } $methods = Utils::getPublicMethodsDefinedBySubClass($root); // Also remove "render" from the list... $methods = array_values(array_diff($methods, ['render'])); // @todo: put this in a better place: $methods[] = '__dispatch'; if (! in_array($method, $methods)) { throw new MethodNotFoundException($method); } if (config('app.debug')) $start = microtime(true); $return = wrap($root)->{$method}(...$params); if (config('app.debug')) trigger('profile', 'call'.$idx, $root->getId(), [$start, microtime(true)]); $returns[] = $finish($return); // Support `Wire:click.renderless`... if ($metadata['renderless'] ?? false) { $root->skipRender(); } } $componentContext->addEffect('returns', $returns); } public function findSynth($keyOrTarget, $component): ?Synth { $context = new ComponentContext($component); try { return $this->propertySynth($keyOrTarget, $context, null); } catch (\Exception $e) { return null; } } public function propertySynth($keyOrTarget, $context, $path): Synth { return is_string($keyOrTarget) ? $this->getSynthesizerByKey($keyOrTarget, $context, $path) : $this->getSynthesizerByTarget($keyOrTarget, $context, $path); } protected function getSynthesizerByKey($key, $context, $path) { foreach ($this->propertySynthesizers as $synth) { if ($synth::getKey() === $key) { return new $synth($context, $path); } } throw new \Exception('No synthesizer found for key: "'.$key.'"'); } protected function getSynthesizerByTarget($target, $context, $path) { // Performance optimization: Cache synthesizer matches by runtime type... $type = get_debug_type($target); if (! isset($this->synthesizerTypeCache[$type])) { foreach ($this->propertySynthesizers as $synth) { if ($synth::match($target)) { $this->synthesizerTypeCache[$type] = $synth; return new $synth($context, $path); } } throw new \Exception('Property type not supported in Livewire for property: ['.json_encode($target).']'); } return new $this->synthesizerTypeCache[$type]($context, $path); } protected function getSynthesizerByType($type, $context, $path) { foreach ($this->propertySynthesizers as $synth) { if ($synth::matchByType($type)) { return new $synth($context, $path); } } return null; } protected function pushOntoComponentStack($component) { array_push($this::$componentStack, $component); } protected function popOffComponentStack() { array_pop($this::$componentStack); } protected function isRemoval($value) { return $value === '__rm__'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/ArraySynth.php
src/Mechanisms/HandleComponents/Synthesizers/ArraySynth.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers; class ArraySynth extends Synth { public static $key = 'arr'; static function match($target) { return is_array($target); } function dehydrate($target, $dehydrateChild) { foreach ($target as $key => $child) { $target[$key] = $dehydrateChild($key, $child); } return [$target, []]; } function hydrate($value, $meta, $hydrateChild) { // If we are "hydrating" a value about to be used in an update, // Let's make sure it's actually an array before try to set it. // This is most common in the case of "__rm__" values, but also // applies to any non-array value... if (! is_array($value)) { return $value; } foreach ($value as $key => $child) { $value[$key] = $hydrateChild($key, $child); } return $value; } function set(&$target, $key, $value) { $target[$key] = $value; } function unset(&$target, $key) { unset($target[$key]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/CollectionSynth.php
src/Mechanisms/HandleComponents/Synthesizers/CollectionSynth.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers; use Illuminate\Support\Collection; class CollectionSynth extends ArraySynth { public static $key = 'clctn'; static function match($target) { return $target instanceof Collection; } function dehydrate($target, $dehydrateChild) { $data = $target->all(); foreach ($data as $key => $child) { $data[$key] = $dehydrateChild($key, $child); } return [ $data, ['class' => get_class($target)] ]; } function hydrate($value, $meta, $hydrateChild) { foreach ($value as $key => $child) { $value[$key] = $hydrateChild($key, $child); } return new $meta['class']($value); } function &get(&$target, $key) { // We need this "$reader" callback to get a reference to // the items property inside collections. Otherwise, // we'd receive a copy instead of the reference. $reader = function & ($object, $property) { $value = & \Closure::bind(function & () use ($property) { return $this->$property; }, $object, $object)->__invoke(); return $value; }; $items =& $reader($target, 'items'); return $items[$key]; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/Synth.php
src/Mechanisms/HandleComponents/Synthesizers/Synth.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers; use Livewire\Mechanisms\HandleComponents\ComponentContext; abstract class Synth { function __construct( public ComponentContext $context, public $path, ) {} public static function getKey() { throw_unless( property_exists(static::class, 'key'), new \Exception('You need to define static $key property on: '.static::class) ); return static::$key; } abstract static function match($target); static function matchByType($type) { return false; } function get(&$target, $key) { if (is_array($target)) { return $target[$key] ?? null; } return $target->$key; } function __call($method, $params) { if ($method === 'dehydrate') { throw new \Exception('You must define a "dehydrate" method'); } if ($method === 'hydrate') { throw new \Exception('You must define a "hydrate" method'); } if ($method === 'hydrateFromType') { throw new \Exception('You must define a "hydrateFromType" method'); } if ($method === 'get') { throw new \Exception('This synth doesn\'t support getting properties: '.get_class($this)); } if ($method === 'set') { throw new \Exception('This synth doesn\'t support setting properties: '.get_class($this)); } if ($method === 'unset') { throw new \Exception('This synth doesn\'t support unsetting properties: '.get_class($this)); } if ($method === 'call') { throw new \Exception('This synth doesn\'t support calling methods: '.get_class($this)); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/IntSynth.php
src/Mechanisms/HandleComponents/Synthesizers/IntSynth.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers; // This synth exists solely to capture empty strings being set to integer properties... class IntSynth extends Synth { public static $key = 'int'; static function match($target) { return false; } static function matchByType($type) { return $type === 'int'; } static function hydrateFromType($type, $value) { if ($value === '' || $value === null) return null; if ((int) $value == $value) return (int) $value; return $value; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/StringableSynth.php
src/Mechanisms/HandleComponents/Synthesizers/StringableSynth.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers; use Illuminate\Support\Stringable; class StringableSynth extends Synth { public static $key = 'str'; static function match($target) { return $target instanceof Stringable; } function dehydrate($target) { return [$target->__toString(), []]; } function hydrate($value) { return str($value); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/FloatSynth.php
src/Mechanisms/HandleComponents/Synthesizers/FloatSynth.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers; // This synth exists solely to capture empty strings being set to float properties... class FloatSynth extends Synth { public static $key = 'float'; static function match($target) { return false; } static function matchByType($type) { return $type === 'float'; } static function hydrateFromType($type, $value) { if ($value === '' || $value === null) return null; if ((float) $value == $value) return (float) $value; return $value; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/StdClassSynth.php
src/Mechanisms/HandleComponents/Synthesizers/StdClassSynth.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers; use stdClass; class StdClassSynth extends Synth { public static $key = 'std'; static function match($target) { return $target instanceof stdClass; } function dehydrate($target, $dehydrateChild) { $data = (array) $target; foreach ($target as $key => $child) { $data[$key] = $dehydrateChild($key, $child); } return [$data, []]; } function hydrate($value, $meta, $hydrateChild) { $obj = new stdClass; foreach ($value as $key => $child) { $obj->$key = $hydrateChild($key, $child); } return $obj; } function set(&$target, $key, $value) { $target->$key = $value; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/CarbonSynth.php
src/Mechanisms/HandleComponents/Synthesizers/CarbonSynth.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers; use Carbon\CarbonImmutable; use DateTime; use Carbon\Carbon; use DateTimeImmutable; use DateTimeInterface; class CarbonSynth extends Synth { public static $types = [ 'native' => DateTime::class, 'nativeImmutable' => DateTimeImmutable::class, 'carbon' => Carbon::class, 'carbonImmutable' => CarbonImmutable::class, 'illuminate' => \Illuminate\Support\Carbon::class, ]; public static $key = 'cbn'; static function match($target) { foreach (static::$types as $type => $class) { if ($target instanceof $class) return true; } return false; } static function matchByType($type) { return is_subclass_of($type, DateTimeInterface::class); } function dehydrate($target) { return [ $target->format(DateTimeInterface::ATOM), ['type' => array_search(get_class($target), static::$types)], ]; } static function hydrateFromType($type, $value) { if ($value === '' || $value === null) return null; return new $type($value); } function hydrate($value, $meta) { if ($value === '' || $value === null) return null; return new static::$types[$meta['type']]($value); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/EnumSynth.php
src/Mechanisms/HandleComponents/Synthesizers/EnumSynth.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers; class EnumSynth extends Synth { public static $key = 'enm'; static function match($target) { return is_object($target) && is_subclass_of($target, 'BackedEnum'); } static function matchByType($type) { return is_subclass_of($type, 'BackedEnum'); } static function hydrateFromType($type, $value) { if ($value === '') return null; return $type::from($value); } function dehydrate($target) { return [ $target->value, ['class' => get_class($target)] ]; } function hydrate($value, $meta) { if ($value === null || $value === '') return null; $class = $meta['class']; return $class::from($value); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/Tests/IntSynthUnitTest.php
src/Mechanisms/HandleComponents/Synthesizers/Tests/IntSynthUnitTest.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers\Tests; use Livewire\Livewire; use Tests\TestComponent; class IntSynthUnitTest extends \Tests\TestCase { public function test_null_value_hydrated_returns_null() { Livewire::test(ComponentWithNullableInt::class) ->set('intField', null) ->assertSetStrict('intField', null); } public function test_int_value_hydrated_returns_int() { Livewire::test(ComponentWithInt::class) ->set('intField', 3) ->assertSetStrict('intField', 3); } public function test_string_value_hydrated_returns_int() { Livewire::test(ComponentWithInt::class) ->set('intField', '3') ->assertSetStrict('intField', 3) ->set('intField', '3.14') ->assertSetStrict('intField', 3); } public function test_float_value_hydrated_returns_int() { Livewire::test(ComponentWithInt::class) ->set('intField', 3.00) ->assertSetStrict('intField', 3) ->set('intField', 3.14) ->assertSetStrict('intField', 3); } public function test_can_hydrate_int_or_string() { Livewire::test(ComponentWithIntOrString::class) ->set('intOrStringField', 3) ->assertSetStrict('intOrStringField', 3) ->set('intOrStringField', 3.00) ->assertSetStrict('intOrStringField', 3) ->set('intOrStringField', 3.14) ->assertSetStrict('intOrStringField', 3) ->set('intOrStringField', '3') ->assertSetStrict('intOrStringField', 3) ->set('intOrStringField', '3.00') ->assertSetStrict('intOrStringField', 3) ->set('intOrStringField', '3.14') ->assertSetStrict('intOrStringField', '3.14') ->set('intOrStringField', 'foo') ->assertSetStrict('intOrStringField', 'foo') ->set('intOrStringField', null) ->assertSetStrict('intOrStringField', null); } } class ComponentWithNullableInt extends TestComponent { public ?int $intField = null; } class ComponentWithInt extends TestComponent { public int $intField; } class ComponentWithIntOrString extends TestComponent { public int|string $intOrStringField; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/Tests/DataBindingUnitTest.php
src/Mechanisms/HandleComponents/Synthesizers/Tests/DataBindingUnitTest.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers\Tests; use Tests\TestComponent; use Livewire\Livewire; class DataBindingUnitTest extends \Tests\TestCase { public function test_update_component_data() { $component = Livewire::test(DataBindingStub::class); $component->set('foo', 'bar'); $this->assertEquals('bar', $component->foo); } public function test_update_nested_component_data_inside_array() { $component = Livewire::test(DataBindingStub::class); $component->set('foo', []); $component->set('foo.0', 'bar'); $component->set('foo.bar', 'baz'); $this->assertEquals(['bar', 'bar' => 'baz'], $component->foo); } public function test_can_remove_an_array_from_an_array() { Livewire::test(new class extends TestComponent { public $tasks = [ [ 'id' => 123 ], [ 'id' => 456 ], ]; }) // We can simulate Livewire's removing an item from an array // by hardcoding "__rm__"... ->set('tasks.1', '__rm__') ->assertSetStrict('tasks', [['id' => 123]]) ; } } class DataBindingStub extends TestComponent { public $foo; public $bar; public $propertyWithHook; public $arrayProperty = ['foo', 'bar']; public function updatedPropertyWithHook($value) { $this->propertyWithHook = 'something else'; } public function changeFoo($value) { $this->foo = $value; } public function changeArrayPropertyOne($value) { $this->arrayProperty[1] = $value; } public function removeArrayPropertyOne() { unset($this->arrayProperty[1]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/Tests/CarbonSynthUnitTest.php
src/Mechanisms/HandleComponents/Synthesizers/Tests/CarbonSynthUnitTest.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers\Tests; use Carbon\Carbon; use Carbon\CarbonImmutable; use Livewire\Livewire; use Tests\TestComponent; class CarbonSynthUnitTest extends \Tests\TestCase { public function test_public_carbon_properties_can_be_cast() { $testable = Livewire::test(ComponentWithPublicCarbonCaster::class) ->updateProperty('date', '2024-02-14') ->assertSet('date', Carbon::parse('2024-02-14')); $this->expectException(\Exception::class); $testable->updateProperty('date', 'Bad Date'); } public function test_public_nullable_carbon_properties_can_be_cast() { $testable = Livewire::test(ComponentWithNullablePublicCarbonCaster::class) ->assertSetStrict('date', null) ->updateProperty('date', '2024-02-14') ->assertSet('date', Carbon::parse('2024-02-14')) ->updateProperty('date', '') ->assertSetStrict('date', null) ->updateProperty('date', null) ->assertSetStrict('date', null); $this->expectException(\Exception::class); $testable->updateProperty('date', 'Bad Date'); } public function test_public_carbon_immutable_properties_can_be_cast() { $testable = Livewire::test(ComponentWithNullablePublicCarbonImmutableCaster::class) ->assertSetStrict('date', null) ->updateProperty('date', '2024-02-14') ->assertSet('date', CarbonImmutable::parse('2024-02-14')) ->updateProperty('date', '') ->assertSetStrict('date', null) ->updateProperty('date', null) ->assertSetStrict('date', null); $this->expectException(\Exception::class); $testable->updateProperty('date', 'Bad Date'); } public function test_public_datetime_properties_can_be_cast() { $testable = Livewire::test(ComponentWithNullablePublicDateTimeCaster::class) ->assertSetStrict('date', null) ->updateProperty('date', '2024-02-14') ->assertSet('date', new \DateTime('2024-02-14')) ->updateProperty('date', '') ->assertSetStrict('date', null) ->updateProperty('date', null) ->assertSetStrict('date', null); $this->expectException(\Exception::class); $testable->updateProperty('date', 'Bad Date'); } public function test_public_datetime_immutable_properties_can_be_cast() { $testable = Livewire::test(ComponentWithNullablePublicDateTimeImmutableCaster::class) ->assertSetStrict('date', null) ->updateProperty('date', '2024-02-14') ->assertSet('date', new \DateTimeImmutable('2024-02-14')) ->updateProperty('date', '') ->assertSetStrict('date', null) ->updateProperty('date', null) ->assertSetStrict('date', null); $this->expectException(\Exception::class); $testable->updateProperty('date', 'Bad Date'); } } class ComponentWithPublicCarbonCaster extends TestComponent { public Carbon $date; } class ComponentWithNullablePublicCarbonCaster extends TestComponent { public ?Carbon $date = null; } class ComponentWithNullablePublicCarbonImmutableCaster extends TestComponent { public ?CarbonImmutable $date = null; } class ComponentWithNullablePublicDateTimeCaster extends TestComponent { public ?\DateTime $date = null; } class ComponentWithNullablePublicDateTimeImmutableCaster extends TestComponent { public ?\DateTimeImmutable $date = null; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/Tests/EnumUnitTest.php
src/Mechanisms/HandleComponents/Synthesizers/Tests/EnumUnitTest.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers\Tests; use Illuminate\Validation\Rule; use Livewire\Livewire; use Tests\TestComponent; use ValueError; class EnumUnitTest extends \Tests\TestCase { public function test_public_properties_can_be_cast() { Livewire::test(ComponentWithPublicEnumCasters::class) ->call('storeTypeOf') ->assertSetStrict('typeOf', TestingEnum::class) ->assertSetStrict('enum', TestingEnum::from('Be excellent to each other')); } public function test_nullable_public_property_can_be_cast() { $testable = Livewire::test(ComponentWithNullablePublicEnumCaster::class) ->assertSetStrict('status', null) ->updateProperty('status', 'Be excellent to each other') ->assertSetStrict('status', TestingEnum::TEST) ->updateProperty('status', '') ->assertSetStrict('status', null); $this->expectException(ValueError::class); $testable->updateProperty('status', 'Be excellent excellent to each other'); } public function test_an_enum_can_be_validated() { Livewire::test(ComponentWithValidatedEnum::class) ->call('save') ->assertHasErrors('enum') ->set('enum', ValidatedEnum::TEST->value) ->call('save') ->assertHasNoErrors(); } public function test_an_array_of_enums() { Livewire::test(ComponentWithEnumArray::class) ->set('list', [ValidatedEnum::TEST]) ->assertSet('list', [ValidatedEnum::TEST]) ->set('list', [ValidatedEnum::BAR]) ->assertSet('list', [ValidatedEnum::BAR]) ->set('list', [ValidatedEnum::BAR, ValidatedEnum::TEST]) ->assertSet('list', [ValidatedEnum::BAR, ValidatedEnum::TEST]) ->set('list', []) ->assertSet('list', []) ; } } enum TestingEnum: string { case TEST = 'Be excellent to each other'; } enum ValidatedEnum: string { case TEST = 'test'; case BAR = 'bar'; } class ComponentWithEnumArray extends TestComponent { public $list = []; } class ComponentWithPublicEnumCasters extends TestComponent { public $typeOf; public $enum; public function hydrate() { $this->enum = TestingEnum::TEST; } public function dehydrate() { $this->enum = TestingEnum::from($this->enum->value); } public function mount() { $this->enum = TestingEnum::TEST; } public function storeTypeOf() { $this->typeOf = get_class($this->enum); } } class ComponentWithNullablePublicEnumCaster extends TestComponent { public ?TestingEnum $status = null; } class ComponentWithValidatedEnum extends TestComponent { public ValidatedEnum $enum; public function rules() { return [ 'enum' => ['required', Rule::enum(ValidatedEnum::class)], ]; } public function save() { $validatedData = $this->validate(); // Check that the validated enum is still an Enum value if (!($this->enum instanceof ValidatedEnum)) { throw new \Exception('The type of Enum has been changed.'); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/Tests/FloatSynthUnitTest.php
src/Mechanisms/HandleComponents/Synthesizers/Tests/FloatSynthUnitTest.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers\Tests; use Livewire\Form; use Livewire\Livewire; use Tests\TestComponent; class FloatSynthUnitTest extends \Tests\TestCase { public function test_hydrated_component_with_null_value_returns_null() { Livewire::test(ComponentWithNullableFloat::class) ->set('floatField', null) ->assertSetStrict('floatField', null); } public function test_hydrated_component_with_empty_string_returns_null() { Livewire::test(ComponentWithNullableFloat::class) ->set('floatField', '') ->assertSetStrict('floatField', null); } public function test_hydrated_form_with_null_value_returns_null() { Livewire::test(FormComponentWithNullableFloat::class) ->set('form.floatField', null) ->assertSetStrict('form.floatField', null); } public function test_hydrated_form_with_empty_string_returns_null() { Livewire::test(FormComponentWithNullableFloat::class) ->set('form.floatField', '') ->assertSetStrict('form.floatField', null); } public function test_int_value_hydrated_returns_float() { Livewire::test(ComponentWithFloat::class) ->set('floatField', 3) ->assertSetStrict('floatField', 3.00); } public function test_string_value_hydrated_returns_float() { Livewire::test(ComponentWithFloat::class) ->set('floatField', '3') ->assertSetStrict('floatField', 3.00) ->set('floatField', '3.14') ->assertSetStrict('floatField', 3.14); } public function test_float_value_hydrated_returns_float() { Livewire::test(ComponentWithFloat::class) ->set('floatField', 3.00) ->assertSetStrict('floatField', 3.00) ->set('floatField', 3.14) ->assertSetStrict('floatField', 3.14); } public function test_can_hydrate_float_or_string() { Livewire::test(ComponentWithFloatOrString::class) ->set('floatOrStringField', 3) ->assertSetStrict('floatOrStringField', 3.00) ->set('floatOrStringField', 3.00) ->assertSetStrict('floatOrStringField', 3.00) ->set('floatOrStringField', 3.14) ->assertSetStrict('floatOrStringField', 3.14) ->set('floatOrStringField', '3') ->assertSetStrict('floatOrStringField', 3.00) ->set('floatOrStringField', '3.00') ->assertSetStrict('floatOrStringField', 3.00) ->set('floatOrStringField', '3.14') ->assertSetStrict('floatOrStringField', 3.14) ->set('floatOrStringField', 'foo') ->assertSetStrict('floatOrStringField', 'foo') ->set('floatOrStringField', null) ->assertSetStrict('floatOrStringField', null); } } class ComponentWithNullableFloat extends TestComponent { public ?float $floatField = null; } class ComponentWithFloat extends TestComponent { public float $floatField; } class ComponentWithFloatOrString extends TestComponent { public float|string $floatOrStringField; } class FormComponentWithNullableFloat extends TestComponent { public FormWithNullableFloat $form; } class FormWithNullableFloat extends Form { public ?float $floatField = null; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleComponents/Synthesizers/Tests/TypedPropertiesUnitTest.php
src/Mechanisms/HandleComponents/Synthesizers/Tests/TypedPropertiesUnitTest.php
<?php namespace Livewire\Mechanisms\HandleComponents\Synthesizers\Tests; use Livewire\Component; use Livewire\Livewire; class TypedPropertiesUnitTest extends \Tests\TestCase { public function test_can_set_uninitialized_typed_properties() { $testMessage = 'hello world'; Livewire::test(ComponentWithUninitializedTypedProperty::class) ->set('message', $testMessage) ->assertSetStrict('message', $testMessage); } } class ComponentWithUninitializedTypedProperty extends Component { public string $message; public function render() { return <<<'HTML' <div> {{ var_dump(isset($this->message)) }} </div> HTML; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/CompileLivewireTags/LivewireTagPrecompiler.php
src/Mechanisms/CompileLivewireTags/LivewireTagPrecompiler.php
<?php namespace Livewire\Mechanisms\CompileLivewireTags; use Illuminate\View\Compilers\ComponentTagCompiler; use Livewire\Drawer\Regexes; use Livewire\Exceptions\ComponentAttributeMissingOnDynamicComponentException; class LivewireTagPrecompiler extends ComponentTagCompiler { public function __invoke($value) { $value = $this->compileSlotTags($value); $value = $this->compileSlotClosingTags($value); $value = $this->compileOpeningTags($value); $value = $this->compileClosingTags($value); $value = $this->compileSelfClosingTags($value); return $value; } public function compileSlotTags($value) { $pattern = '/'.Regexes::$slotOpeningTag.'/x'; return preg_replace_callback($pattern, function (array $matches) { $name = $matches['name'] ?? 'default'; $output = ''; $output .= '<?php if (isset($__slotName)) { $__slotNameOriginal = $__slotName; } ?>' . PHP_EOL; $output .= '<?php $__slotName = '.$name.'; ?>' . PHP_EOL; $output .= '<?php ob_start(); ?>' . PHP_EOL; return $output; }, $value); } public function compileSlotClosingTags($value) { $pattern = '/'.Regexes::$slotClosingTag.'/x'; return preg_replace_callback($pattern, function (array $matches) { $output = ''; $output .= '<?php $__slotContent = ob_get_clean(); ?>' . PHP_EOL; $output .= '<?php $__slots[$__slotName] = $__slotContent; ?>' . PHP_EOL; $output .= '<?php if (isset($__slotNameOriginal)) { $__slotName = $__slotNameOriginal; unset($__slotNameOriginal); } ?>' . PHP_EOL; return $output; }, $value); } public function compileOpeningTags($value) { $pattern = '/'.Regexes::$livewireOpeningTag.'/x'; return preg_replace_callback($pattern, function (array $matches) { $attributes = $this->getAttributesFromAttributeString($matches['attributes']); $keys = array_keys($attributes); $values = array_values($attributes); $attributesCount = count($attributes); for ($i=0; $i < $attributesCount; $i++) { if ($keys[$i] === ':' && $values[$i] === 'true') { if (isset($values[$i + 1]) && $values[$i + 1] === 'true') { $attributes[$keys[$i + 1]] = '$'.$keys[$i + 1]; unset($attributes[':']); } } } $component = $matches[1]; if ($component === 'styles') return '@livewireStyles'; if ($component === 'scripts') return '@livewireScripts'; if ($component === 'dynamic-component' || $component === 'is') { if (! isset($attributes['component']) && ! isset($attributes['is'])) { throw new ComponentAttributeMissingOnDynamicComponentException; } // Does not need quotes as resolved with quotes already. $component = $attributes['component'] ?? $attributes['is']; unset($attributes['component'], $attributes['is']); } else { // Add single quotes to the component name to compile it as string in quotes $component = "'{$component}'"; } $keyInnerContent = null; if (isset($attributes['key']) || isset($attributes['wire:key'])) { $keyInnerContent = $attributes['key'] ?? $attributes['wire:key']; unset($attributes['key'], $attributes['wire:key']); } else { $keyInnerContent = 'null'; } $attributeInnerContent = '[' . $this->attributesToString($attributes, escapeBound: false) . ']'; $output = ''; $output .= '<?php if (isset($__component)) { $__componentOriginal = $__component; } ?>' . PHP_EOL; $output .= '<?php if (isset($__key)) { $__keyOriginal = $__key; } ?>' . PHP_EOL; $output .= '<?php if (isset($__attributes)) { $__attributesOriginal = $__attributes; } ?>' . PHP_EOL; $output .= '<?php if (isset($__slots)) { $__slotsOriginal = $__slots; } ?>' . PHP_EOL; $output .= '<?php $__component = '.$component.'; ?>' . PHP_EOL; $output .= '<?php $__key = '.$keyInnerContent.'; ?>' . PHP_EOL; $output .= '<?php $__attributes = '.$attributeInnerContent.'; ?>' . PHP_EOL; $output .= '<?php $__slots = []; ?>' . PHP_EOL; $output .= '<?php ob_start(); ?>' . PHP_EOL; return $output; }, $value); } public function compileClosingTags($value) { $pattern = '/'.Regexes::$livewireClosingTag.'/x'; return preg_replace_callback($pattern, function (array $matches) { $output = ''; $output .= "<?php \$__slots['default'] = ob_get_clean(); ?>" . PHP_EOL; $output .= '@livewire($__component, $__attributes, key($__key), $__slots ?? [])' . PHP_EOL; $output .= '<?php if (isset($__componentOriginal)) { $__component = $__componentOriginal; unset($__componentOriginal); } ?>' . PHP_EOL; $output .= '<?php if (isset($__keyOriginal)) { $__key = $__keyOriginal; unset($__keyOriginal); } ?>' . PHP_EOL; $output .= '<?php if (isset($__attributesOriginal)) { $__attributes = $__attributesOriginal; unset($__attributesOriginal); } ?>' . PHP_EOL; $output .= '<?php if (isset($__slotsOriginal)) { $__slots = $__slotsOriginal; unset($__slotsOriginal); } ?>' . PHP_EOL; return $output; }, $value); } public function compileSelfClosingTags($value) { $pattern = '/'.Regexes::$livewireOpeningTagOrSelfClosingTag.'/x'; return preg_replace_callback($pattern, function (array $matches) { $attributes = $this->getAttributesFromAttributeString($matches['attributes']); $keys = array_keys($attributes); $values = array_values($attributes); $attributesCount = count($attributes); for ($i=0; $i < $attributesCount; $i++) { if ($keys[$i] === ':' && $values[$i] === 'true') { if (isset($values[$i + 1]) && $values[$i + 1] === 'true') { $attributes[$keys[$i + 1]] = '$'.$keys[$i + 1]; unset($attributes[':']); } } } $component = $matches[1]; if ($component === 'styles') return '@livewireStyles'; if ($component === 'scripts') return '@livewireScripts'; if ($component === 'dynamic-component' || $component === 'is') { if (! isset($attributes['component']) && ! isset($attributes['is'])) { throw new ComponentAttributeMissingOnDynamicComponentException; } // Does not need quotes as resolved with quotes already. $component = $attributes['component'] ?? $attributes['is']; unset($attributes['component'], $attributes['is']); } else { // Add single quotes to the component name to compile it as string in quotes $component = "'{$component}'"; } if (isset($attributes['key']) || isset($attributes['wire:key'])) { $key = $attributes['key'] ?? $attributes['wire:key']; unset($attributes['key'], $attributes['wire:key']); return "@livewire({$component}, [".$this->attributesToString($attributes, escapeBound: false)."], key({$key}))"; } return "@livewire({$component}, [".$this->attributesToString($attributes, escapeBound: false).'])'; }, $value); } protected function attributesToString(array $attributes, $escapeBound = true) { return collect($attributes) ->map(function (string $value, string $attribute) use ($escapeBound) { return $escapeBound && isset($this->boundAttributes[$attribute]) && $value !== 'true' && ! is_numeric($value) ? "'{$attribute}' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute({$value})" : "'{$attribute}' => {$value}"; }) ->implode(','); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/CompileLivewireTags/CompileLivewireTags.php
src/Mechanisms/CompileLivewireTags/CompileLivewireTags.php
<?php namespace Livewire\Mechanisms\CompileLivewireTags; use Livewire\Mechanisms\Mechanism; class CompileLivewireTags extends Mechanism { public function boot() { app('blade.compiler')->precompiler(new LivewireTagPrecompiler); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/CompileLivewireTags/UnitTest.php
src/Mechanisms/CompileLivewireTags/UnitTest.php
<?php namespace Livewire\Mechanisms\CompileLivewireTags; use Illuminate\Support\Facades\Blade; use Livewire\Livewire; class UnitTest extends \Tests\TestCase { public function test_can_compile_livewire_self_closing_tags() { Livewire::component('foo', new class extends \Livewire\Component { public function render() { return '<div>noop</div>'; } }); $output = Blade::render(' <livewire:foo /> '); $this->assertStringNotContainsString('<livewire:', $output); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/PersistentMiddleware/BrowserTest.php
src/Mechanisms/PersistentMiddleware/BrowserTest.php
<?php namespace Livewire\Mechanisms\PersistentMiddleware; use Closure; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as AuthUser; use Illuminate\Foundation\Http\Kernel; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Route; use Livewire\Component as BaseComponent; use Livewire\Livewire; use Sushi\Sushi; use Symfony\Component\HttpFoundation\Response; use Tests\BrowserTestCase; class BrowserTest extends BrowserTestCase { protected function getEnvironmentSetUp($app) { parent::getEnvironmentSetUp($app); $app['config']->set('auth.providers.users.model', User::class); } protected function resolveApplicationHttpKernel($app) { $app->singleton(\Illuminate\Contracts\Http\Kernel::class, HttpKernel::class); } public static function tweakApplicationHook() { return function() { Livewire::addPersistentMiddleware([AllowListedMiddleware::class, IsBanned::class]); // Overwrite the default route for these tests, so the middleware is included Route::get('livewire-dusk/{component}', function ($component) { $class = urldecode($component); return app()->call(app('livewire')->new($class)); })->middleware(['web', AllowListedMiddleware::class, BlockListedMiddleware::class]); Route::get('/force-login/{userId}', function ($userId) { Auth::login(User::find($userId)); return 'You\'re logged in.'; })->middleware('web'); Route::get('/force-logout', function () { Auth::logout(); return 'You\'re logged out.'; })->middleware('web'); Route::get('/with-authentication/livewire-dusk/{component}', function ($component) { $class = urldecode($component); return app()->call(app('livewire')->new($class)); })->middleware(['web', 'auth']); Route::get('/with-redirects/livewire-dusk/{component}', function ($component) { $class = urldecode($component); return app()->call(app('livewire')->new($class)); })->middleware(['web', 'auth', IsBanned::class]); Gate::policy(Post::class, PostPolicy::class); Route::get('/with-authorization/{post}/livewire-dusk/{component}', function (Post $post, $component) { $class = urldecode($component); return app()->call(new $class); })->middleware(['web', 'auth', 'can:update,post']); Route::get('/with-authorization/{post}/inline-auth', Component::class) ->middleware(['web', 'auth', 'can:update,post']); }; } public function test_that_persistent_middleware_is_applied_to_subsequent_livewire_requests() { // @todo: Copy implementation from V2 for persistent middleware and ensure localisation and subdirectory hosting are supported. https://github.com/livewire/livewire/pull/5490 Livewire::visit([Component::class, 'child' => NestedComponent::class]) // See allow-listed middleware from original request. ->assertSeeIn('@middleware', json_encode([AllowListedMiddleware::class, BlockListedMiddleware::class])) ->waitForLivewire()->click('@refresh') // See that the original request middleware was re-applied. ->assertSeeIn('@middleware', json_encode([AllowListedMiddleware::class])) ->waitForLivewire()->click('@showNested') // Even to nested components shown AFTER the first load. ->assertSeeIn('@middleware', json_encode([AllowListedMiddleware::class])) ->assertSeeIn('@nested-middleware', json_encode([AllowListedMiddleware::class])) ->waitForLivewire()->click('@refreshNested') // Make sure they are still applied when stand-alone requests are made to that component. ->assertSeeIn('@middleware', json_encode([AllowListedMiddleware::class])) ->assertSeeIn('@nested-middleware', json_encode([AllowListedMiddleware::class])) ; } public function test_that_authentication_middleware_is_re_applied() { Livewire::visit(Component::class) ->visit('/with-authentication/livewire-dusk/'.urlencode(Component::class)) ->assertDontSee('Protected Content') ->visit('/force-login/1') ->visit('/with-authentication/livewire-dusk/'.urlencode(Component::class)) ->waitForLivewireToLoad() ->assertSee('Protected Content') // We're going to make a fetch request, but store the request payload // so we can replay it from a different page. ->tap(function ($b) { $script = <<<'JS' let unDecoratedFetch = window.fetch let decoratedFetch = (...args) => { window.localStorage.setItem( 'lastFetchArgs', JSON.stringify(args), ) return unDecoratedFetch(...args) } window.fetch = decoratedFetch JS; $b->script($script); }) ->waitForLivewire()->click('@changeProtected') ->assertDontSee('Protected Content') ->assertSee('Still Secure Content') // Now we logout. ->visit('/force-logout') // Now we try and re-run the request payload, expecting that // the "auth" middleware will be applied, recognize we've // logged out and throw an error in the response. ->tap(function ($b) { $script = <<<'JS' let args = JSON.parse(localStorage.getItem('lastFetchArgs')) window.controller = new AbortController() args[1].signal = window.controller.signal window.fetch(...args).then(i => i.text()).then(response => { document.body.textContent = 'response-ready: '+JSON.stringify(response) }) JS; $b->script($script); }) ->waitForText('response-ready: ') ->assertDontSee('Protected Content'); ; } public function test_that_authorization_middleware_is_re_applied() { Livewire::visit(Component::class) ->visit('/with-authorization/1/livewire-dusk/'.urlencode(Component::class)) ->assertDontSee('Protected Content') ->visit('/force-login/1') ->visit('/with-authorization/1/livewire-dusk/'.urlencode(Component::class)) ->assertSee('Protected Content') ->waitForLivewireToLoad() ->tap(function ($b) { $script = <<<'JS' let unDecoratedFetch = window.fetch let decoratedFetch = (...args) => { window.localStorage.setItem( 'lastFetchArgs', JSON.stringify(args), ) return unDecoratedFetch(...args) } window.fetch = decoratedFetch JS; $b->script($script); }) ->waitForLivewire()->click('@changeProtected') ->assertDontSee('Protected Content') ->assertSee('Still Secure Content') ->visit('/force-login/2') ->tap(function ($b) { $script = <<<'JS' let args = JSON.parse(localStorage.getItem('lastFetchArgs')) window.controller = new AbortController() args[1].signal = window.controller.signal window.fetch(...args).then(i => i.text()).then(response => { document.body.textContent = 'response-ready: '+JSON.stringify(response) }) JS; $b->script($script); }) ->waitForText('response-ready: ') ->assertDontSee('Protected Content') ; } public function test_that_persistent_middleware_redirects_on_subsequent_requests() { Livewire::visit(Component::class) ->tap(function () { User::where('id', 1)->update(['banned' => false]); // Reset the user. Sometimes it's cached(?. }) ->visit('/force-login/1') ->visit('/with-redirects/livewire-dusk/' . urlencode(Component::class)) ->assertSee('Protected Content') ->tap(function () { User::where('id', 1)->update(['banned' => true]); }) ->waitForLivewire() ->click('@refresh') ->assertPathIs('/force-logout') ; } public function test_that_authorization_middleware_is_re_applied_on_page_components() { // This test relies on "app('router')->subsituteImplicitBindingsUsing()"... if (app()->version() < '10.37.1') { $this->markTestSkipped(); } Livewire::visit(Component::class) ->visit('/with-authorization/1/inline-auth') ->assertDontSee('Protected Content') ->visit('/force-login/1') ->visit('/with-authorization/1/inline-auth') ->assertSee('Protected Content') ->waitForLivewireToLoad() ->tap(function ($b) { $script = <<<'JS' let unDecoratedFetch = window.fetch let decoratedFetch = (...args) => { window.localStorage.setItem( 'lastFetchArgs', JSON.stringify(args), ) return unDecoratedFetch(...args) } window.fetch = decoratedFetch JS; $b->script($script); }) ->waitForLivewire()->click('@changeProtected') ->assertDontSee('Protected Content') ->assertSee('Still Secure Content') ->visit('/force-login/2') ->tap(function ($b) { $script = <<<'JS' let args = JSON.parse(localStorage.getItem('lastFetchArgs')) window.controller = new AbortController() args[1].signal = window.controller.signal window.fetch(...args).then(i => i.text()).then(response => { document.body.textContent = 'response-ready: '+JSON.stringify(response) }) JS; $b->script($script); }) ->waitForText('response-ready: ') ->assertDontSee('Protected Content') ; } } class HttpKernel extends Kernel { /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \Illuminate\Foundation\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ]; /** * The application's route middleware groups. * * @var array */ protected $middlewareGroups = [ 'web' => [ \Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; /** * The application's route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \Orchestra\Testbench\Http\Middleware\RedirectIfAuthenticated::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, ]; /** * The priority-sorted list of middleware. * * This forces non-global middleware to always be in the given order. * * @var array */ protected $middlewarePriority = [ \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \Illuminate\Auth\Middleware\Authenticate::class, \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \Illuminate\Auth\Middleware\Authorize::class, ]; } class Component extends BaseComponent { public static $loggedMiddleware = []; public $middleware = []; public $showNested = false; public $changeProtected = false; public function mount(Post $post) { // } public function showNestedComponent() { $this->showNested = true; } public function toggleProtected() { $this->changeProtected = ! $this->changeProtected; } public function render() { $this->middleware = static::$loggedMiddleware; return <<<'HTML' <div> <span dusk="middleware">@json($middleware)</span> <button wire:click="$refresh" dusk="refresh">Refresh</button> <button wire:click="toggleProtected" dusk="changeProtected">Change Protected</button> <button wire:click="showNestedComponent" dusk="showNested">Show Nested</button> <h1> @unless($changeProtected) Protected Content @else Still Secure Content @endunless </h1> @if ($showNested) @livewire(\Livewire\Mechanisms\PersistentMiddleware\NestedComponent::class) @endif </div> HTML; } } class NestedComponent extends BaseComponent { public $middleware = []; public function render() { $this->middleware = Component::$loggedMiddleware; return <<<'HTML' <div> <span dusk="nested-middleware">@json($middleware)</span> <button wire:click="$refresh" dusk="refreshNested">Refresh</button> </div> HTML; } } class AllowListedMiddleware { public function handle(Request $request, Closure $next): Response { Component::$loggedMiddleware[] = static::class; return $next($request); } } class BlockListedMiddleware { public function handle(Request $request, Closure $next): Response { Component::$loggedMiddleware[] = static::class; return $next($request); } } class User extends AuthUser { use Sushi; protected $fillable = ['banned']; public function posts() { return $this->hasMany(Post::class); } protected $rows = [ [ 'id' => 1, 'name' => 'First User', 'email' => 'first@laravel-livewire.com', 'password' => '', 'banned' => false, ], [ 'id' => 2, 'name' => 'Second user', 'email' => 'second@laravel-livewire.com', 'password' => '', 'banned' => false, ], ]; } class Post extends Model { use Sushi; public function user() { return $this->belongsTo(User::class); } protected $rows = [ ['title' => 'First', 'user_id' => 1], ['title' => 'Second', 'user_id' => 2], ]; } class PostPolicy { public function update(User $user, Post $post) { return (int) $post->user_id === (int) $user->id; } } class IsBanned { public function handle(Request $request, Closure $next): Response { if ($request->user()->banned) { return redirect('/force-logout'); } return $next($request); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/PersistentMiddleware/UnitTest.php
src/Mechanisms/PersistentMiddleware/UnitTest.php
<?php namespace Livewire\Mechanisms\PersistentMiddleware; use Illuminate\Support\Facades\Facade; use Livewire\Livewire; class UnitTest extends \LegacyTests\Unit\TestCase { public function test_it_does_not_have_persistent_middleware_memory_leak_when_adding_middleware() { $base = Livewire::getPersistentMiddleware(); Livewire::addPersistentMiddleware('MyMiddleware'); $config = $this->app['config']; $this->app->forgetInstances(); $this->app->forgetScopedInstances(); Facade::clearResolvedInstances(); // Need to rebind these for the testcase cleanup to work. $this->app->instance('app', $this->app); $this->app->instance('config', $config); // It hangs around because it is a static variable, so we do expect // it to still exist here. $this->assertSame([ ...$base, 'MyMiddleware', ], Livewire::getPersistentMiddleware()); Livewire::addPersistentMiddleware('MyMiddleware'); $this->assertSame([ ...$base, 'MyMiddleware', ], Livewire::getPersistentMiddleware()); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/PersistentMiddleware/PersistentMiddleware.php
src/Mechanisms/PersistentMiddleware/PersistentMiddleware.php
<?php namespace Livewire\Mechanisms\PersistentMiddleware; use Illuminate\Routing\Router; use Livewire\Mechanisms\Mechanism; use function Livewire\on; use Illuminate\Support\Str; use Livewire\Drawer\Utils; use Livewire\Mechanisms\HandleRequests\HandleRequests; class PersistentMiddleware extends Mechanism { protected static $persistentMiddleware = [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, \Laravel\Jetstream\Http\Middleware\AuthenticateSession::class, \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \App\Http\Middleware\RedirectIfAuthenticated::class, \Illuminate\Auth\Middleware\Authenticate::class, \Illuminate\Auth\Middleware\Authorize::class, \App\Http\Middleware\Authenticate::class, ]; protected $path; protected $method; function boot() { on('dehydrate', function ($component, $context) { [$path, $method] = $this->extractPathAndMethodFromRequest(); $context->addMemo('path', $path); $context->addMemo('method', $method); }); on('snapshot-verified', function ($snapshot) { // Only apply middleware to requests hitting the Livewire update endpoint, and not any fake requests such as a test. if (! app(HandleRequests::class)->isLivewireRoute()) return; $this->extractPathAndMethodFromSnapshot($snapshot); $this->applyPersistentMiddleware(); }); on('flush-state', function() { // Only flush these at the end of a full request, so that child components have access to this data. $this->path = null; $this->method = null; }); } function addPersistentMiddleware($middleware) { static::$persistentMiddleware = Router::uniqueMiddleware(array_merge(static::$persistentMiddleware, (array) $middleware)); } function setPersistentMiddleware($middleware) { static::$persistentMiddleware = Router::uniqueMiddleware((array) $middleware); } function getPersistentMiddleware() { return static::$persistentMiddleware; } protected function extractPathAndMethodFromRequest() { if (app(HandleRequests::class)->isLivewireRoute()) { return [$this->path, $this->method]; } return [request()->path(), request()->method()]; } protected function extractPathAndMethodFromSnapshot($snapshot) { if ( ! isset($snapshot['memo']['path']) || ! isset($snapshot['memo']['method']) ) return; // Store these locally, so dynamically added child components can use this data. $this->path = $snapshot['memo']['path']; $this->method = $snapshot['memo']['method']; } protected function applyPersistentMiddleware() { $request = $this->makeFakeRequest(); $middleware = $this->getApplicablePersistentMiddleware($request); // Only send through pipeline if there are middleware found if (is_null($middleware)) return; Utils::applyMiddleware($request, $middleware); } protected function makeFakeRequest() { $originalPath = $this->formatPath($this->path); $originalMethod = $this->method; $currentPath = $this->formatPath(request()->path()); // Clone server bag to ensure changes below don't overwrite the original. $serverBag = clone request()->server; // Replace the Livewire endpoint path with the path from the original request. $serverBag->set( 'REQUEST_URI', str_replace($currentPath, $originalPath, $serverBag->get('REQUEST_URI')) ); $serverBag->set('REQUEST_METHOD', $originalMethod); /** * Make the fake request from the current request with path and method changed so * all other request data, such as headers, are available in the fake request, * but merge in the new server bag with the updated `REQUEST_URI`. */ $request = request()->duplicate( server: $serverBag->all() ); return $request; } protected function formatPath($path) { return '/' . ltrim($path, '/'); } protected function getApplicablePersistentMiddleware($request) { $route = $this->getRouteFromRequest($request); if (! $route) return []; $middleware = app('router')->gatherRouteMiddleware($route); return $this->filterMiddlewareByPersistentMiddleware($middleware); } protected function getRouteFromRequest($request) { $route = app('router')->getRoutes()->match($request); $request->setRouteResolver(fn() => $route); return $route; } protected function filterMiddlewareByPersistentMiddleware($middleware) { $middleware = collect($middleware); $persistentMiddleware = collect(app(PersistentMiddleware::class)->getPersistentMiddleware()); return $middleware ->filter(function ($value, $key) use ($persistentMiddleware) { return $persistentMiddleware->contains(function($iValue, $iKey) use ($value) { // Some middlewares can be closures. if (! is_string($value)) return false; // Ensure any middleware arguments aren't included in the comparison return Str::before($value, ':') == $iValue; }); }) ->values() ->all(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/FrontendAssets/FrontendAssets.php
src/Mechanisms/FrontendAssets/FrontendAssets.php
<?php namespace Livewire\Mechanisms\FrontendAssets; use Livewire\Drawer\Utils; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Blade; use Livewire\Mechanisms\Mechanism; use Livewire\Mechanisms\HandleRequests\EndpointResolver; use function Livewire\on; class FrontendAssets extends Mechanism { public $hasRenderedScripts = false; public $hasRenderedStyles = false; public $javaScriptRoute; public $scriptTagAttributes = []; public function boot() { app($this::class)->setScriptRoute(function ($handle) { return config('app.debug') ? Route::get(EndpointResolver::scriptPath(minified: false), $handle) : Route::get(EndpointResolver::scriptPath(minified: true), $handle); }); Route::get(EndpointResolver::mapPath(csp: false), [static::class, 'maps']); Route::get(EndpointResolver::mapPath(csp: true), [static::class, 'cspMaps']); Blade::directive('livewireScripts', [static::class, 'livewireScripts']); Blade::directive('livewireScriptConfig', [static::class, 'livewireScriptConfig']); Blade::directive('livewireStyles', [static::class, 'livewireStyles']); app('livewire')->provide(function() { $this->publishes( [ __DIR__.'/../../../dist' => public_path('vendor/livewire'), ], 'livewire:assets', ); }); on('flush-state', function () { $instance = app(static::class); $instance->hasRenderedScripts = false; $instance->hasRenderedStyles = false; }); } function useScriptTagAttributes($attributes) { $this->scriptTagAttributes = array_merge($this->scriptTagAttributes, $attributes); } function setScriptRoute($callback) { $route = $callback([self::class, 'returnJavaScriptAsFile']); $this->javaScriptRoute = $route; } public static function livewireScripts($expression) { return '{!! \Livewire\Mechanisms\FrontendAssets\FrontendAssets::scripts('.$expression.') !!}'; } public static function livewireScriptConfig($expression) { return '{!! \Livewire\Mechanisms\FrontendAssets\FrontendAssets::scriptConfig('.$expression.') !!}'; } public static function livewireStyles($expression) { return '{!! \Livewire\Mechanisms\FrontendAssets\FrontendAssets::styles('.$expression.') !!}'; } public function returnJavaScriptAsFile() { $isCsp = app('livewire')->isCspSafe(); if (config('app.debug')) { $file = $isCsp ? 'livewire.csp.js' : 'livewire.js'; } else { $file = $isCsp ? 'livewire.csp.min.js' : 'livewire.min.js'; } return Utils::pretendResponseIsFile(__DIR__.'/../../../dist/'.$file); } public function maps() { $file = app('livewire')->isCspSafe() ? 'livewire.csp.min.js.map' : 'livewire.min.js.map'; return Utils::pretendResponseIsFile(__DIR__.'/../../../dist/'.$file); } public function cspMaps() { return Utils::pretendResponseIsFile(__DIR__.'/../../../dist/livewire.csp.min.js.map'); } /** * @return string */ public static function styles($options = []) { app(static::class)->hasRenderedStyles = true; $nonce = isset($options['nonce']) ? "nonce=\"{$options['nonce']}\" data-livewire-style" : ''; $progressBarColor = config('livewire.navigate.progress_bar_color', '#2299dd'); // Note: the attribute selectors are "doubled" so that they don't get overriden when Tailwind's CDN loads a script tag // BELOW the one Livewire injects... $html = <<<HTML <!-- Livewire Styles --> <style {$nonce}> [wire\:loading][wire\:loading], [wire\:loading\.delay][wire\:loading\.delay], [wire\:loading\.list-item][wire\:loading\.list-item], [wire\:loading\.inline-block][wire\:loading\.inline-block], [wire\:loading\.inline][wire\:loading\.inline], [wire\:loading\.block][wire\:loading\.block], [wire\:loading\.flex][wire\:loading\.flex], [wire\:loading\.table][wire\:loading\.table], [wire\:loading\.grid][wire\:loading\.grid], [wire\:loading\.inline-flex][wire\:loading\.inline-flex] { display: none; } [wire\:loading\.delay\.none][wire\:loading\.delay\.none], [wire\:loading\.delay\.shortest][wire\:loading\.delay\.shortest], [wire\:loading\.delay\.shorter][wire\:loading\.delay\.shorter], [wire\:loading\.delay\.short][wire\:loading\.delay\.short], [wire\:loading\.delay\.default][wire\:loading\.delay\.default], [wire\:loading\.delay\.long][wire\:loading\.delay\.long], [wire\:loading\.delay\.longer][wire\:loading\.delay\.longer], [wire\:loading\.delay\.longest][wire\:loading\.delay\.longest] { display: none; } [wire\:offline][wire\:offline] { display: none; } [wire\:dirty]:not(textarea):not(input):not(select) { display: none; } :root { --livewire-progress-bar-color: {$progressBarColor}; } [x-cloak] { display: none !important; } [wire\:cloak] { display: none !important; } dialog#livewire-error::backdrop { background-color: rgba(0, 0, 0, .6); } </style> HTML; return static::minify($html); } /** * @return string */ public static function scripts($options = []) { app(static::class)->hasRenderedScripts = true; $debug = config('app.debug'); $scripts = static::js($options); // HTML Label. $html = $debug ? ['<!-- Livewire Scripts -->'] : []; $html[] = $scripts; return implode("\n", $html); } public static function js($options) { // Use the default endpoint... $url = app(static::class)->javaScriptRoute->uri; // Use the configured one... $url = config('livewire.asset_url') ?: $url; // Use the legacy passed in one... $url = $options['asset_url'] ?? $url; // Use the new passed in one... $url = $options['url'] ?? $url; $url = rtrim($url, '/'); $url = (string) str($url)->when(! str($url)->isUrl(), fn($url) => $url->start('/')); // Add the build manifest hash to it... $manifest = json_decode(file_get_contents(__DIR__.'/../../../dist/manifest.json'), true); $versionHash = $manifest['/livewire.js']; $url = "{$url}?id={$versionHash}"; $token = app()->has('session.store') ? csrf_token() : ''; $assetWarning = null; $nonce = isset($options['nonce']) ? "nonce=\"{$options['nonce']}\"" : ''; [$url, $assetWarning] = static::usePublishedAssetsIfAvailable($url, $manifest, $nonce); $progressBar = config('livewire.navigate.show_progress_bar', true) ? '' : 'data-no-progress-bar'; $uriPrefix = app('livewire')->getUriPrefix(); $updateUri = app('livewire')->getUpdateUri(); $extraAttributes = Utils::stringifyHtmlAttributes( app(static::class)->scriptTagAttributes, ); return <<<HTML {$assetWarning}<script src="{$url}" {$nonce} {$progressBar} data-csrf="{$token}" data-uri-prefix="{$uriPrefix}" data-update-uri="{$updateUri}" {$extraAttributes}></script> HTML; } public static function scriptConfig($options = []) { app(static::class)->hasRenderedScripts = true; $nonce = isset($options['nonce']) ? " nonce=\"{$options['nonce']}\"" : ''; $progressBar = config('livewire.navigate.show_progress_bar', true) ? '' : 'data-no-progress-bar'; $attributes = json_encode([ 'csrf' => app()->has('session.store') ? csrf_token() : '', 'uri' => app('livewire')->getUpdateUri(), 'uriPrefix' => app('livewire')->getUriPrefix(), 'progressBar' => $progressBar, 'nonce' => isset($options['nonce']) ? $options['nonce'] : '', ]); return <<<HTML <script{$nonce} data-navigate-once="true">window.livewireScriptConfig = {$attributes};</script> HTML; } protected static function usePublishedAssetsIfAvailable($url, $manifest, $nonce) { $assetWarning = null; // Check to see if static assets have been published... if (! file_exists(public_path('vendor/livewire/manifest.json'))) { return [$url, $assetWarning]; } $publishedManifest = json_decode(file_get_contents(public_path('vendor/livewire/manifest.json')), true); $versionedFileName = $publishedManifest['/livewire.js']; $isCsp = app('livewire')->isCspSafe(); if (config('app.debug')) { $fileName = $isCsp ? '/livewire.csp.js' : '/livewire.js'; } else { $fileName = $isCsp ? '/livewire.csp.min.js' : '/livewire.min.js'; } $versionedFileName = "{$fileName}?id={$versionedFileName}"; $assertUrl = config('livewire.asset_url') ?? (app('livewire')->isRunningServerless() ? rtrim(config('app.asset_url'), '/')."/vendor/livewire$versionedFileName" : url("vendor/livewire{$versionedFileName}") ); $url = $assertUrl; if ($manifest !== $publishedManifest) { $assetWarning = <<<HTML <script {$nonce}> console.warn('Livewire: The published Livewire assets are out of date\\n See: https://livewire.laravel.com/docs/installation#publishing-livewires-frontend-assets') </script>\n HTML; } return [$url, $assetWarning]; } protected static function minify($subject) { return preg_replace('~(\v|\t|\s{2,})~m', '', $subject); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/FrontendAssets/BrowserTest.php
src/Mechanisms/FrontendAssets/BrowserTest.php
<?php namespace Livewire\Mechanisms\FrontendAssets; use Illuminate\Support\Facades\Route; use Livewire\Livewire; use Tests\TestComponent; class BrowserTest extends \Tests\BrowserTestCase { public function test_can_register_a_custom_javascript_endpoint() { Livewire::setScriptRoute(function ($handle) { return Route::get('/custom/livewire.js', function () use ($handle) { return "alert('hi mom')"; }); }); Livewire::visit(new class extends TestComponent {}) ->assertDialogOpened('hi mom') ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/FrontendAssets/UnitTest.php
src/Mechanisms/FrontendAssets/UnitTest.php
<?php namespace Livewire\Mechanisms\FrontendAssets; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Route; use Livewire\Livewire; use Livewire\LivewireManager; use function Livewire\trigger; class UnitTest extends \Tests\TestCase { public function setUp(): void { \Livewire\LivewireManager::$v4 = false; parent::setUp(); } public function tearDown(): void { // Clean up any published assets after each test if (file_exists(public_path('vendor/livewire'))) { File::deleteDirectory(public_path('vendor/livewire')); } parent::tearDown(); } public function test_styles() { $assets = app(FrontendAssets::class); $this->assertFalse($assets->hasRenderedStyles); $this->assertStringStartsWith('<!-- Livewire Styles -->', $assets->styles()); $this->assertStringNotContainsString('data-livewire-style', $assets->styles()); $this->assertStringContainsString('nonce="test" data-livewire-style', $assets->styles(['nonce' => 'test'])); $this->assertTrue($assets->hasRenderedStyles); } public function test_scripts() { $assets = app(FrontendAssets::class); $this->assertFalse($assets->hasRenderedScripts); $scripts = $assets->scripts(); $this->assertStringContainsString('<script src="', $scripts); $this->assertTrue($assets->hasRenderedScripts); } public function test_use_normal_scripts_url_if_app_debug_is_true() { config()->set('app.debug', true); $assets = app(FrontendAssets::class); // Call boot again, as the script route has to be set after the config is set $assets->boot(); $this->assertStringContainsString('livewire.js', $assets->scripts()); } public function test_use_minified_scripts_url_if_app_debug_is_false() { config()->set('app.debug', false); $assets = app(FrontendAssets::class); // Call boot again, as the script route has to be set after the config is set $assets->boot(); $this->assertStringContainsString('livewire.min.js', $assets->scripts()); } public function test_use_normal_scripts_file_if_app_debug_is_true() { config()->set('app.debug', true); $assets = app(FrontendAssets::class); $fileResponse = $assets->returnJavaScriptAsFile(); $this->assertEquals('livewire.js', $fileResponse->getFile()->getFilename()); } public function test_use_minified_scripts_file_if_app_debug_is_false() { config()->set('app.debug', false); $assets = app(FrontendAssets::class); $fileResponse = $assets->returnJavaScriptAsFile(); $this->assertEquals('livewire.min.js', $fileResponse->getFile()->getFilename()); } public function test_if_script_route_has_been_overridden_use_normal_scripts_file_if_app_debug_is_true() { config()->set('app.debug', true); $assets = app(FrontendAssets::class); $assets->setScriptRoute(function ($handle) { return Route::get('/livewire/livewire.js', $handle); }); $response = $this->get('/livewire/livewire.js'); $this->assertEquals('livewire.js', $response->getFile()->getFilename()); } public function test_if_script_route_has_been_overridden_use_minified_scripts_file_if_app_debug_is_false() { config()->set('app.debug', false); $assets = app(FrontendAssets::class); $assets->setScriptRoute(function ($handle) { return Route::get('/livewire/livewire.js', $handle); }); $response = $this->get('/livewire/livewire.js'); $this->assertEquals('livewire.min.js', $response->getFile()->getFilename()); } public function test_flush_state_event_resets_has_rendered() { $assets = app(FrontendAssets::class); $assets->styles(); $assets->scripts(); $this->assertTrue($assets->hasRenderedStyles); $this->assertTrue($assets->hasRenderedScripts); trigger('flush-state'); $this->assertFalse($assets->hasRenderedScripts); $this->assertFalse($assets->hasRenderedStyles); } public function test_js_does_not_prepend_slash_for_url() { $url = 'https://example.com/livewire/livewire.js'; $this->assertStringStartsWith('<script src="'.$url, FrontendAssets::js(['url' => $url])); } public function js_prepends_slash_for_non_url() { $url = 'livewire/livewire.js'; $this->assertStringStartsWith('<script src="/'.$url, FrontendAssets::js(['url' => $url])); } public function test_it_returns_published_assets_url_when_running_serverless() { $assets = app(FrontendAssets::class); Artisan::call('livewire:publish', ['--assets' => true]); config()->set('app.debug', false); config()->set('app.asset_url', 'https://example.com/'); $manager = $this->partialMock(LivewireManager::class, function ($mock) { $mock->shouldReceive('isRunningServerless') ->once() ->andReturn(true); }); $this->app->instance('livewire', $manager); $this->assertStringStartsWith('<script src="https://example.com/vendor/livewire/livewire.min.js', $assets->scripts()); // Clean up published assets if (file_exists(public_path('vendor/livewire'))) { File::deleteDirectory(public_path('vendor/livewire')); } } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleRequests/HandleRequests.php
src/Mechanisms/HandleRequests/HandleRequests.php
<?php namespace Livewire\Mechanisms\HandleRequests; use Illuminate\Support\Facades\Route; use Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets; use Livewire\Mechanisms\HandleRequests\EndpointResolver; use Livewire\Exceptions\PayloadTooLargeException; use Livewire\Exceptions\TooManyComponentsException; use Livewire\Mechanisms\Mechanism; use function Livewire\trigger; class HandleRequests extends Mechanism { protected $updateRoute; function boot() { // Only set it if another provider hasn't already set it.... if (! $this->updateRoute) { app($this::class)->setUpdateRoute(function ($handle) { return Route::post(EndpointResolver::updatePath(), $handle)->middleware('web'); }); } $this->skipRequestPayloadTamperingMiddleware(); } function getUriPrefix() { return EndpointResolver::prefix(); } function getUpdateUri() { return (string) str( route($this->updateRoute->getName(), [], false) )->start('/'); } function skipRequestPayloadTamperingMiddleware() { \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::skipWhen(function () { return $this->isLivewireRequest(); }); \Illuminate\Foundation\Http\Middleware\TrimStrings::skipWhen(function () { return $this->isLivewireRequest(); }); } function setUpdateRoute($callback) { $route = $callback([self::class, 'handleUpdate']); // Append `livewire.update` to the existing name, if any. if (! str($route->getName())->endsWith('livewire.update')) { $route->name('livewire.update'); } $this->updateRoute = $route; } function isLivewireRequest() { return request()->hasHeader('X-Livewire'); } function isLivewireRoute() { // @todo: Rename this back to `isLivewireRequest` once the need for it in tests has been fixed. $route = request()->route(); if (! $route) return false; /* * Check to see if route name ends with `livewire.update`, as if * a custom update route is used and they add a name, then when * we call `->name('livewire.update')` on the route it will * suffix the existing name with `livewire.update`. */ return $route->named('*livewire.update'); } function handleUpdate() { // Check payload size limit... $maxSize = config('livewire.payload.max_size'); if ($maxSize !== null) { $contentLength = request()->header('Content-Length', 0); if ($contentLength > $maxSize) { throw new PayloadTooLargeException($contentLength, $maxSize); } } $requestPayload = request(key: 'components', default: []); // Check max components limit... $maxComponents = config('livewire.payload.max_components'); if ($maxComponents !== null && count($requestPayload) > $maxComponents) { throw new TooManyComponentsException(count($requestPayload), $maxComponents); } $finish = trigger('request', $requestPayload); $requestPayload = $finish($requestPayload); $componentResponses = []; foreach ($requestPayload as $componentPayload) { $snapshot = json_decode($componentPayload['snapshot'], associative: true); $updates = $componentPayload['updates']; $calls = $componentPayload['calls']; [ $snapshot, $effects ] = app('livewire')->update($snapshot, $updates, $calls); $componentResponses[] = [ 'snapshot' => json_encode($snapshot), 'effects' => $effects, ]; } $responsePayload = [ 'components' => $componentResponses, 'assets' => SupportScriptsAndAssets::getAssets(), ]; $finish = trigger('response', $responsePayload); return $finish($responsePayload); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleRequests/BrowserTest.php
src/Mechanisms/HandleRequests/BrowserTest.php
<?php namespace Livewire\Mechanisms\HandleRequests; use Illuminate\Support\Facades\Route; use Livewire\Livewire; class BrowserTest extends \Tests\BrowserTestCase { public function test_can_register_a_custom_update_endpoint() { Livewire::setUpdateRoute(function ($handle) { return Route::post('/custom/update', function () use ($handle) { $response = app(HandleRequests::class)->handleUpdate(); // Override normal Livewire and force the updated count to be "5" instead of 2... $response['components'][0]['effects']['html'] = (string) str($response['components'][0]['effects']['html'])->replace( '<span dusk="output">2</span>', '<span dusk="output">5</span>' ); return $response; })->name('custom'); }); Livewire::visit(new class extends \Livewire\Component { public $count = 1; function inc() { $this->count++; } function render() { return <<<'HTML' <div> <button wire:click="inc" dusk="target">+</button> <span dusk="output">{{ $count }}</span> </div> HTML; } }) ->assertSeeIn('@output', 1) ->waitForLivewire()->click('@target') ->assertSeeIn('@output', 5) ; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleRequests/UnitTest.php
src/Mechanisms/HandleRequests/UnitTest.php
<?php use Illuminate\Http\Request; use Livewire\Mechanisms\HandleRequests\HandleRequests; use Tests\TestCase; class UnitTest extends TestCase { public function test_livewire_can_run_handle_request_without_components_on_payload(): void { $handleRequestsInstance = new HandleRequests(); $request = new Request(); $result = $handleRequestsInstance->handleUpdate($request); $this->assertIsArray($result); $this->assertArrayHasKey('components', $result); $this->assertArrayHasKey('assets', $result); $this->assertIsArray($result['components']); $this->assertEmpty($result['components']); $this->assertIsArray($result['assets']); $this->assertEmpty($result['assets']); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/HandleRequests/EndpointResolver.php
src/Mechanisms/HandleRequests/EndpointResolver.php
<?php namespace Livewire\Mechanisms\HandleRequests; class EndpointResolver { /** * Get the base path prefix for all Livewire endpoints. * * Uses APP_KEY to generate a unique prefix per installation, * making it harder to target Livewire apps with universal scanners. */ public static function prefix(): string { $hash = substr(hash('sha256', config('app.key') . 'livewire-endpoint'), 0, 8); return '/livewire-' . $hash; } /** * Get the path for the update endpoint. */ public static function updatePath(): string { return static::prefix() . '/update'; } /** * Get the path for the JavaScript asset endpoint. */ public static function scriptPath(bool $minified = false): string { $file = $minified ? 'livewire.min.js' : 'livewire.js'; return static::prefix() . '/' . $file; } /** * Get the path for the source map endpoint. */ public static function mapPath(bool $csp = false): string { $file = $csp ? 'livewire.csp.min.js.map' : 'livewire.min.js.map'; return static::prefix() . '/' . $file; } /** * Get the path for the file upload endpoint. */ public static function uploadPath(): string { return static::prefix() . '/upload-file'; } /** * Get the path for the file preview endpoint. */ public static function previewPath(): string { return static::prefix() . '/preview-file/{filename}'; } /** * Get the path for component JavaScript modules. */ public static function componentJsPath(): string { return static::prefix() . '/js/{component}.js'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/Tests/DirectlyAssignComponentParametersAsPropertiesUnitTest.php
src/Mechanisms/Tests/DirectlyAssignComponentParametersAsPropertiesUnitTest.php
<?php namespace Livewire\Mechanisms\Tests; use Livewire\Livewire; class DirectlyAssignComponentParametersAsPropertiesUnitTest extends \Tests\TestCase { public function test_parameters_are_directly_set_as_properties_without_mount_method() { Livewire::test(ComponentWithDirectlyAssignedProperties::class, [ 'foo' => 'bar', 'baz' => 'bob', ])->assertSeeText('barbob'); } public function test_parameters_are_directly_set_as_properties_even_if_mount_method_accepts_them_too() { Livewire::test(ComponentWithDirectlyAssignedPropertiesAndMountMethod::class, [ 'foo' => 'bar', 'baz' => 'bob', ])->assertSeeText('barbobbarbob'); } } class ComponentWithDirectlyAssignedProperties extends \Livewire\Component { public $foo; public $baz; public function render() { return app('view')->make('show-name', [ 'name' => $this->foo.$this->baz, ]); } } class ComponentWithDirectlyAssignedPropertiesAndMountMethod extends \Livewire\Component { public $foo; public $baz; public $fooFromMount; public $bazFromMount; public function mount($foo, $baz) { $this->fooFromMount = $foo; $this->bazFromMount = $baz; } public function render() { return app('view')->make('show-name', [ 'name' => $this->foo.$this->baz.$this->fooFromMount.$this->bazFromMount, ]); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/Tests/LoadBalancerCompatibilityUnitTest.php
src/Mechanisms/Tests/LoadBalancerCompatibilityUnitTest.php
<?php namespace Livewire\Mechanisms\Tests; use Livewire\Livewire; use Livewire\Component; use Tests\TestComponent; class LoadBalancerCompatibilityUnitTest extends \Tests\TestCase { public function test_component_keys_are_deterministic_across_load_balancers() { $component = Livewire::test([new class extends Component { public function render() { return '<div> <livewire:child /> </div>'; } }, 'child' => new class extends TestComponent {} ]); $firstKey = array_keys($component->snapshot['memo']['children'])[0]; // Clear the view cache to simulate blade views being cached on two different servers... \Illuminate\Support\Facades\Artisan::call('view:clear'); $component = Livewire::test([new class extends Component { public function render() { return '<div> <livewire:child /> </div>'; } }, 'child' => new class extends TestComponent {} ]); $secondKey = array_keys($component->snapshot['memo']['children'])[0]; $this->assertEquals($firstKey, $secondKey); } public function test_deterministic_keys_can_still_be_generated_from_blade_strings_not_files() { $contentsA = app('blade.compiler')->compileString(<<<'HTML' <div> <livewire:the-child /> </div> HTML); // Reset any internal key counters... app('livewire')->flushState(); $contentsB = app('blade.compiler')->compileString(<<<'HTML' <div> <livewire:the-child /> </div> HTML); $keyA = str($contentsA)->between('lw-', '-0')->toString(); $keyB = str($contentsB)->between('lw-', '-0')->toString(); $this->assertEquals($keyA, $keyB); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/Tests/CustomUpdateRouteBrowserTest.php
src/Mechanisms/Tests/CustomUpdateRouteBrowserTest.php
<?php namespace Livewire\Mechanisms\Tests; use Livewire\Livewire; use Livewire\Component; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\URL; class CustomUpdateRouteBrowserTest extends \Tests\BrowserTestCase { public static function tweakApplicationHook() { return function () { // This would normally be done in something like middleware URL::defaults(['tenant' => 'custom-tenant']); Livewire::setUpdateRoute(function ($handle) { return Route::post('/{tenant}/livewire/update', $handle)->name('tenant.livewire.update'); }); // Doesn't seem to be needed in real applications, but is needed in tests app('router')->getRoutes()->refreshNameLookups(); Route::prefix('/{tenant}')->group(function () { Route::get('/page', function ($tenant) { return (app('livewire')->new('test'))(); })->name('tenant.page'); }); Livewire::component('test', new class extends Component { public $count = 0; function increment() { $this->count++; } public function render() { return <<<'HTML' <div> <h1 dusk="count">Count: {{ $count }}</h1> <button wire:click="increment" dusk="button">Increment</button> <p>Tenant: {{ request()->route()->parameter('tenant') }}</p> <p>Route: {{ request()->route()->getName() }}</p> </div> HTML; } }); }; } public function test_can_use_a_custom_update_route_with_a_uri_segment() { $this->browse(function (\Laravel\Dusk\Browser $browser) { $browser ->visit('/custom-tenant/page') ->assertSee('Count: 0') ->assertSee('Tenant: custom-tenant') ->assertSee('Route: tenant.page') ->waitForLivewire() ->click('button') ->assertSee('Count: 1') ->assertSee('Tenant: custom-tenant') ->assertSee('Route: tenant.livewire.update'); }); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/Tests/ComponentSkipRenderUnitTest.php
src/Mechanisms/Tests/ComponentSkipRenderUnitTest.php
<?php namespace Livewire\Mechanisms\Tests; use Illuminate\Support\Facades\Route; use Livewire\Component; use Livewire\Livewire; use function Livewire\store; use function Livewire\str; class ComponentSkipRenderUnitTest extends \Tests\TestCase { public function test_component_renders_like_normal() { $component = Livewire::test(ComponentSkipRenderStub::class); $this->assertTrue( str($component->html())->contains([$component->id(), 'foo']) ); } public function test_on_skip_render_render_is_not_called() { $component = Livewire::test(ComponentSkipRenderStub::class); $component->assertSetStrict('skipped', false); $component->call('skip'); $component->assertSetStrict('skipped', true); $this->assertNotNull($component->html()); } public function test_with_skip_render_attribute_render_is_not_called() { $component = Livewire::test(ComponentSkipRenderAttributeStub::class); $component->assertSetStrict('skipped', false); $component->call('skip'); $component->assertSetStrict('skipped', true); $this->assertNotNull($component->html()); } public function test_on_redirect_in_mount_render_is_not_called() { Route::get('/403', ComponentSkipRenderOnRedirectHelperInMountStub::class); $this->get('/403')->assertRedirect('/bar'); } } class ComponentSkipRenderStub extends Component { public $skipped = false; public function skip() { $this->skipped = true; $this->skipRender(); } public function render() { if ($this->skipped) { throw new \RuntimeException('Render should not be called after noop()'); } return app('view')->make('null-view'); } } class ComponentSkipRenderAttributeStub extends Component { public $skipped = false; #[\Livewire\Attributes\Renderless] public function skip() { $this->skipped = true; } public function render() { if ($this->skipped) { throw new \RuntimeException('Render should not be called after noop()'); } return app('view')->make('null-view'); } } class ComponentSkipRenderOnRedirectInMountStub extends Component { public function mount() { store($this)->set('redirect', '/yoyoyo'); $this->skipRender(); $this->redirect('/foo'); } public function render() { throw new \RuntimeException('Render should not be called on redirect'); } } class ComponentSkipRenderOnRedirectHelperInMountStub extends Component { public function mount() { $this->skipRender(); return redirect('/bar'); } public function render() { throw new \RuntimeException('Render should not be called on redirect'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/Tests/LivewireDirectiveUnitTest.php
src/Mechanisms/Tests/LivewireDirectiveUnitTest.php
<?php namespace Livewire\Mechanisms\Tests; use Illuminate\Support\Facades\Artisan; // TODO - Change this to \Tests\TestCase class LivewireDirectiveUnitTest extends \LegacyTests\Unit\TestCase { public function test_component_is_loaded_with_blade_directive() { Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $output = view('render-component', [ 'component' => 'foo', ])->render(); $this->assertStringContainsString('div', $output); } public function test_component_is_loaded_with_blade_directive_by_classname() { Artisan::call('make:livewire', ['name' => 'foo', '--class' => true]); $output = view('render-component', [ 'component' => \App\Livewire\Foo::class, ])->render(); $this->assertStringContainsString('div', $output); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/Tests/InlineBladeTemplatesUnitTest.php
src/Mechanisms/Tests/InlineBladeTemplatesUnitTest.php
<?php namespace Livewire\Mechanisms\Tests; use Livewire\Component; use Livewire\Livewire; class InlineBladeTemplatesUnitTest extends \Tests\TestCase { public function test_renders_inline_blade_template() { Livewire::test(ComponentWithInlineBladeTemplate::class) ->assertSee('foo'); } } class ComponentWithInlineBladeTemplate extends Component { public $name = 'foo'; public function render() { return <<<'blade' <div> <span>{{ $name }}</span> </div> blade; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/ExtendBlade/ExtendedCompilerEngine.php
src/Mechanisms/ExtendBlade/ExtendedCompilerEngine.php
<?php namespace Livewire\Mechanisms\ExtendBlade; use function Livewire\trigger; class ExtendedCompilerEngine extends \Illuminate\View\Engines\CompilerEngine { public function get($path, array $data = []) { if (! ExtendBlade::isRenderingLivewireComponent()) return parent::get($path, $data); $currentComponent = ExtendBlade::currentRendering(); trigger('view:compile', $currentComponent, $path); return parent::get($path, $data); } protected function evaluatePath($__path, $__data) { if (! ExtendBlade::isRenderingLivewireComponent()) { return parent::evaluatePath($__path, $__data); } $obLevel = ob_get_level(); ob_start(); // We'll evaluate the contents of the view inside a try/catch block so we can // flush out any stray output that might get out before an error occurs or // an exception is thrown. This prevents any partial views from leaking. try { $component = ExtendBlade::currentRendering(); \Closure::bind(function () use ($__path, $__data) { extract($__data, EXTR_SKIP); include $__path; }, $component, $component)(); } catch (\Exception|\Throwable $e) { $this->handleViewException($e, $obLevel); } return ltrim(ob_get_clean()); } // Errors thrown while a view is rendering are caught by the Blade // compiler and wrapped in an "ErrorException". This makes Livewire errors // harder to read, AND causes issues like `abort(404)` not actually working. protected function handleViewException(\Throwable $e, $obLevel) { if ($this->shouldBypassExceptionForLivewire($e, $obLevel)) { // This is because there is no "parent::parent::". \Illuminate\View\Engines\PhpEngine::handleViewException($e, $obLevel); return; } parent::handleViewException($e, $obLevel); } public function shouldBypassExceptionForLivewire(\Throwable $e, $obLevel) { $uses = array_flip(class_uses_recursive($e)); return ( // Don't wrap "abort(403)". $e instanceof \Illuminate\Auth\Access\AuthorizationException // Don't wrap "abort(404)". || $e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException // Don't wrap "abort(500)". || $e instanceof \Symfony\Component\HttpKernel\Exception\HttpException // Don't wrap most Livewire exceptions. || isset($uses[\Livewire\Exceptions\BypassViewHandler::class]) ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/ExtendBlade/UnitTest.php
src/Mechanisms/ExtendBlade/UnitTest.php
<?php namespace Livewire\Mechanisms\ExtendBlade; use ErrorException; use Exception; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\View; use Livewire\Component; use Livewire\Exceptions\BypassViewHandler; use Livewire\Livewire; use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Tests\TestComponent; class UnitTest extends \Tests\TestCase { public function test_livewire_only_directives_apply_to_livewire_components_and_not_normal_blade() { Livewire::directive('foo', function ($expression) { return 'bar'; }); $output = Blade::render(' <div>@foo</div> @livewire(\Livewire\Mechanisms\ExtendBlade\ExtendBladeTestComponent::class) <div>@foo</div> '); $this->assertCount(3, explode('@foo', $output)); } public function test_livewire_only_precompilers_apply_to_livewire_components_and_not_normal_blade() { Livewire::precompiler(function ($string) { return preg_replace_callback('/@foo/sm', function ($matches) { return 'bar'; }, $string); }); $output = Blade::render(' <div>@foo</div> @livewire(\Livewire\Mechanisms\ExtendBlade\ExtendBladeTestComponent::class) <div>@foo</div> '); $this->assertCount(3, explode('@foo', $output)); } public function test_this_keyword_will_reference_the_livewire_component_class() { Livewire::test(ComponentForTestingThisKeyword::class) ->assertSee(ComponentForTestingThisKeyword::class); } public function test_this_directive_returns_javascript_component_object_string() { Livewire::test(ComponentForTestingDirectives::class) ->assertDontSee('@this') ->assertSee('window.Livewire.find('); } public function test_this_directive_can_be_used_in_nested_blade_component() { Livewire::test(ComponentForTestingNestedThisDirective::class) ->assertDontSee('@this') ->assertSee('window.Livewire.find('); } public function test_public_property_is_accessible_in_view_via_this() { Livewire::test(PublicPropertiesInViewWithThisStub::class) ->assertSee('Caleb'); } public function test_public_properties_are_accessible_in_view_without_this() { Livewire::test(PublicPropertiesInViewWithoutThisStub::class) ->assertSee('Caleb'); } public function test_protected_property_is_accessible_in_view_via_this() { Livewire::test(ProtectedPropertiesInViewWithThisStub::class) ->assertSee('Caleb'); } public function test_protected_properties_are_not_accessible_in_view_without_this() { Livewire::test(ProtectedPropertiesInViewWithoutThisStub::class) ->assertDontSee('Caleb'); } public function test_normal_errors_thrown_from_inside_a_livewire_view_are_wrapped_by_the_blade_handler() { // Blade wraps thrown exceptions in "ErrorException" by default. $this->expectException(ErrorException::class); Livewire::component('foo', NormalExceptionIsThrownInViewStub::class); View::make('render-component', ['component' => 'foo'])->render(); } public function test_livewire_errors_thrown_from_inside_a_livewire_view_bypass_the_blade_wrapping() { // Exceptions that use the "BypassViewHandler" trait remain unwrapped. $this->expectException(SomeCustomLivewireException::class); Livewire::component('foo', LivewireExceptionIsThrownInViewStub::class); View::make('render-component', ['component' => 'foo'])->render(); } public function test_errors_thrown_by_abort_404_function_are_not_wrapped() { $this->expectException(NotFoundHttpException::class); Livewire::component('foo', Abort404IsThrownInComponentMountStub::class); View::make('render-component', ['component' => 'foo'])->render(); } public function test_errors_thrown_by_abort_500_function_are_not_wrapped() { $this->expectException(HttpException::class); Livewire::component('foo', Abort500IsThrownInComponentMountStub::class); View::make('render-component', ['component' => 'foo'])->render(); } public function test_errors_thrown_by_authorization_exception_function_are_not_wrapped() { $this->expectException(AuthorizationException::class); Livewire::component('foo', AuthorizationExceptionIsThrownInComponentMountStub::class); View::make('render-component', ['component' => 'foo'])->render(); } } class ExtendBladeTestComponent extends Component { public function render() { return '<div>@foo</div>'; } } class ComponentForTestingThisKeyword extends Component { public function render() { return '<div>{{ get_class($this) }}</div>'; } } class ComponentForTestingDirectives extends Component { public function render() { return '<div>@this</div>'; } } class ComponentForTestingNestedThisDirective extends Component { public function render() { return "<div>@component('components.this-directive')@endcomponent</div>"; } } class PublicPropertiesInViewWithThisStub extends Component { public $name = 'Caleb'; public function render() { return app('view')->make('show-name-with-this'); } } class PublicPropertiesInViewWithoutThisStub extends Component { public $name = 'Caleb'; public function render() { return app('view')->make('show-name'); } } class ProtectedPropertiesInViewWithThisStub extends Component { protected $name = 'Caleb'; public function render() { return app('view')->make('show-name-with-this'); } } class ProtectedPropertiesInViewWithoutThisStub extends Component { protected $name = 'Caleb'; public function render() { return app('view')->make('show-name'); } } class SomeCustomLivewireException extends \Exception { use BypassViewHandler; } class NormalExceptionIsThrownInViewStub extends Component { public function render() { return app('view')->make('execute-callback', [ 'callback' => function () { throw new Exception(); }, ]); } } class LivewireExceptionIsThrownInViewStub extends Component { public function render() { return app('view')->make('execute-callback', [ 'callback' => function () { throw new SomeCustomLivewireException(); }, ]); } } class Abort404IsThrownInComponentMountStub extends TestComponent { public function mount() { abort(404); } } class Abort500IsThrownInComponentMountStub extends TestComponent { public function mount() { abort(500); } } class AuthorizationExceptionIsThrownInComponentMountStub extends TestComponent { public function mount() { throw new AuthorizationException(); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/ExtendBlade/ExtendBlade.php
src/Mechanisms/ExtendBlade/ExtendBlade.php
<?php namespace Livewire\Mechanisms\ExtendBlade; use Illuminate\Support\Facades\Blade; use Livewire\Mechanisms\Mechanism; use function Livewire\invade; use function Livewire\on; class ExtendBlade extends Mechanism { protected $directives = []; protected $precompilers = []; protected $renderCounter = 0; protected static $livewireComponents = []; function startLivewireRendering($component) { static::$livewireComponents[] = $component; } function endLivewireRendering() { array_pop(static::$livewireComponents); } static function currentRendering() { return end(static::$livewireComponents); } static function isRenderingLivewireComponent() { return ! empty(static::$livewireComponents); } function boot() { Blade::directive('this', fn() => "window.Livewire.find('{{ \$_instance->getId() }}')"); on('render', function ($target, $view) { $this->startLivewireRendering($target); $undo = $this->livewireifyBladeCompiler(); $this->renderCounter++; return function ($html) use ($view, $undo, $target) { $this->endLivewireRendering(); $this->renderCounter--; if ($this->renderCounter === 0) { $undo(); } return $html; }; }); // This is a custom view engine that gets used when rendering // Livewire views. Things like letting certain exceptions bubble // to the handler, and registering custom directives like: "@this". app()->make('view.engine.resolver')->register('blade', function () { return new ExtendedCompilerEngine(app('blade.compiler')); }); app()->singleton(DeterministicBladeKeys::class); // Reset this singleton between tests and Octane requests... on('flush-state', function () { app()->singleton(DeterministicBladeKeys::class); static::$livewireComponents = []; }); // We're using "precompiler" as a hook for the point in time when // Laravel compiles a Blade view... app('blade.compiler')->precompiler(function ($value) { app(DeterministicBladeKeys::class)->hookIntoCompile(app('blade.compiler'), $value); return $value; }); } function livewireOnlyDirective($name, $handler) { $this->directives[$name] = $handler; } function livewireOnlyPrecompiler($handler) { $this->precompilers[] = $handler; } function livewireifyBladeCompiler() { $removals = []; if ($this->renderCounter === 0) { $customDirectives = app('blade.compiler')->getCustomDirectives(); $precompilers = invade(app('blade.compiler'))->precompilers; foreach ($this->directives as $name => $handler) { if (! isset($customDirectives[$name])) { $customDirectives[$name] = $handler; invade(app('blade.compiler'))->customDirectives = $customDirectives; $removals[] = function () use ($name) { $customDirectives = app('blade.compiler')->getCustomDirectives(); unset($customDirectives[$name]); invade(app('blade.compiler'))->customDirectives = $customDirectives; }; } } foreach ($this->precompilers as $handler) { if (array_search($handler, $precompilers) === false) { array_unshift($precompilers, $handler); invade(app('blade.compiler'))->precompilers = $precompilers; $removals[] = function () use ($handler) { $precompilers = invade(app('blade.compiler'))->precompilers; $index = array_search($handler, $precompilers); if ($index === false) return; unset($precompilers[$index]); invade(app('blade.compiler'))->precompilers = $precompilers; }; } } } return function () use ($removals) { while ($removals) array_pop($removals)(); }; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Mechanisms/ExtendBlade/DeterministicBladeKeys.php
src/Mechanisms/ExtendBlade/DeterministicBladeKeys.php
<?php namespace Livewire\Mechanisms\ExtendBlade; use Illuminate\View\Compilers\BladeCompiler; class DeterministicBladeKeys { protected $countersByPath = []; protected $currentPathHash; public function generate() { if (! $this->currentPathHash) { throw new \Exception('Latest compiled component path not found.'); } $path = $this->currentPathHash; $count = $this->counter(); // $key = "lw-[hash of Blade view path]-[current @livewire directive count]" return 'lw-' . $this->currentPathHash . '-' . $count; } public function counter() { if (! isset($this->countersByPath[$this->currentPathHash])) { $this->countersByPath[$this->currentPathHash] = 0; } return $this->countersByPath[$this->currentPathHash]++; } public function hookIntoCompile(BladeCompiler $compiler, $viewContent) { $path = $compiler->getPath(); // If there is no path this means this Blade is being compiled // with ->compileString(...) directly instead of ->compile() // therefore we'll generate a hash of the contents instead if ($path === null) { $path = $viewContent; } $this->currentPathHash = crc32($path); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/NonPublicComponentMethodCall.php
src/Exceptions/NonPublicComponentMethodCall.php
<?php namespace Livewire\Exceptions; class NonPublicComponentMethodCall extends \Exception { use BypassViewHandler; public function __construct($method) { parent::__construct('Component method not found: ['.$method.']'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/TooManyComponentsException.php
src/Exceptions/TooManyComponentsException.php
<?php namespace Livewire\Exceptions; class TooManyComponentsException extends \Exception { public function __construct(int $count, int $maxComponents) { $message = "Too many components in a single request ({$count}). " . "Maximum allowed is {$maxComponents}. " . "You can configure this limit in config/livewire.php under 'payload.max_components'."; parent::__construct($message); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/PropertyNotFoundException.php
src/Exceptions/PropertyNotFoundException.php
<?php namespace Livewire\Exceptions; class PropertyNotFoundException extends \Exception { use BypassViewHandler; public function __construct($property, $component) { parent::__construct( "Property [\${$property}] not found on component: [{$component}]" ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/RootTagMissingFromViewException.php
src/Exceptions/RootTagMissingFromViewException.php
<?php namespace Livewire\Exceptions; class RootTagMissingFromViewException extends \Exception { use BypassViewHandler; public function __construct() { parent::__construct( 'Livewire encountered a missing root tag when trying to render a ' . "component. \n When rendering a Blade view, make sure it contains a root HTML tag." ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/ComponentAttributeMissingOnDynamicComponentException.php
src/Exceptions/ComponentAttributeMissingOnDynamicComponentException.php
<?php namespace Livewire\Exceptions; class ComponentAttributeMissingOnDynamicComponentException extends \Exception { use BypassViewHandler; public function __construct() { parent::__construct('Dynamic component tag is missing component attribute.'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/MissingRulesException.php
src/Exceptions/MissingRulesException.php
<?php namespace Livewire\Exceptions; class MissingRulesException extends \Exception { use BypassViewHandler; public function __construct($instance) { $class = $instance::class; parent::__construct( "Missing [\$rules/rules()] property/method on: [{$class}]." ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/ComponentNotFoundException.php
src/Exceptions/ComponentNotFoundException.php
<?php namespace Livewire\Exceptions; class ComponentNotFoundException extends \Exception { use BypassViewHandler; }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/MaxNestingDepthExceededException.php
src/Exceptions/MaxNestingDepthExceededException.php
<?php namespace Livewire\Exceptions; class MaxNestingDepthExceededException extends \Exception { public function __construct(string $path, int $maxDepth) { $message = "Property path [{$path}] exceeds the maximum nesting depth of {$maxDepth} levels. " . "You can configure this limit in config/livewire.php under 'payload.max_nesting_depth'."; parent::__construct($message); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/BypassViewHandler.php
src/Exceptions/BypassViewHandler.php
<?php namespace Livewire\Exceptions; trait BypassViewHandler { // }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/EventHandlerDoesNotExist.php
src/Exceptions/EventHandlerDoesNotExist.php
<?php namespace Livewire\Exceptions; class EventHandlerDoesNotExist extends \Exception { public function __construct(public readonly string $eventName) { parent::__construct('Handler for event ' . $eventName . ' does not exist'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/PublicPropertyNotFoundException.php
src/Exceptions/PublicPropertyNotFoundException.php
<?php namespace Livewire\Exceptions; class PublicPropertyNotFoundException extends \Exception { use BypassViewHandler; public function __construct($property, $component) { parent::__construct( "Unable to set component data. Public property [\${$property}] not found on component: [{$component}]" ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/PayloadTooLargeException.php
src/Exceptions/PayloadTooLargeException.php
<?php namespace Livewire\Exceptions; class PayloadTooLargeException extends \Exception { public function __construct(int $size, int $maxSize) { $sizeKb = round($size / 1024); $maxKb = round($maxSize / 1024); $message = "Livewire request payload is too large ({$sizeKb}KB). " . "Maximum allowed size is {$maxKb}KB. " . "You can configure this limit in config/livewire.php under 'payload.max_size'."; parent::__construct($message); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/LivewireReleaseTokenMismatchException.php
src/Exceptions/LivewireReleaseTokenMismatchException.php
<?php namespace Livewire\Exceptions; use Symfony\Component\HttpKernel\Exception\HttpException; class LivewireReleaseTokenMismatchException extends HttpException { public function __construct() { parent::__construct( 419, "Livewire detected a release token mismatch. \n". "This happens when a user's browser session has been invalidated by a new deployment." ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/TooManyCallsException.php
src/Exceptions/TooManyCallsException.php
<?php namespace Livewire\Exceptions; class TooManyCallsException extends \Exception { public function __construct(int $count, int $maxCalls) { $message = "Too many method calls in a single request ({$count}). " . "Maximum allowed is {$maxCalls}. " . "You can configure this limit in config/livewire.php under 'payload.max_calls'."; parent::__construct($message); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Exceptions/MethodNotFoundException.php
src/Exceptions/MethodNotFoundException.php
<?php namespace Livewire\Exceptions; class MethodNotFoundException extends \Exception { use BypassViewHandler; public function __construct($method) { parent::__construct( "Unable to call component method. Public method [{$method}] not found on component" ); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Performance/RenderPerformanceBenchmarkTest.php
src/Performance/RenderPerformanceBenchmarkTest.php
<?php namespace Livewire\Performance; use Livewire\Component; use Tests\TestCase; class RenderPerformanceBenchmarkTest extends TestCase { protected int $iterations = 1000; protected array $results = []; public function test_benchmark_simple_component_render() { $this->benchmark('Simple Component Render', function () { app('livewire')->mount(SimpleBenchmarkComponent::class); }); } public function test_benchmark_component_with_properties() { $this->benchmark('Component with Properties', function () { app('livewire')->mount(ComponentWithProperties::class, ['name' => 'John', 'count' => 42]); }); } public function test_benchmark_component_with_computed_property() { $this->benchmark('Component with Computed Property', function () { app('livewire')->mount(ComponentWithComputed::class); }); } public function test_benchmark_component_with_template() { $this->benchmark('Component with Blade Template', function () { app('livewire')->mount(ComponentWithTemplate::class); }); } public function test_benchmark_component_with_lifecycle_hooks() { $this->benchmark('Component with Lifecycle Hooks', function () { app('livewire')->mount(ComponentWithHooks::class); }); } protected function benchmark(string $name, callable $callback) { // Warm up for ($i = 0; $i < 10; $i++) { $callback(); } // Run benchmark $start = microtime(true); $memoryStart = memory_get_usage(); for ($i = 0; $i < $this->iterations; $i++) { $callback(); } $elapsed = microtime(true) - $start; $memoryUsed = memory_get_usage() - $memoryStart; // Calculate metrics $avgTime = ($elapsed / $this->iterations) * 1000; // Convert to ms $rendersPerSecond = $this->iterations / $elapsed; $avgMemory = $memoryUsed / $this->iterations; // Store results $this->results[$name] = [ 'total_time' => $elapsed, 'avg_time_ms' => $avgTime, 'renders_per_second' => $rendersPerSecond, 'memory_used' => $memoryUsed, 'avg_memory_bytes' => $avgMemory, ]; // Output results echo "\n"; echo "================================================\n"; echo "Benchmark: {$name}\n"; echo "================================================\n"; echo "Iterations: " . number_format($this->iterations) . "\n"; echo "Total Time: " . number_format($elapsed, 4) . "s\n"; echo "Avg Time: " . number_format($avgTime, 4) . "ms\n"; echo "Renders/Second: " . number_format($rendersPerSecond, 2) . "\n"; echo "Memory Used: " . $this->formatBytes($memoryUsed) . "\n"; echo "Avg Memory/Render: " . $this->formatBytes($avgMemory) . "\n"; echo "================================================\n"; // Assert reasonable performance (adjust these thresholds as needed) $this->assertLessThan( 10.0, $elapsed, "{$name}: {$this->iterations} renders took {$elapsed}s (expected < 10s)" ); return $this->results[$name]; } protected function formatBytes(int $bytes): string { $units = ['B', 'KB', 'MB', 'GB']; $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= (1 << (10 * $pow)); return round($bytes, 2) . ' ' . $units[$pow]; } public function tearDown(): void { if (!empty($this->results)) { echo "\n"; echo "================================================\n"; echo "BENCHMARK SUMMARY\n"; echo "================================================\n"; foreach ($this->results as $name => $metrics) { echo sprintf( "%-35s %8.2fms %8.0f r/s\n", $name . ':', $metrics['avg_time_ms'], $metrics['renders_per_second'] ); } echo "================================================\n"; } parent::tearDown(); } } // Benchmark Components class SimpleBenchmarkComponent extends Component { public function render() { return '<div>Simple Component</div>'; } } class ComponentWithProperties extends Component { public $name = ''; public $count = 0; public function mount($name, $count) { $this->name = $name; $this->count = $count; } public function render() { return <<<'blade' <div> <span>Name: {{ $name }}</span> <span>Count: {{ $count }}</span> </div> blade; } } class ComponentWithComputed extends Component { public $items = []; public function mount() { $this->items = range(1, 10); } #[\Livewire\Attributes\Computed] public function total() { return array_sum($this->items); } public function render() { return <<<'blade' <div> <span>Total: {{ $this->total }}</span> </div> blade; } } class ComponentWithTemplate extends Component { public $title = 'Benchmark Title'; public $description = 'This is a benchmark description with some text.'; public $items = []; public function mount() { $this->items = ['Item 1', 'Item 2', 'Item 3']; } public function render() { return <<<'blade' <div> <h1>{{ $title }}</h1> <p>{{ $description }}</p> <ul> @foreach($items as $item) <li>{{ $item }}</li> @endforeach </ul> </div> blade; } } class ComponentWithHooks extends Component { public $data = []; public function mount() { $this->data = ['key' => 'value']; } public function boot() { // Lifecycle hook } public function booted() { // Lifecycle hook } public function hydrate() { // Lifecycle hook } public function render() { return '<div>{{ json_encode($data) }}</div>'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/UnitTest.php
src/Finder/UnitTest.php
<?php namespace Livewire\Finder; use Livewire\Finder\Fixtures\SelfNamedComponent\SelfNamedComponent; use Livewire\Finder\Fixtures\Nested\NestedComponent; use Livewire\Finder\Fixtures\IndexComponent\Index; use Livewire\Finder\Fixtures\FinderTestClassComponent; use Livewire\Component; class UnitTest extends \Tests\TestCase { public function test_can_add_and_resolve_component_named_class() { $finder = new Finder(); $finder->addComponent('test-component', class: FinderTestClassComponent::class); $name = $finder->normalizeName(FinderTestClassComponent::class); $this->assertEquals('test-component', $name); $class = $finder->resolveClassComponentClassName('test-component'); $this->assertEquals(FinderTestClassComponent::class, $class); } public function test_can_add_and_resolve_component_unnamed_class() { $finder = new Finder(); $finder->addComponent(class: FinderTestClassComponent::class); $name = $finder->normalizeName(FinderTestClassComponent::class); $this->assertEquals('lw' . crc32(FinderTestClassComponent::class), $name); $class = $finder->resolveClassComponentClassName($name); $this->assertEquals(FinderTestClassComponent::class, $class); } public function test_can_add_and_resolve_component_named_anonymous_class() { $finder = new Finder(); $finder->addComponent('test-component', class: $obj = new class extends Component { public function render() { return '<div>Finder Location Test Component</div>'; } }); $name = $finder->normalizeName($obj); $this->assertEquals('test-component', $name); $class = $finder->resolveClassComponentClassName('test-component'); $this->assertEquals($obj::class, $class); } public function test_can_add_and_resolve_component_unnamed_anonymous_class() { $finder = new Finder(); $finder->addComponent(class: $obj = new class extends Component { public function render() { return '<div>Finder Location Test Component</div>'; } }); $name = $finder->normalizeName($obj); $this->assertEquals('lw' . crc32($obj::class), $name); $class = $finder->resolveClassComponentClassName($name); $this->assertEquals($obj::class, $class); } public function test_can_add_and_resolve_component_named_view_based() { $finder = new Finder(); $finder->addComponent('test-component', viewPath: __DIR__ . '/Fixtures/finder-test-single-file-component.blade.php'); $name = $finder->normalizeName('test-component'); $this->assertEquals('test-component', $name); $path = $finder->resolveSingleFileComponentPath('test-component'); $this->assertEquals(__DIR__ . '/Fixtures/finder-test-single-file-component.blade.php', $path); } public function test_can_add_and_resolve_component_named_view_based_with_zap() { $finder = new Finder(); $finder->addComponent('test-component-with-zap', viewPath: __DIR__ . '/Fixtures/⚡︎finder-test-single-file-component-with-zap.blade.php'); $name = $finder->normalizeName('test-component-with-zap'); $this->assertEquals('test-component-with-zap', $name); $path = $finder->resolveSingleFileComponentPath('test-component-with-zap'); $this->assertEquals(__DIR__ . '/Fixtures/⚡︎finder-test-single-file-component-with-zap.blade.php', $path); } public function test_can_add_and_resolve_component_named_multi_file() { $finder = new Finder(); $finder->addComponent('multi-file-test', viewPath: __DIR__ . '/Fixtures/multi-file-test-component'); $name = $finder->normalizeName('multi-file-test'); $this->assertEquals('multi-file-test', $name); $path = $finder->resolveMultiFileComponentPath('multi-file-test'); $this->assertEquals(__DIR__ . '/Fixtures/multi-file-test-component', $path); } public function test_can_add_and_resolve_component_named_multi_file_with_zap() { $finder = new Finder(); $finder->addComponent('multi-file-zap', viewPath: __DIR__ . '/Fixtures/⚡︎multi-file-zap-component'); $name = $finder->normalizeName('multi-file-zap'); $this->assertEquals('multi-file-zap', $name); $path = $finder->resolveMultiFileComponentPath('multi-file-zap'); $this->assertEquals(__DIR__ . '/Fixtures/⚡︎multi-file-zap-component', $path); } public function test_can_resolve_location_class_component() { $finder = new Finder(); $finder->addLocation(classNamespace: 'Livewire\Finder\Fixtures'); $name = $finder->normalizeName(FinderTestClassComponent::class); $this->assertEquals('finder-test-class-component', $name); $class = $finder->resolveClassComponentClassName($name); $this->assertEquals('Livewire\Finder\Fixtures\FinderTestClassComponent', $class); } public function test_can_resolve_location_class_nested_component() { $finder = new Finder(); $finder->addLocation(classNamespace: 'Livewire\Finder\Fixtures'); $name = $finder->normalizeName(NestedComponent::class); $this->assertEquals('nested.nested-component', $name); $class = $finder->resolveClassComponentClassName($name); $this->assertEquals('Livewire\Finder\Fixtures\Nested\NestedComponent', $class); } public function test_can_resolve_location_class_index_component() { $finder = new Finder(); $finder->addLocation(classNamespace: 'Livewire\Finder\Fixtures'); $name = $finder->normalizeName(Index::class); $this->assertEquals('index-component', $name); $class = $finder->resolveClassComponentClassName($name); $this->assertEquals('Livewire\Finder\Fixtures\IndexComponent\Index', $class); } public function test_can_resolve_location_class_self_named_component() { $finder = new Finder(); $finder->addLocation(classNamespace: 'Livewire\Finder\Fixtures'); $name = $finder->normalizeName(SelfNamedComponent::class); $this->assertEquals('self-named-component', $name); $class = $finder->resolveClassComponentClassName($name); $this->assertEquals('Livewire\Finder\Fixtures\SelfNamedComponent\SelfNamedComponent', $class); } public function test_can_resolve_location_single_file_component() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('finder-test-single-file-component'); $this->assertEquals('finder-test-single-file-component', $name); $path = $finder->resolveSingleFileComponentPath('finder-test-single-file-component'); $this->assertEquals(__DIR__ . '/Fixtures/finder-test-single-file-component.blade.php', $path); } public function test_can_resolve_location_single_file_component_with_zap() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('finder-test-single-file-component-with-zap'); $this->assertEquals('finder-test-single-file-component-with-zap', $name); $path = $finder->resolveSingleFileComponentPath('finder-test-single-file-component-with-zap'); $this->assertEquals(__DIR__ . '/Fixtures/⚡finder-test-single-file-component-with-zap.blade.php', $path); } public function test_can_resolve_location_index_single_file_component() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('nested-view-based'); $this->assertEquals('nested-view-based', $name); $path = $finder->resolveSingleFileComponentPath('nested-view-based'); $this->assertEquals(__DIR__ . '/Fixtures/nested-view-based/index.blade.php', $path); } public function test_can_resolve_location_self_named_single_file_component() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('self-named-component'); $this->assertEquals('self-named-component', $name); $path = $finder->resolveSingleFileComponentPath('self-named-component'); $this->assertEquals(__DIR__ . '/Fixtures/self-named-component/self-named-component.blade.php', $path); } public function test_can_resolve_location_nested_index_single_file_component() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('nested-view-based.index-named-component'); $this->assertEquals('nested-view-based.index-named-component', $name); $path = $finder->resolveSingleFileComponentPath('nested-view-based.index-named-component'); $this->assertEquals(__DIR__ . '/Fixtures/nested-view-based/index-named-component/index.blade.php', $path); } public function test_can_resolve_location_nested_self_named_single_file_component() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('nested-view-based.self-named-component'); $this->assertEquals('nested-view-based.self-named-component', $name); $path = $finder->resolveSingleFileComponentPath('nested-view-based.self-named-component'); $this->assertEquals(__DIR__ . '/Fixtures/nested-view-based/self-named-component/self-named-component.blade.php', $path); } public function test_can_resolve_location_multi_file_component() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('multi-file-test-component'); $this->assertEquals('multi-file-test-component', $name); $path = $finder->resolveMultiFileComponentPath('multi-file-test-component'); $this->assertEquals(__DIR__ . '/Fixtures/multi-file-test-component', $path); } public function test_can_resolve_location_multi_file_index_component() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('multi-file-index'); $this->assertEquals('multi-file-index', $name); $path = $finder->resolveMultiFileComponentPath('multi-file-index'); $this->assertEquals(__DIR__ . '/Fixtures/multi-file-index', $path); } public function test_can_resolve_location_multi_file_self_named_component() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('multi-file-self-named'); $this->assertEquals('multi-file-self-named', $name); $path = $finder->resolveMultiFileComponentPath('multi-file-self-named'); $this->assertEquals(__DIR__ . '/Fixtures/multi-file-self-named', $path); } public function test_can_resolve_location_multi_file_component_with_zap() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('multi-file-zap-component'); $this->assertEquals('multi-file-zap-component', $name); $path = $finder->resolveMultiFileComponentPath('multi-file-zap-component'); $this->assertEquals(__DIR__ . '/Fixtures/⚡multi-file-zap-component', $path); } public function test_it_does_not_resolve_a_multi_file_component_for_a_nested_single_file_self_named_component() { $finder = new Finder(); $finder->addLocation(viewPath: __DIR__ . '/Fixtures'); $name = $finder->normalizeName('nested-view-based.self-named-component'); $this->assertEquals('nested-view-based.self-named-component', $name); $path = $finder->resolveMultiFileComponentPath('nested-view-based.self-named-component'); $this->assertEquals('', $path); } public function test_can_resolve_namespace_class_component() { $finder = new Finder(); $finder->addNamespace('admin', classNamespace: 'Livewire\Finder\Fixtures'); $class = $finder->resolveClassComponentClassName('admin::finder-test-class-component'); $this->assertEquals('Livewire\Finder\Fixtures\FinderTestClassComponent', $class); } public function test_can_resolve_namespace_class_nested_component() { $finder = new Finder(); $finder->addNamespace('admin', classNamespace: 'Livewire\Finder\Fixtures'); $class = $finder->resolveClassComponentClassName('admin::nested.nested-component'); $this->assertEquals('Livewire\Finder\Fixtures\Nested\NestedComponent', $class); } public function test_can_resolve_namespace_class_index_component() { $finder = new Finder(); $finder->addNamespace('admin', classNamespace: 'Livewire\Finder\Fixtures'); $class = $finder->resolveClassComponentClassName('admin::index-component'); $this->assertEquals('Livewire\Finder\Fixtures\IndexComponent\Index', $class); } public function test_can_resolve_namespace_class_self_named_component() { $finder = new Finder(); $finder->addNamespace('admin', classNamespace: 'Livewire\Finder\Fixtures'); $class = $finder->resolveClassComponentClassName('admin::self-named-component'); $this->assertEquals('Livewire\Finder\Fixtures\SelfNamedComponent\SelfNamedComponent', $class); } public function test_returns_null_for_namespace_unknown_component() { $finder = new Finder(); $finder->addNamespace('admin', classNamespace: 'Livewire\Finder\Fixtures'); $class = $finder->resolveClassComponentClassName('unknown::some-component'); $this->assertNull($class); } public function test_can_resolve_namespace_single_file_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveSingleFileComponentPath('admin::finder-test-single-file-component'); $this->assertEquals(__DIR__ . '/Fixtures/finder-test-single-file-component.blade.php', $path); } public function test_can_resolve_namespace_single_file_component_with_zap() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveSingleFileComponentPath('admin::finder-test-single-file-component-with-zap'); $this->assertEquals(__DIR__ . '/Fixtures/⚡finder-test-single-file-component-with-zap.blade.php', $path); } public function test_can_resolve_namespace_index_single_file_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveSingleFileComponentPath('admin::nested-view-based'); $this->assertEquals(__DIR__ . '/Fixtures/nested-view-based/index.blade.php', $path); } public function test_can_resolve_namespace_self_named_single_file_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveSingleFileComponentPath('admin::self-named-component'); $this->assertEquals(__DIR__ . '/Fixtures/self-named-component/self-named-component.blade.php', $path); } public function test_can_resolve_namespace_nested_index_single_file_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveSingleFileComponentPath('admin::nested-view-based.index-named-component'); $this->assertEquals(__DIR__ . '/Fixtures/nested-view-based/index-named-component/index.blade.php', $path); } public function test_can_resolve_namespace_nested_self_named_single_file_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveSingleFileComponentPath('admin::nested-view-based.self-named-component'); $this->assertEquals(__DIR__ . '/Fixtures/nested-view-based/self-named-component/self-named-component.blade.php', $path); } public function test_returns_null_for_namespace_unknown_single_file_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveSingleFileComponentPath('unknown::some-component'); $this->assertNull($path); } public function test_can_resolve_namespace_multi_file_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveMultiFileComponentPath('admin::multi-file-test-component'); $this->assertEquals(__DIR__ . '/Fixtures/multi-file-test-component', $path); } public function test_can_resolve_namespace_multi_file_component_with_zap() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveMultiFileComponentPath('admin::multi-file-zap-component'); $this->assertEquals(__DIR__ . '/Fixtures/⚡multi-file-zap-component', $path); } public function test_can_resolve_namespace_multi_file_index_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveMultiFileComponentPath('admin::multi-file-index'); $this->assertEquals(__DIR__ . '/Fixtures/multi-file-index', $path); } public function test_can_resolve_namespace_multi_file_self_named_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveMultiFileComponentPath('admin::multi-file-self-named'); $this->assertEquals(__DIR__ . '/Fixtures/multi-file-self-named', $path); } public function test_returns_null_for_namespace_unknown_multi_file_component() { $finder = new Finder(); $finder->addNamespace('admin', viewPath: __DIR__ . '/Fixtures'); $path = $finder->resolveMultiFileComponentPath('unknown::some-component'); $this->assertNull($path); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Finder.php
src/Finder/Finder.php
<?php namespace Livewire\Finder; use Livewire\Component; class Finder { private const ZAP = "\u{26A1}"; private const ZAP_VS15 = "\u{26A1}\u{FE0E}"; private const ZAP_VS16 = "\u{26A1}\u{FE0F}"; protected $classLocations = []; protected $viewLocations = []; protected $classNamespaces = []; protected $viewNamespaces = []; protected $classComponents = []; protected $viewComponents = []; public function addComponent($name = null, $viewPath = null, $class = null): void { // Support $name being used a single argument for class-based components... if ($name !== null && $class === null && $viewPath === null) { $class = $name; $name = null; } if (is_object($class)) { $class = get_class($class); } // Support $class being used a single named argument for class-based components... if ($name === null && $class !== null && $viewPath === null) { $name = $this->generateHashName($class); } if ($name == null && $class === null && $viewPath !== null) { throw new \Exception('You must provide a name when registering a single/multi-file component'); } if ($name) { if ($class !== null) $this->classComponents[$name] = $this->normalizeClassName($class); elseif ($viewPath !== null) $this->viewComponents[$name] = $viewPath; } } public function addLocation($viewPath = null, $classNamespace = null): void { if ($classNamespace !== null) $this->classLocations[] = $this->normalizeClassName($classNamespace); if ($viewPath !== null) $this->viewLocations[] = $viewPath; } public function addNamespace($namespace, $viewPath = null, $classNamespace = null, $classPath = null, $classViewPath = null): void { if ($classNamespace !== null) { $this->classNamespaces[$namespace] = [ 'classNamespace' => $this->normalizeClassName($classNamespace), 'classPath' => $classPath, 'classViewPath' => $classViewPath, ]; } if ($viewPath !== null) $this->viewNamespaces[$namespace] = $viewPath; } public function getClassNamespace(string $namespace): array { return $this->classNamespaces[$namespace]; } public function normalizeName($nameComponentOrClass): ?string { if (is_object($nameComponentOrClass)) { $nameComponentOrClass = get_class($nameComponentOrClass); } $class = null; if (is_subclass_of($class = $nameComponentOrClass, Component::class)) { if (is_object($class)) { $class = get_class($class); } $name = array_search($class, $this->classComponents); if ($name !== false) { return $name; } $hashOfClass = $this->generateHashName($class); $name = $this->classComponents[$hashOfClass] ?? false; if ($name !== false) { return $name; } $result = $this->generateNameFromClass($class); return $result; } return $nameComponentOrClass; } public function parseNamespaceAndName($name): array { if (str_contains($name, '::')) { [$namespace, $componentName] = explode('::', $name, 2); return [$namespace, $componentName]; } return [null, $name]; } public function resolveClassComponentClassName($name): ?string { [$namespace, $componentName] = $this->parseNamespaceAndName($name); // Check if the component is in a namespace... if ($namespace !== null) { if (isset($this->classNamespaces[$namespace]['classNamespace'])) { $class = $this->generateClassFromName($componentName, [$this->classNamespaces[$namespace]['classNamespace']]); if (class_exists($class)) { return $class; } } return null; } // Check if the component is explicitly registered... if (isset($this->classComponents[$name])) { return $this->classComponents[$name]; } // Check if the component is in a class location... $class = $this->generateClassFromName($name, $this->classLocations); if (! class_exists($class)) { return null; } return $class; } public function resolveSingleFileComponentPath($name): ?string { $path = null; [$namespace, $componentName] = $this->parseNamespaceAndName($name); if ($namespace !== null) { if (isset($this->viewNamespaces[$namespace])) { $locations = [$this->viewNamespaces[$namespace]]; } else { return null; } } else { $componentName = $name; // Check if the component is explicitly registered... if (isset($this->viewComponents[$name])) { $path = $this->viewComponents[$name]; if (! is_dir($path) && file_exists($path) && $this->hasValidSingleFileComponentSource($path)) { return $path; } } $locations = $this->viewLocations; } // Check for a component inside locations... foreach ($locations as $location) { $location = $this->normalizeLocation($location); $segments = explode('.', $componentName); $lastSegment = last($segments); $leadingSegments = implode('.', array_slice($segments, 0, -1)); $trailingPath = str_replace('.', '/', $lastSegment); $leadingPath = $leadingSegments ? str_replace('.', '/', $leadingSegments) . '/' : ''; $paths = [ 'singleFileWithZap' => $location . '/' . $leadingPath . self::ZAP . $trailingPath . '.blade.php', 'singleFileWithZapVariation15' => $location . '/' . $leadingPath . self::ZAP_VS15 . $trailingPath . '.blade.php', 'singleFileWithZapVariation16' => $location . '/' . $leadingPath . self::ZAP_VS16 . $trailingPath . '.blade.php', 'singleFileAsIndexWithZap' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP . 'index.blade.php', 'singleFileAsIndexWithZapVariation15' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP_VS15 . 'index.blade.php', 'singleFileAsIndexWithZapVariation16' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP_VS16 . 'index.blade.php', 'singleFileAsSelfNamedWithZap' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP . $trailingPath . '.blade.php', 'singleFileAsSelfNamedWithZapVariation15' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP_VS15 . $trailingPath . '.blade.php', 'singleFileAsSelfNamedWithZapVariation16' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP_VS16 . $trailingPath . '.blade.php', 'singleFile' => $location . '/' . $leadingPath . $trailingPath . '.blade.php', 'singleFileAsIndex' => $location . '/' . $leadingPath . $trailingPath . '/index.blade.php', 'singleFileAsSelfNamed' => $location . '/' . $leadingPath . $trailingPath . '/' . $trailingPath . '.blade.php', ]; foreach ($paths as $filePath) { if (! is_dir($filePath) && file_exists($filePath) && $this->hasValidSingleFileComponentSource($filePath)) { return $filePath; } } } return $path; } public function resolveMultiFileComponentPath($name): ?string { $path = null; [$namespace, $componentName] = $this->parseNamespaceAndName($name); if ($namespace !== null) { if (isset($this->viewNamespaces[$namespace])) { $locations = [$this->viewNamespaces[$namespace]]; } else { return null; } } else { $componentName = $name; // Check if the component is explicitly registered... if (isset($this->viewComponents[$name])) { $path = $this->viewComponents[$name]; if (is_dir($path)) { return $path; } } $locations = $this->viewLocations; } // Check for a multi-file component inside locations... foreach ($locations as $location) { $location = $this->normalizeLocation($location); $segments = explode('.', $componentName); $lastSegment = last($segments); $leadingSegments = implode('.', array_slice($segments, 0, -1)); $trailingPath = str_replace('.', '/', $lastSegment); $leadingPath = $leadingSegments ? str_replace('.', '/', $leadingSegments) . '/' : ''; $dirs = [ 'multiFileWithZap' => $location . '/' . $leadingPath . self::ZAP . $trailingPath, 'multiFileWithZapVariation15' => $location . '/' . $leadingPath . self::ZAP_VS15 . $trailingPath, 'multiFileWithZapVariation16' => $location . '/' . $leadingPath . self::ZAP_VS16 . $trailingPath, 'multiFileAsIndexWithZap' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP . 'index', 'multiFileAsIndexWithZapVariation15' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP_VS15 . 'index', 'multiFileAsIndexWithZapVariation16' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP_VS16 . 'index', 'multiFileAsSelfNamedWithZap' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP . $trailingPath, 'multiFileAsSelfNamedWithZapVariation15' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP_VS15 . $trailingPath, 'multiFileAsSelfNamedWithZapVariation16' => $location . '/' . $leadingPath . $trailingPath . '/' . self::ZAP_VS16 . $trailingPath, 'multiFile' => $location . '/' . $leadingPath . $trailingPath, 'multiFileAsIndex' => $location . '/' . $leadingPath . $trailingPath . '/index', 'multiFileAsSelfNamed' => $location . '/' . $leadingPath . $trailingPath . '/' . $trailingPath, ]; foreach ($dirs as $dir) { $baseName = basename($dir); $fileBaseName = str_contains($baseName, 'index') ? 'index' : $baseName; // Strip out the emoji from folder name to derive the file name... $fileBaseName = preg_replace('/' . self::ZAP . '[\x{FE0E}\x{FE0F}]?/u', '', $fileBaseName); if ( is_dir($dir) && $this->hasValidMultiFileComponentSource($dir, $fileBaseName) ) { return $dir; } } } return $path; } protected function generateClassFromName($name, $classNamespaces = []): string { $baseClass = collect(str($name)->explode('.')) ->map(fn ($segment) => (string) str($segment)->studly()) ->join('\\'); foreach ($classNamespaces as $classNamespace) { $class = '\\' . $classNamespace . '\\' . $baseClass; $indexClass = '\\' . $classNamespace . '\\' . $baseClass . '\\Index'; $lastSegment = last(explode('.', $name)); $selfNamedClass = '\\' . $classNamespace . '\\' . $baseClass . '\\' . str($lastSegment)->studly(); if (class_exists($class)) return $this->normalizeClassName($class); if (class_exists($indexClass)) return $this->normalizeClassName($indexClass); if (class_exists($selfNamedClass)) return $this->normalizeClassName($selfNamedClass); } return $this->normalizeClassName($baseClass); } protected function generateNameFromClass($class): string { $class = str_replace( ['/', '\\'], '.', $this->normalizePath($class) ); $fullName = str(collect(explode('.', $class)) ->map(fn ($i) => \Illuminate\Support\Str::kebab($i)) ->implode('.')); if ($fullName->startsWith('.')) { $fullName = $fullName->substr(1); } // If using an index component in a sub folder, remove the '.index' so the name is the subfolder name... if ($fullName->endsWith('.index')) { $fullName = $fullName->replaceLast('.index', ''); } // If using a self-named component in a sub folder, remove the '.[last_segment]' so the name is the subfolder name... $segments = explode('.', $fullName); $lastSegment = end($segments); $secondToLastSegment = $segments[count($segments) - 2]; if ($secondToLastSegment && $lastSegment === $secondToLastSegment) { $fullName = $fullName->replaceLast('.' . $lastSegment, ''); } $classNamespaces = collect($this->classNamespaces) ->map(fn ($classNamespace) => $classNamespace['classNamespace']) ->merge($this->classLocations) ->toArray(); foreach ($classNamespaces as $classNamespace) { $namespace = str_replace( ['/', '\\'], '.', $this->normalizePath($classNamespace) ); $namespace = collect(explode('.', $namespace)) ->map(fn ($i) => \Illuminate\Support\Str::kebab($i)) ->implode('.'); if ($fullName->startsWith($namespace)) { return (string) $fullName->substr(strlen($namespace) + 1); } } return (string) $fullName; } protected function normalizeClassName(string $className): string { return trim($className, '\\'); } protected function generateHashName(string $className): string { return 'lw' . crc32($this->normalizeClassName($className)); } protected function normalizePath(string $path): string { return trim(trim($path, '/'), '\\'); } protected function normalizeLocation(string $location): string { return rtrim($location, '/'); } protected function hasValidSingleFileComponentSource(string $filePath): bool { // Read the file contents $contents = file_get_contents($filePath); if ($contents === false) { return false; } // Light touch check: Look for the pattern that indicates an SFC // Pattern: <?php followed by 'new' and 'class' (with potential attributes/newlines between) // This distinguishes SFCs from regular Blade views return preg_match('/\<\?php.*new\s+.*class/s', $contents) === 1; } protected function hasValidMultiFileComponentSource(string $dir, string $fileBaseName): bool { return file_exists($dir . '/' . $fileBaseName . '.php') && file_exists($dir . '/' . $fileBaseName . '.blade.php'); } public function resolveSingleFileComponentPathForCreation(string $name): string { [$namespace, $componentName] = $this->parseNamespaceAndName($name); // Get the appropriate location if ($namespace !== null && isset($this->viewNamespaces[$namespace])) { $location = $this->viewNamespaces[$namespace]; } else { // Use the first configured component location or fallback $location = $this->viewLocations[0] ?? resource_path('views/components'); } $location = $this->normalizeLocation($location); // Parse the component name into path segments $segments = explode('.', $componentName ?? $name); $lastSegment = array_pop($segments); $leadingPath = !empty($segments) ? implode('/', $segments) . '/' : ''; // Determine if emoji should be used (get from config) $useEmoji = config('livewire.make_command.emoji', true); $prefix = $useEmoji ? self::ZAP : ''; // Build the file path return $location . '/' . $leadingPath . $prefix . $lastSegment . '.blade.php'; } public function resolveMultiFileComponentPathForCreation(string $name): string { [$namespace, $componentName] = $this->parseNamespaceAndName($name); // Get the appropriate location if ($namespace !== null && isset($this->viewNamespaces[$namespace])) { $location = $this->viewNamespaces[$namespace]; } else { // Use the first configured component location or fallback $location = $this->viewLocations[0] ?? resource_path('views/components'); } $location = $this->normalizeLocation($location); // Parse the component name into path segments $segments = explode('.', $componentName ?? $name); $lastSegment = array_pop($segments); $leadingPath = !empty($segments) ? implode('/', $segments) . '/' : ''; // Determine if emoji should be used (get from config) $useEmoji = config('livewire.make_command.emoji', true); $prefix = $useEmoji ? self::ZAP : ''; // Build the directory path return $location . '/' . $leadingPath . $prefix . $lastSegment; } public function resolveClassComponentFilePaths(string $name): ?array { [$namespace, $componentName] = $this->parseNamespaceAndName($name); // Parse the component name into segments $segments = explode('.', $componentName ?? $name); // Convert segments to StudlyCase for class name $classSegments = array_map(fn($segment) => str($segment)->studly()->toString(), $segments); $className = implode('\\', $classSegments); // Convert segments to kebab-case for view name $viewSegments = array_map(fn($segment) => str($segment)->kebab()->toString(), $segments); $viewName = implode('.', $viewSegments); if ($namespace !== null) { if (! isset($this->classNamespaces[$namespace])) { return null; } $classNamespaceDetails = $this->classNamespaces[$namespace]; $configuredClassPath = $classNamespaceDetails['classPath']; $configuredViewPath = $classNamespaceDetails['classViewPath']; } else { $configuredClassPath = config('livewire.class_path', app_path('Livewire')); $configuredViewPath = config('livewire.view_path', resource_path('views/livewire')); } // Build the class file path $classPath = $configuredClassPath . '/' . str_replace('\\', '/', $className) . '.php'; // Build the view file path $viewPath = $configuredViewPath . '/' . str_replace('.', '/', $viewName) . '.blade.php'; return [ 'class' => $classPath, 'view' => $viewPath, ]; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/FinderTestClassComponent.php
src/Finder/Fixtures/FinderTestClassComponent.php
<?php namespace Livewire\Finder\Fixtures; use Livewire\Component; class FinderTestClassComponent extends Component { public function render() { return '<div>Finder Location Test Component</div>'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/⚡finder-test-single-file-component-with-zap.blade.php
src/Finder/Fixtures/⚡finder-test-single-file-component-with-zap.blade.php
<?php use Livewire\Component; new class extends Component { // }; ?> <div>Finder Test Single File Component With Zap</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/finder-test-single-file-component.blade.php
src/Finder/Fixtures/finder-test-single-file-component.blade.php
<?php use Livewire\Component; new class extends Component { // }; ?> <div>Finder Test Single File Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/self-named-component/self-named-component.blade.php
src/Finder/Fixtures/self-named-component/self-named-component.blade.php
<?php use Livewire\Component; new class extends Component { // }; ?> <div>Finder Test Single File Index Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/⚡multi-file-zap-component/multi-file-zap-component.php
src/Finder/Fixtures/⚡multi-file-zap-component/multi-file-zap-component.php
<?php use Livewire\Component; class MultiFileZapComponent extends Component { public function render() { return view('livewire.multi-file-zap-component'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/⚡multi-file-zap-component/multi-file-zap-component.blade.php
src/Finder/Fixtures/⚡multi-file-zap-component/multi-file-zap-component.blade.php
<div>Finder Test Multi-file Zap Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/multi-file-self-named/multi-file-self-named.blade.php
src/Finder/Fixtures/multi-file-self-named/multi-file-self-named.blade.php
<div>Finder Test Multi-file Self-named Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/multi-file-self-named/multi-file-self-named.php
src/Finder/Fixtures/multi-file-self-named/multi-file-self-named.php
<?php use Livewire\Component; class MultiFileSelfNamed extends Component { public function render() { return view('livewire.multi-file-self-named'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/nested-view-based/index.blade.php
src/Finder/Fixtures/nested-view-based/index.blade.php
<?php use Livewire\Component; new class extends Component { // }; ?> <div>Finder Test Single File Index Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/nested-view-based/self-named-component/self-named-component.blade.php
src/Finder/Fixtures/nested-view-based/self-named-component/self-named-component.blade.php
<?php use Livewire\Component; new class extends Component { // }; ?> <div>Finder Test Nested Self Named Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/nested-view-based/index/index.blade.php
src/Finder/Fixtures/nested-view-based/index/index.blade.php
<div>Finder Test Multi-file Index Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/nested-view-based/index/index.php
src/Finder/Fixtures/nested-view-based/index/index.php
<?php use Livewire\Component; new class extends Component { // };
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/nested-view-based/index-named-component/index.blade.php
src/Finder/Fixtures/nested-view-based/index-named-component/index.blade.php
<?php use Livewire\Component; new class extends Component { // }; ?> <div>Finder Test Nested Index Named Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/IndexComponent/Index.php
src/Finder/Fixtures/IndexComponent/Index.php
<?php namespace Livewire\Finder\Fixtures\IndexComponent; use Livewire\Component; class Index extends Component { public function render() { return '<div>Finder Location Test Component</div>'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/Nested/NestedComponent.php
src/Finder/Fixtures/Nested/NestedComponent.php
<?php namespace Livewire\Finder\Fixtures\Nested; use Livewire\Component; class NestedComponent extends Component { public function render() { return '<div>Finder Location Test Component</div>'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/multi-file-index/index.blade.php
src/Finder/Fixtures/multi-file-index/index.blade.php
<div>Finder Test Multi-file Index Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/multi-file-index/index.php
src/Finder/Fixtures/multi-file-index/index.php
<?php use Livewire\Component; class MultiFileIndex extends Component { public function render() { return view('livewire.multi-file-index'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/multi-file-test-component/multi-file-test-component.blade.php
src/Finder/Fixtures/multi-file-test-component/multi-file-test-component.blade.php
<div>Finder Test Multi-file Component</div>
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/multi-file-test-component/multi-file-test-component.php
src/Finder/Fixtures/multi-file-test-component/multi-file-test-component.php
<?php use Livewire\Component; class MultiFileTestComponent extends Component { public function render() { return view('livewire.multi-file-test-component'); } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false
livewire/livewire
https://github.com/livewire/livewire/blob/f2f58e728b8e834780be780ee727a85e9513d56b/src/Finder/Fixtures/SelfNamedComponent/SelfNamedComponent.php
src/Finder/Fixtures/SelfNamedComponent/SelfNamedComponent.php
<?php namespace Livewire\Finder\Fixtures\SelfNamedComponent; use Livewire\Component; class SelfNamedComponent extends Component { public function render() { return '<div>Finder Location Test Component</div>'; } }
php
MIT
f2f58e728b8e834780be780ee727a85e9513d56b
2026-01-04T15:02:34.292445Z
false